// Rebuild public/quack_audio.wasm from the vendored Rust clone. The clone is
// git-ignored; the small stage API the browser needs is kept as a patch, so a
// fresh clone needs it applied first:
//
//   git -C duck-pond apply audio/duck-pond-stage.patch
//   npm run audio
//
// The wasm itself is committed, so this is only needed when the Rust source or
// the bridge changes.
import { execFileSync } from 'node:child_process';
import { copyFileSync, existsSync, readFileSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const root = dirname(dirname(fileURLToPath(import.meta.url)));
const duck = join(root, 'duck-pond');
const wasm = join(duck, 'target', 'wasm32-unknown-unknown', 'release', 'duck_pond_web.wasm');
const out = join(root, 'public', 'quack_audio.wasm');
const patch = join(root, 'audio', 'duck-pond-stage.patch');

if (!existsSync(join(duck, 'Cargo.toml'))) {
	console.error(`no duck-pond clone at ${duck}`);
	console.error('clone https://github.com/celphase/duck-pond there first');
	process.exit(1);
}
const source = readFileSync(join(duck, 'src', 'scene.rs'), 'utf8');
const bridge = readFileSync(join(duck, 'web', 'src', 'lib.rs'), 'utf8');
if (!source.includes('pub struct Stage') || !bridge.includes('quack_audio_new')) {
	console.error('the clone does not have the quack stage API yet; apply the patch first:');
	console.error(`  git -C "${duck}" apply "${patch}"`);
	process.exit(1);
}

const cargo = process.platform === 'win32' ? 'cargo.exe' : 'cargo';
execFileSync(cargo, ['build', '--release', '--target', 'wasm32-unknown-unknown', '-p', 'duck-pond-web'], {
	cwd: duck,
	stdio: 'inherit',
});
copyFileSync(wasm, out);
console.log(`built public/quack_audio.wasm (${(statSync(out).size / 1024).toFixed(0)} KiB)`);