import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';

const root = fileURLToPath(new URL('./', import.meta.url));
const source = `${root}bsd-source`;
const sdk = `${root}emsdk/upstream/emscripten`;
const output = `${root}bsd-build`;
const revision = 'ce5fdeb1ccd9db288950faa21fd09c42c0a59bbb';
const actualRevision = spawnSync('git', ['-C', source, 'rev-parse', 'HEAD'], { encoding: 'utf8' });
if (actualRevision.status !== 0 || actualRevision.stdout.trim() !== revision) throw new Error('Unexpected BSD fork source revision');
const patch = `${root}bsd-quantize-status.patch`;
const patchSha256 = '159a336fe49f417da9f0a768ae5374fd0c388487ea9d65dbf5f60bc3425728d4';
const baseSourceSha256 = 'bb8b96e83d5c9c0eb3841ca48d71e2d36ba08a3a2969646a0c043c6d8fb0ecda';
const patchedSourceSha256 = 'b19c74a2f4b64b416db53ab97c5d551c27d97c634bcabdaea958687afe06fca0';
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
if (digest(await readFile(patch)) !== patchSha256) throw new Error('Unexpected quantizer patch');
if (digest(await readFile(`${source}/libimagequant.c`)) === baseSourceSha256) {
	const applied = spawnSync('patch', ['--batch', '-p1', '-i', patch], { cwd: source, stdio: 'inherit' });
	if (applied.status !== 0) throw new Error('Quantizer error propagation patch failed');
}
if (digest(await readFile(`${source}/libimagequant.c`)) !== patchedSourceSha256) throw new Error('Unexpected patched quantizer source');
await mkdir(output, { recursive: true });
const flags = ['-std=c99', '-O3', '-flto', '-DNDEBUG=1', '-DUSE_SSE=0', '-I', source,
	`${root}bsd-png.c`, ...['blur', 'libimagequant', 'mediancut', 'mempool', 'nearest', 'pam', 'viter'].map(name => `${source}/${name}.c`),
	'--use-port=libpng', '-sMODULARIZE=1', '-sEXPORT_ES6=1', '-sENVIRONMENT=web,worker,node',
	'-sALLOW_MEMORY_GROWTH=1', '-sMAXIMUM_MEMORY=2147483648', '-sSTACK_SIZE=1048576',
	'-sFILESYSTEM=0', '-sDYNAMIC_EXECUTION=0',
	'-sEXPORTED_FUNCTIONS=["_malloc","_free","_encode","_output_pointer","_output_length","_output_failed","_output_release"]',
	'-sEXPORTED_RUNTIME_METHODS=["HEAPU8"]',
	'-o', `${output}/bsd-png.mjs`];
const result = spawnSync(`${sdk}/emcc`, flags, { stdio: 'inherit' });
if (result.status !== 0) process.exit(result.status ?? 1);
const assets = [];
for (const name of ['bsd-png.mjs', 'bsd-png.wasm']) {
	const bytes = await readFile(`${output}/${name}`);
	assets.push({ name, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
}
const compiler = spawnSync(`${sdk}/emcc`, ['--version'], { encoding: 'utf8' }).stdout;
await writeFile(`${output}/manifest.json`, JSON.stringify({
	revision, source: 'https://github.com/lovell/libimagequant', license: 'BSD-2-Clause plus historical notices',
	patch: { file: 'bsd-quantize-status.patch', sha256: patchSha256, baseSourceSha256, patchedSourceSha256, purpose: 'Preserve quality-floor and allocation failures; never report success with a null quantization result.' },
	compiler, emsdkRelease: 'f6264d4a4dd9ba24a9f0a5702835a44d1463de13',
	libpng: '1.6.58', zlib: '1.3.2', flags, assets, threads: false, simd: false
}, null, 2) + '\n');
console.log(JSON.stringify(assets, null, 2));
