#!/usr/bin/env node
/* Offline gate for "The Game That May Never End".
 * Run from the repo root:  node research/the-game-that-may-never-end/verify-the-game-that-may-never-end.mjs
 * Node 22, no dependencies, no network. Prints one line per assertion and
 * exits non-zero on any FAIL. */

import { createHash } from 'node:crypto';
import { readFile, mkdtemp, rm } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { spawnSync } from 'node:child_process';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const DIR = 'public/strata/the-game-that-may-never-end';
const SLUG = 'the-game-that-may-never-end';

let n = 0;
let failures = 0;
function check(name, ok, detail) {
  n++;
  if (!ok) failures++;
  const line = `${ok ? 'PASS' : 'FAIL'} ${String(n).padStart(3, '0')}  ${name}${detail ? ' :: ' + detail : ''}`;
  console.log(line);
  return ok;
}
function control(name, ok, detail) {
  if (!ok) failures++;
  console.log(`${ok ? 'PASS' : 'FAIL'} CTRL   ${name}${detail ? ' :: ' + detail : ''}`);
}
function skip(name, detail) {
  console.log(`SKIP   ${name}${detail ? ' :: ' + detail : ''}`);
}

const sha256hex = (bytes) => createHash('sha256').update(bytes).digest('hex');

/* ---------------------------------------------------------------- */
async function main() {
  const t0 = Date.now();

  /* 1. compile-free load of the shipped binary */
  const wasmPath = path.join(ROOT, DIR, 'engine.wasm');
  if (!existsSync(wasmPath)) {
    check('engine.wasm exists and instantiates', false,
          'missing: the pipeline compiles engine.c; run it, then re-run this verifier');
    finish();
    return;
  }
  const wasmBytes = await readFile(wasmPath);
  let mod = null;
  let exportsOk = false;
  try {
    mod = await WebAssembly.compile(wasmBytes);
    const x = new WebAssembly.Instance(mod, {}).exports;
    const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'aw_state', 'aw_state_len', 'memory'];
    exportsOk = need.every((k) => k in x);
    check('engine.wasm instantiates with the full ABI', exportsOk,
          need.filter((k) => !(k in x)).join(',') || 'all exports present');
  } catch (e) {
    check('engine.wasm instantiates with the full ABI', false, e.message);
  }
  if (!mod || !exportsOk) { finish(); return; }

  /* 2. hash against the manifest the pipeline wrote */
  let manifest = null;
  try {
    manifest = await import(pathToFileURL(path.join(ROOT, DIR, 'manifest.js')));
    const digest = sha256hex(wasmBytes);
    check('sha256(engine.wasm) equals manifest WASM_SHA256',
          typeof manifest.WASM_SHA256 === 'string' &&
          digest === manifest.WASM_SHA256.toLowerCase(),
          digest.slice(0, 16) + '...');
  } catch (e) {
    check('sha256(engine.wasm) equals manifest WASM_SHA256', false, 'manifest.js unreadable: ' + e.message);
  }

  /* 3. reproducible build, with an honest skip */
  await reproducibleBuild(manifest);

  /* shared modules */
  await import(pathToFileURL(path.join(ROOT, 'public/_kit/deep.js')));
  const AW = globalThis.AW;
  const plan = await import(pathToFileURL(path.join(ROOT, DIR, 'plan.js')));
  const ref = await import(pathToFileURL(path.join(ROOT, DIR, 'reference.js')));
  const full = { ...plan, engine: { module: mod }, reference: ref };

  /* 4. the battery: both implementations, identical fingerprints */
  let rows = [];
  try {
    const st = await AW.deep.selftest(full);
    rows = st.rows;
    check('battery: engine and reference agree on every row',
          st.agree && rows.length === plan.battery.length,
          rows.map((r) => (r.agree ? 'ok' : 'MISMATCH')).join(' '));
    // A battery's rows need not be pairwise distinct: the mandatory full-size check recomputes
    // the same instance under a DIFFERENT DECOMPOSITION, so where that row sits in the battery
    // it agrees by construction. What makes a battery non-trivial is reaching more than one
    // instance; coinciding rows are reported rather than punished.
    const fps = rows.map((r) => r.wasm);
    const nDistinct = new Set(fps).size;
    check(`battery: exercises ${nDistinct} distinct instance(s) across ${fps.length} rows`, nDistinct >= 2,
          nDistinct < fps.length ? `${fps.length - nDistinct} row(s) agree across a different decomposition` : `${nDistinct} distinct fingerprints`);
  } catch (e) {
    check('battery: engine and reference agree on every row', false, e.message);
  }

  /* 5. the control on the control */
  try {
    const broken = plan.breakReference(ref);
    check('breakReference returns a different object', broken !== ref);
    const ctl = await AW.deep.control(full);
    check('broken reference is CAUGHT by the battery', ctl.passed,
          `caught ${ctl.caught} of ${ctl.of} rows`);
  } catch (e) {
    check('breakReference returns a different object', false, e.message);
    check('broken reference is CAUGHT by the battery', false, e.message);
  }

  /* planted objects: the unmodified engine must measure doctored INPUT.
   * These plants earned their keep once already: they caught a turn-order bug
   * (no alternation between obligations) that the engine and the reference
   * SHARED, and which the battery therefore could never see. See FIX-NOTE.md. */
  try {
    const inst = AW.deep.instantiate(mod);
    const sp = plan.shortGamePlant();
    inst.init(1, 100000);
    inst.putState(sp.state);
    const c1 = inst.chunk(0, 0, 1);
    const v1 = new DataView(c1.out.buffer);
    const eMax = v1.getUint32(0, true), eCap = v1.getUint32(4, true), eViol = v1.getUint32(8, true);
    ref.init(1, 100000);
    ref.putState(sp.state);
    const r1 = ref.chunk(0, 0, 1);
    const rv1 = new DataView(r1.out.buffer);
    check('planted short deal: engine measures exactly 5 tricks, finished, no violations',
          eMax === 5 && eCap === 0 && eViol === 0,
          `engine max=${eMax} capped=${eCap} viol=${eViol}`);
    check('planted short deal: reference independently measures the same',
          rv1.getUint32(0, true) === eMax && rv1.getUint32(4, true) === eCap);

    const cp = plan.cyclePlant(1000);
    inst.init(1, cp.cap);
    inst.putState(cp.state);
    const c2 = inst.chunk(0, 0, 1);
    const v2 = new DataView(c2.out.buffer);
    ref.init(1, cp.cap);
    ref.putState(cp.state);
    const r2 = ref.chunk(0, 0, 1);
    const rv2 = new DataView(r2.out.buffer);
    check('planted cycling deal: engine hits the cap and reports no finish',
          v2.getUint32(4, true) === 1 && v2.getUint32(0, true) === 0 && v2.getUint32(12, true) === 1,
          `capped=${v2.getUint32(4, true)} max=${v2.getUint32(0, true)}`);
    check('planted cycling deal: reference independently hits the cap too',
          rv2.getUint32(4, true) === 1 && rv2.getUint32(0, true) === 0);

    /* A cap is a timeout, not a proof of non-termination. Prove the cycle:
     * the game is deterministic, so if the EXACT ordered state (both hands in
     * order, plus the leader) after trick 5 equals the state after trick 1,
     * the four-trick block repeats forever and no cap can ever be reached
     * legitimately. This is the positive witness for the page's headline
     * claim that the game CAN fail to terminate.
     *
     * The replay MUST use exactly the bytes the engine is handed: the deck is
     * taken from the plant's state buffer and cut to the slot's DECLARED
     * length. An earlier revision of this assertion passed plan.cycleDeck()'s
     * whole 52-byte array instead; its 46 unused trailing slots are zero-
     * filled, and card 0 is an Ace, so the reference silently dealt a 52-card
     * pack carrying 46 extra Aces and the states compared belonged to a deal
     * nobody had traced. Reading the deck out of the plant state makes that
     * divergence impossible by construction. */
    {
      const cps = cp.state;
      const dlen = cps[16 + 52] || 52;
      const six = Array.from(cps.subarray(16, 16 + dlen));
      const t1 = ref.playDeck(six, 1000000, ref.PEN_RULE_M, 1);
      const t5 = ref.playDeck(six, 1000000, ref.PEN_RULE_M, 5);
      const same = t5.halted === 1 &&
        t1.h0.join(',') === t5.h0.join(',') &&
        t1.h1.join(',') === t5.h1.join(',') &&
        t1.lead === t5.lead;
      check('planted cycling deal: state after trick 5 equals state after trick 1, a PROVED period-4 cycle (not a timeout)',
            same,
            `deck length ${dlen}; after trick 1: P0=[${t1.h0}] P1=[${t1.h1}] lead=P${t1.lead}` +
            (same ? ' ; after trick 5: identical'
                  : ` ; after trick 5: P0=[${t5.h0}] P1=[${t5.h1}] lead=P${t5.lead}`));
      /* and the engine agrees the deal is unfinishable far past one period */
      const inst2 = AW.deep.instantiate(mod);
      inst2.init(1, 20000);
      inst2.putState(cp.state);
      const c3 = inst2.chunk(0, 0, 1);
      const v3 = new DataView(c3.out.buffer);
      check('planted cycling deal: engine still unfinished at a 20,000-trick cap (5,000 periods deep)',
            v3.getUint32(4, true) === 1 && v3.getUint32(0, true) === 0,
            `capped=${v3.getUint32(4, true)} max=${v3.getUint32(0, true)}`);
    }
  } catch (e) {
    check('planted short deal: engine measures exactly 5 tricks, finished, no violations', false, e.message);
    check('planted short deal: reference independently measures the same', false, e.message);
    check('planted cycling deal: engine hits the cap and reports no finish', false, e.message);
    check('planted cycling deal: reference independently hits the cap too', false, e.message);
  }

  /* 6. THE FULL-SIZE CHECK, run for real: two decompositions of the same
   *    seed set must produce byte-identical summaries. 2^20 deals each. */
  const FS_CHUNKS_A = 64, FS_P0_A = 16384;
  const FS_CHUNKS_B = 32, FS_P0_B = 32768;
  const FS_CAP = 20000;
  const FS_TOTAL = FS_CHUNKS_A * FS_P0_A;
  let accA = null, accB = null;
  try {
    const ta = Date.now();
    accA = runInline(AW, mod, plan, FS_CHUNKS_A, FS_P0_A, FS_CAP);
    accB = runInline(AW, mod, plan, FS_CHUNKS_B, FS_P0_B, FS_CAP);
    const secs = ((Date.now() - ta) / 1000).toFixed(1);
    const fa = plan.fingerprint(accA), fb = plan.fingerprint(accB);
    check('full size: two decompositions (64x16384 vs 32x32768) agree exactly',
          fa === fb && accA.deals === FS_TOTAL,
          `${FS_TOTAL.toLocaleString('en-US')} deals per decomposition, ${secs}s`);
    check('full size: zero invariant violations across every deal',
          accA.viol === 0 && accB.viol === 0,
          `violations A=${accA.viol} B=${accB.viol}`);
    check('full size: the search finished at least one deal',
          accA.max > 0 && accA.capped < accA.deals,
          `longest finished=${accA.max} tricks, capped=${accA.capped}`);
  } catch (e) {
    check('full size: two decompositions (64x16384 vs 32x32768) agree exactly', false, e.message);
  }

  /* cross-method: the record itself, replayed by the naive reference */
  if (accA && accA.max > 0) {
    try {
      const best = accA.best;
      const rr = ref.playSeed(best, FS_CAP, false);
      const inst = AW.deep.instantiate(mod);
      inst.init(1, FS_CAP);
      const c = inst.chunk(0, Number(best), 1);
      const engineSingle = new DataView(c.out.buffer).getUint32(0, true);
      check('record cross-method: reference replay of the record seed matches the engine',
            rr.finished && rr.tricks === engineSingle && Number(best) < FS_TOTAL,
            `seed ${best.toString(16)}: reference ${rr.tricks} tricks, engine ${engineSingle} tricks`);
    } catch (e) {
      check('record cross-method: reference replay of the record seed matches the engine', false, e.message);
    }
  }

  /* 7. every fixed fact the PAGE states, recomputed and matched */
  try {
    const html = await readFile(path.join(ROOT, DIR, 'index.html'), 'utf8');
    const m = html.match(/<script type="application\/json" id="stated-facts">([\s\S]*?)<\/script>/);
    if (!m) { check('page states its fixed facts in machine-readable form', false, 'no #stated-facts block'); }
    else {
      const f = JSON.parse(m[1]);
      check('stated facts: total deals = chunks x seeds per chunk = plan total',
            f.totalDeals === f.chunks * f.seedsPerChunk && f.totalDeals === plan.TOTAL_DEALS,
            `${f.totalDeals.toLocaleString('en-US')}`);
      check('stated facts: trick cap and decomposition B match the plan',
            f.cap === plan.CAP && f.decompB.chunks === plan.DECOMP_B.chunks &&
            f.decompB.seedsPerChunk === plan.DECOMP_B.p0 &&
            f.decompB.chunks * f.decompB.seedsPerChunk === plan.TOTAL_DEALS);
      check('stated facts: penalty values are the ones the rules state',
            f.penalty.A === 4 && f.penalty.K === 3 && f.penalty.Q === 2 && f.penalty.J === 1);
      const phrases = ['Ace pays 4', 'King pays 3', 'Queen pays 2', 'Jack pays 1',
                       '100,663,296', '393,216', '100,000'];
      check('page prose carries the stated constants in words and figures',
            phrases.every((s) => html.includes(s)),
            phrases.filter((s) => !html.includes(s)).join(' | ') || 'all present');
      check('page names its offline verifier by path',
            html.includes(`research/${SLUG}/verify-${SLUG}.mjs`));
    }
  } catch (e) {
    check('page states its fixed facts in machine-readable form', false, e.message);
  }

  /* 8. negative controls on the verifier itself */
  {
    const bad = Uint8Array.from(wasmBytes);
    bad[bad.length >> 1] ^= 0xff;
    control('hash control: a corrupted binary would fail the hash check',
            sha256hex(bad) !== (manifest && manifest.WASM_SHA256 ? manifest.WASM_SHA256.toLowerCase() : ''));
  }
  {
    const inst = AW.deep.instantiate(mod);
    inst.init(4, 300);
    const c = inst.chunk(0, 0, 1);
    const good = plan.initial();
    plan.reduce(good, new DataView(c.out.buffer), 0, 0);
    const badOut = new Uint8Array(c.out);
    badOut[40] ^= 1;                       /* one flip inside the histogram */
    const badAcc = plan.initial();
    plan.reduce(badAcc, new DataView(badOut.buffer), 0, 0);
    control('record control: a flipped histogram byte changes the fingerprint',
            plan.fingerprint(good) !== plan.fingerprint(badAcc));
  }
  {
    const broken = plan.breakReference(ref);
    control('identity control: breakReference really returns a different object', broken !== ref);
  }

  finish();

  function runInline(AWlib, module, pl, chunks, p0, p1) {
    const inst = AWlib.deep.instantiate(module);
    inst.init(p0, p1);
    const acc = pl.initial();
    for (let i = 0; i < chunks; i++) {
      const c = inst.chunk(0, i, chunks);
      pl.reduce(acc, new DataView(c.out.buffer), i, 0);
    }
    return acc;
  }

  async function reproducibleBuild(manifestObj) {
    const script = path.join(ROOT, 'research/_ox3/lib/build-wasm.sh');
    if (!existsSync(script)) { skip('reproducible build', 'research/_ox3/lib/build-wasm.sh not present'); return; }
    let found = null;
    try {
      const v = spawnSync('clang', ['--version'], { encoding: 'utf8' });
      if (v.status === 0) found = v.stdout.split('\n')[0].trim();
    } catch (_) { /* absent */ }
    const pinned = manifestObj && manifestObj.CLANG ? String(manifestObj.CLANG) : null;
    if (!found || !pinned || !(found.includes(pinned) || pinned.includes(found))) {
      skip('reproducible build', `clang ${found || 'absent'} != pinned ${pinned || 'unknown'}`);
      return;
    }
    const tmp = await mkdtemp(path.join(tmpdir(), 'awbuild-'));
    const out = path.join(tmp, 'engine.wasm');
    const src = path.join(ROOT, DIR, 'engine.c');
    let built = false;
    for (const argv of [[src, out], [out, src]]) {
      const r = spawnSync('bash', [script, ...argv], { cwd: ROOT, encoding: 'utf8' });
      if (r.status === 0 && existsSync(out)) { built = true; break; }
    }
    if (!built) {
      check('reproducible build reproduces engine.wasm byte for byte', false,
            'build-wasm.sh ran but produced no output');
    } else {
      const rebuilt = await readFile(out);
      check('reproducible build reproduces engine.wasm byte for byte',
            Buffer.compare(rebuilt, wasmBytes) === 0,
            `${rebuilt.length} bytes`);
    }
    await rm(tmp, { recursive: true, force: true });
  }

  function finish() {
    const secs = ((Date.now() - t0) / 1000).toFixed(1);
    console.log(`
${n - failures}/${n} checks passed in ${secs}s`);
    process.exit(failures ? 1 : 0);
  }
}

main().catch((e) => { console.error('verifier crashed:', e); process.exit(1); });
