import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';

const root = new URL('../', import.meta.url);

test('web PK4 central directories are cached without replacing payload I/O', async () => {
  const [patch, build, runtimeTest, harness, pkg] = await Promise.all([
    readFile(new URL('port/native/patches/0014-cache-web-pk4-central-directory.patch', root), 'utf8'),
    readFile(new URL('tools/build-wasm.sh', root), 'utf8'),
    readFile(new URL('tools/test-zip-cache.sh', root), 'utf8'),
    readFile(new URL('tests/native/unzip-cache-harness.cpp', root), 'utf8'),
    readFile(new URL('package.json', root), 'utf8')
  ]);

  assert.match(patch, /#ifdef __EMSCRIPTEN__/);
  assert.match(patch, /unzlocal_CacheCentralDirectory/);
  assert.match(patch, /stream = fmemopen/);
  assert.match(patch, /cache->references\+\+/);
  assert.match(patch, /--s->central_dir_cache->references == 0/);
  assert.match(patch, /unzSetCurrentFileInfoPosition\( file->z, pakFile->pos \)/);
  assert.match(patch, /unzOpenCurrentFile\( file->z \) != UNZ_OK/);
  assert.doesNotMatch(patch, /^\+\s*memcpy\( zfi, pak->handle, sizeof\(unz_s\) \)/m);
  assert.doesNotMatch(patch, /pfile_in_zip_read_info->file=central_file/);
  assert.match(build, /0014-cache-web-pk4-central-directory\.patch/);
  assert.match(build, /grep -Fq 'unzlocal_CacheCentralDirectory'/);
  assert.match(runtimeTest, /-fsanitize=address/);
  assert.match(runtimeTest, /-fsanitize=undefined/);
  assert.doesNotMatch(runtimeTest, /-fsanitize=address,undefined/);
  assert.match(runtimeTest, /-fno-pie -no-pie -fsanitize=address/);
  assert.match(runtimeTest, /timeout --signal=TERM --kill-after=2s 30s/);
  assert.match(runtimeTest, /ulimit -f 2048/);
  assert.match(runtimeTest, /fixture-sfx\.zip/);
  assert.match(harness, /unzReOpen\( path, first \)/);
  assert.match(harness, /unzClose\( original \)/);
  assert.match(harness, /unzSetCurrentFileInfoPosition/);
  assert.equal(JSON.parse(pkg).scripts['test:zip-cache'], 'tools/test-zip-cache.sh');
});
