import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');

test('the WebAssembly build disables Emscripten 6.0.2 growable ArrayBuffers', () => {
  const build = fs.readFileSync(path.join(root, 'tools/build-wasm.sh'), 'utf8');
  const patch = fs.readFileSync(
    path.join(root, 'port/native/patches/0026-disable-growable-arraybuffers.patch'),
    'utf8'
  );

  assert.match(build, /0026-disable-growable-arraybuffers\.patch/);
  assert.match(patch, /'-sGROWABLE_ARRAYBUFFERS=0'/);
  assert.match(build, /grep -Fq -- '-sGROWABLE_ARRAYBUFFERS=0'/);
});

test('frozen SP and MP glue use fixed ArrayBuffers between memory grows', () => {
  for (const variant of ['sp', 'mp']) {
    const source = fs.readFileSync(path.join(root, `engine/openq4-${variant}.mjs`), 'utf8');
    assert.doesNotMatch(source, /wasmMemory\.toResizableBuffer\(\)/, `${variant} enables resizable memory`);
    assert.match(
      source,
      /function getMemoryBuffer\(\)\s*\{\s*return wasmMemory\.buffer;\s*\}/,
      `${variant} does not expose the ordinary WebAssembly memory buffer`
    );
  }
});
