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)), '..');
const patchName = '0030-use-rgba8-web-light-textures.patch';

function patchList(source, variable) {
  const body = source.match(new RegExp(`${variable}=\\(([\\s\\S]*?)\\n\\)`));
  assert.ok(body, `missing ${variable}`);
  return [...body[1].matchAll(/(\d{4}-[^/"']+\.patch)/g)].map((match) => match[1]);
}

test('WebAssembly light textures use RGBA8 while native keeps RGB565', () => {
  const patch = fs.readFileSync(path.join(root, 'port/native/patches', patchName), 'utf8');
  const lightCase = patch.match(/case TD_LIGHT:[\s\S]*?break;/);

  assert.ok(lightCase, 'patch does not change the TD_LIGHT format selection');
  assert.match(lightCase[0], /#if defined\( __EMSCRIPTEN__ \)/);
  assert.match(lightCase[0], /opts\.format = FMT_RGBA8;/);
  assert.match(lightCase[0], /#else\s*\n\+?\s*opts\.format = FMT_RGB565;/);
  assert.match(lightCase[0], /#endif/);
});

test('the RGBA8 light-texture patch is web-only and included in the source offer', () => {
  const wasmBuild = fs.readFileSync(path.join(root, 'tools/build-wasm.sh'), 'utf8');
  const nativeBuild = fs.readFileSync(path.join(root, 'tools/build-native.sh'), 'utf8');
  const sourceOffer = fs.readFileSync(path.join(root, 'tools/stage-source-offer.sh'), 'utf8');

  assert.ok(patchList(wasmBuild, 'OPENQ4_PATCH_FILES').includes(patchName));
  assert.ok(patchList(sourceOffer, 'OPENQ4_PATCH_FILES').includes(patchName));
  assert.ok(!patchList(nativeBuild, 'OPENQ4_PATCH_FILES').includes(patchName));
  assert.ok(!patchList(wasmBuild, 'GAMELIBS_PATCH_FILES').includes(patchName));
  assert.match(wasmBuild, /WebGL 2 has no GL_UNPACK_SWAP_BYTES support/);
});
