#!/usr/bin/env node
// verify-every-expert-board-that-forces-a-guess.mjs — the offline gate.
//
// Run from the repo root:  node research/every-expert-board-that-forces-a-guess/verify-every-expert-board-that-forces-a-guess.mjs
//
// Node 22, no dependencies, no network. Prints one line per assertion, then a total,
// and exits non-zero on any FAIL. AW_CENSUS_BOARDS overrides the full-size census
// count for debugging; the default is the real size.

import { readFileSync, writeFileSync, mkdtempSync, rmSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { tmpdir, cpus } from 'node:os';
import { spawnSync } from 'node:child_process';
import { pathToFileURL, fileURLToPath } from 'node:url';
import { Worker } from 'node:worker_threads';
import path from 'node:path';

const SLUG = 'every-expert-board-that-forces-a-guess';
const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const DIR = path.join(ROOT, 'public', 'strata', SLUG);
const WASM = path.join(DIR, 'engine.wasm');
const ENGINE_C = path.join(DIR, 'engine.c');
const BUILD_SH = path.join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh');

let fails = 0, n = 0;
const pad = (k) => String(k).padStart(3, '0');
function check(id, label, ok, extra) {
  n++;
  console.log(`${ok ? 'PASS' : 'FAIL'} ${pad(id)}  ${label}${extra ? '  :: ' + extra : ''}`);
  if (!ok) fails++;
}
function control(id, label, ok) {
  console.log(`CONTROL ${pad(id)}  ${label}: ${ok ? 'caught' : 'NOT CAUGHT'}`);
  if (!ok) fails++;
}
function info(s) { console.log('INFO   ' + s); }

/* ---- load the committed ES modules through temp .mjs copies, so their ESM
       interpretation does not depend on the repo's package.json type ---- */
function loadModule(srcPath, name) {
  const code = readFileSync(srcPath, 'utf8');
  const dir = mkdtempSync(path.join(tmpdir(), 'awv-'));
  const p = path.join(dir, name);
  writeFileSync(p, code);
  return import(pathToFileURL(p).href);
}
const ref = await loadModule(path.join(DIR, 'reference.js'), 'reference.mjs');
const planMod = await loadModule(path.join(DIR, 'plan.js'), 'plan.mjs');
const manifest = await loadModule(path.join(DIR, 'manifest.js'), 'manifest.mjs');
const { plan, IX, NF, REC_BYTES } = planMod;

/* ---- engine access ---- */
let engBytes = null, eng = null;
try {
  engBytes = readFileSync(WASM);
  const mod = await WebAssembly.compile(engBytes);
  const inst = new WebAssembly.Instance(mod, {});
  const x = inst.exports;
  eng = {
    x,
    init(p0, p1) { if (x.aw_reset) x.aw_reset(); if (x.aw_init) x.aw_init(p0 >>> 0, p1 >>> 0); },
    chunk(r, i, nch) {
      const ops = x.aw_chunk(r >>> 0, i >>> 0, nch >>> 0);
      const len = x.aw_out_len() >>> 0;
      const ptr = x.aw_out() >>> 0;
      return { out: new Uint8Array(x.memory.buffer, ptr, len).slice(), ops };
    },
  };
} catch (e) {
  console.log('FAIL 000  engine.wasm could not be loaded: ' + e.message);
  process.exit(1);
}

function runCensusEng(p0, p1, chunks) {
  const acc = plan.initial();
  eng.init(p0, p1);
  for (let i = 0; i < chunks; i++) {
    const c = eng.chunk(0, i, chunks);
    plan.reduce(acc, new DataView(c.out.buffer), i, 0);
  }
  return acc;
}
function runCensusRef(p0, p1, chunks) {
  const acc = plan.initial();
  ref.init(p0, p1);
  for (let i = 0; i < chunks; i++) {
    const c = ref.chunk(0, i, chunks);
    plan.reduce(acc, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, 0);
  }
  return acc;
}
function accEqual(a, b) {
  for (let i = 0; i < NF; i++) if (a[i] !== b[i]) return false;
  return true;
}

/* ---- the full-size census across every core, the way the page runs it ----
   The page runs its census in a pool of browser Workers, one wasm instance each,
   with the chunk index range split between them; this drives the identical
   decomposition through node's worker_threads so the offline gate measures the
   same thing at the same size instead of one core's worth of it. A worker sums
   its chunks' records in u64 BigInts, so the split is exact rather than merely
   close, and assertion 8b below checks the pooled total against the ordinary
   single-instance loop on a smaller run: if the engine ever carried state from
   one chunk into the next, splitting the range would move the answer and that
   assertion is what would say so. */
const workerSrc = `
const { parentPort } = require('node:worker_threads');
let ex = null;
parentPort.on('message', (m) => {
  if (m.t === 'bytes') {
    ex = new WebAssembly.Instance(new WebAssembly.Module(m.bytes), {}).exports;
    parentPort.postMessage({ t: 'ready' });
    return;
  }
  if (ex.aw_reset) ex.aw_reset();
  ex.aw_init(m.p0 >>> 0, m.p1 >>> 0);
  const acc = new BigUint64Array(m.nf);
  for (let i = m.lo; i < m.hi; i++) {
    ex.aw_chunk(0, i, m.chunks);
    const dv = new DataView(ex.memory.buffer, ex.aw_out() >>> 0, ex.aw_out_len() >>> 0);
    for (let k = 0; k < m.nf; k++) acc[k] += dv.getBigUint64(k * 8, true);
  }
  parentPort.postMessage({ t: 'done', acc: acc.buffer }, [acc.buffer]);
});
`;
const poolDir = mkdtempSync(path.join(tmpdir(), 'awv-pool-'));
const workerFile = path.join(poolDir, 'census-worker.cjs');
writeFileSync(workerFile, workerSrc);

async function runCensusPool(p0, p1, chunks) {
  const nW = Math.max(1, Math.min(cpus().length || 1, chunks));
  const per = Math.ceil(chunks / nW);
  const jobs = [];
  for (let w = 0; w < nW; w++) {
    const lo = w * per, hi = Math.min(chunks, lo + per);
    if (lo < hi) jobs.push({ lo, hi });
  }
  const acc = plan.initial();
  await Promise.all(jobs.map((job) => new Promise((resolve, reject) => {
    const wk = new Worker(workerFile);
    wk.on('error', reject);
    wk.on('message', (m) => {
      if (m.t === 'ready') {
        wk.postMessage({ p0, p1, chunks, lo: job.lo, hi: job.hi, nf: NF });
        return;
      }
      const part = new BigUint64Array(m.acc);
      for (let k = 0; k < NF; k++) acc[k] += part[k];
      wk.terminate();
      resolve();
    });
    wk.postMessage({ t: 'bytes', bytes: engBytes });
  })));
  return { acc, workers: jobs.length };
}
function rates(acc) {
  const B = Number(acc[IX.boards]);
  const r = (k) => B ? Number(acc[IX[k]]) / B : 0;
  return {
    boards: B,
    guess: r('boardsWithGuess'),
    winA: r('winsA'), winB: r('winsB'), winC: r('winsC'),
    meanGuesses: B ? Number(acc[IX.totalGuesses]) / B : 0,
  };
}
function wald(p, nn) { return 1.96 * Math.sqrt(Math.max(p * (1 - p), 0) / nn); }

/* ================================================================ 1. ABI */
{
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'memory'];
  const missing = need.filter((k) => !(k in eng.x));
  check(1, 'engine.wasm instantiates and exports the full ABI', missing.length === 0,
    missing.length ? 'missing: ' + missing.join(',') : '');
}

/* ================================================================ 2. hash */
{
  const actual = createHash('sha256').update(engBytes).digest('hex');
  const expected = String(manifest.WASM_SHA256 || '').toLowerCase();
  check(2, 'sha256(engine.wasm) equals manifest.WASM_SHA256', actual === expected && expected.length > 0,
    actual.slice(0, 16) + '...');
}

/* ================================================================ 3. reproducible build (honest skip) */
{
  let clangOut = null;
  try {
    const r = spawnSync('clang', ['--version'], { encoding: 'utf8' });
    if (r.status === 0) clangOut = r.stdout;
  } catch (_) {}
  const pinned = manifest.CLANG ? String(manifest.CLANG) : '';
  const norm = (s) => String(s).replace(/\s+/g, ' ').trim();
  if (!clangOut || !pinned) {
    console.log(`SKIP   reproducible build (clang ${clangOut ? 'present' : 'absent'}, pin ${pinned ? 'present' : 'absent'})`);
  } else if (!norm(clangOut).includes(norm(pinned))) {
    console.log(`SKIP   reproducible build (clang ${norm(clangOut).split('(')[0].trim()} != pinned ${norm(pinned)})`);
  } else if (!readFileSyncSafe(BUILD_SH)) {
    console.log('SKIP   reproducible build (research/_ox3/lib/build-wasm.sh not found)');
  } else {
    const tmp = path.join(tmpdir(), 'aw-rebuild-' + Date.now() + '.wasm');
    const r = spawnSync('bash', [BUILD_SH, ENGINE_C, tmp], { encoding: 'utf8' });
    if (r.status !== 0) {
      check(3, 'reproducible build', false, 'build-wasm.sh exited ' + r.status + ': ' + (r.stderr || '').slice(0, 200));
    } else {
      const reb = readFileSync(tmp);
      const same = reb.length === engBytes.length && reb.equals(engBytes);
      check(3, 'rebuilt engine.c is byte-identical to the committed engine.wasm', same,
        `${engBytes.length} vs ${reb.length} bytes`);
    }
  }
}
function readFileSyncSafe(p) { try { readFileSync(p); return true; } catch (_) { return false; } }

/* ================================================================ 4. battery */
{
  const rows = [];
  let allAgree = true;
  for (const b of plan.battery) {
    const fw = plan.fingerprint(runCensusEng(b.p0, b.p1, b.chunks));
    const fr = plan.fingerprint(runCensusRef(b.p0, b.p1, b.chunks));
    rows.push({ label: b.label, fw, fr, agree: fw === fr });
    if (fw !== fr) allAgree = false;
  }
  check(4, `battery: wasm and reference fingerprints agree on all ${rows.length} rows`, allAgree,
    rows.filter((r) => !r.agree).map((r) => r.label).join('; ') || '');
  const distinct = new Set(rows.map((r) => r.fw)).size === rows.length;
  check(5, 'battery rows produce pairwise-distinct fingerprints', distinct);
  globalThis.__batteryRows = rows;
}

/* ================================================================ 6. control */
{
  const broken = plan.breakReference(ref);
  const differentObject = broken !== ref;
  check(6, 'breakReference returns a different object', differentObject);
  let caught = 0;
  for (const b of plan.battery) {
    const fw = plan.fingerprint(runCensusEng(b.p0, b.p1, b.chunks));
    broken.init(b.p0, b.p1);
    const accB = plan.initial();
    for (let i = 0; i < b.chunks; i++) {
      const c = broken.chunk(0, i, b.chunks);
      plan.reduce(accB, new DataView(c.out.buffer, c.out.byteOffset, c.out.byteLength), i, 0);
    }
    if (fw !== plan.fingerprint(accB)) caught++;
  }
  check(7, 'control: the broken reference disagrees on at least one battery row', caught > 0,
    `caught on ${caught}/${plan.battery.length} rows`);
}

/* ================================================================ 8. full-size census, two decompositions */
{
  const N = Number(process.env.AW_CENSUS_BOARDS || 12000);
  const t0 = Date.now();
  const ra = await runCensusPool(N, 0, 7);
  const rb = await runCensusPool(N, 0, 23);
  const A = ra.acc, B = rb.acc;
  const dt = ((Date.now() - t0) / 1000).toFixed(1);
  check(8, `full-size census: ${N.toLocaleString('en-US')} expert boards under 7 and 23 chunks give identical totals`,
    accEqual(A, B), `${dt}s across ${ra.workers} and ${rb.workers} workers`);
  /* The pool is a driver, not a second algorithm, and it must not be able to move
     the answer. Same boards, same chunk count, one wasm instance in this process
     against the split pool: any state the engine carried across a chunk boundary,
     or any board a split dropped or double-counted, shows up here. */
  {
    const M = Math.min(N, 500);
    const single = runCensusEng(M, 0, 7);
    const pooled = (await runCensusPool(M, 0, 7)).acc;
    check(8, `pool control: ${M} boards through the worker pool equal the same ${M} boards through one in-process instance`,
      accEqual(single, pooled), plan.fingerprint(single) + ' vs ' + plan.fingerprint(pooled));
  }
  const rt = rates(A);
  info(`guess rate ${(rt.guess * 100).toFixed(2)}% +/- ${wald(rt.guess, rt.boards).toFixed(2)}pp; ` +
       `wins A/B/C ${(rt.winA * 100).toFixed(2)} / ${(rt.winB * 100).toFixed(2)} / ${(rt.winC * 100).toFixed(2)}%; ` +
       `mean guesses ${rt.meanGuesses.toFixed(3)}`);
  const inv = [
    ['contradictionsSafe', 'solver never deduced safe a cell the board mines'],
    ['contradictionsMine', 'solver never flagged a safe cell as a mine'],
    ['verifyFailures', 'every enumerated assignment re-verified against its constraints'],
    ['sumRuleViolations', 'expected-mines sum rule held on every enumeration'],
    ['infeasible', 'no component enumerated to an empty feasible set'],
    ['runawayGames', 'no game ran away past the iteration guard'],
  ];
  for (const [k, label] of inv) {
    check(9, `invariant on every board: ${label}`, A[IX[k]] === 0n, `${k}=${A[IX[k]]}`);
  }
  /* A solver that plays sound logic and then the best-survival guess wins a
     substantial fraction of expert boards under every policy. Zero wins over a
     five-figure census is impossible unless the solver's model of the board has
     come detached from the board; this assertion is what would have caught the
     neighbour-table truncation independently of the battery. */
  check(9, 'invariant on every board: a sound solver wins some expert boards under every policy',
    A[IX.winsA] > 0n && A[IX.winsB] > 0n && A[IX.winsC] > 0n,
    `winsA=${A[IX.winsA]} winsB=${A[IX.winsB]} winsC=${A[IX.winsC]}`);
  info(`component bound: ${A[IX.boundHits]} enumeration cycles hit a cap on ${A[IX.boardsHitBound]} boards ` +
       `(reported, not asserted zero; a cap is 96 cells, 24 components, 256 constraints, or the 2,097,152-node DFS budget)`);
}

/* ================================================================ 10. planted objects, through the real engine */
{
  const chain = runCensusEng(1, 5, 1);
  const chainOk =
    chain[IX.boards] === 1n &&
    chain[IX.winsC] === 1n &&
    chain[IX.totalGuesses] === 0n &&
    chain[IX.contradictionsSafe] === 0n &&
    chain[IX.contradictionsMine] === 0n &&
    chain[IX.runawayGames] === 0n;
  check(10, 'planted chain board: the unmodified engine deduces the two-step chain and wins with zero guesses', chainOk);

  const pair = runCensusEng(1, 6, 1);
  const pairOk =
    pair[IX.boards] === 1n &&
    pair[IX.totalGuesses] === 1n &&
    pair[IX.hist00 + 25] === 1n &&
    pair[IX.boardsWithGuess] === 1n &&
    pair[IX.contradictionsSafe] === 0n &&
    pair[IX.contradictionsMine] === 0n;
  check(11, 'planted pair board: the engine reports exactly one forced guess at exactly one half (bin 25 of 50)', pairOk);
}

/* ================================================================ 12. cross-method on small boards
   A position only tests anything if the deduction fixpoint leaves at least one cell
   hidden: on a board it solves outright there is no marginal left to compare, and
   the comparison loop runs zero times. Eight seeds of the two smallest variants
   produce exactly that, sixteen fully determined boards and NOTHING compared, so the
   count of compared positions is asserted, not assumed, and the seed range is wide
   enough to make it. The 4x4 tiny boards are always fully determined and contribute
   none of it; the count below is the 5x5 micro boards' and the line says so. */
{
  const SEEDS = 128;
  const perVariant = { 3: 0, 4: 0 };
  let positions = 0, worst = 0, ok = true, why = '';
  let firstA = null, firstB = null;
  outer:
  for (const variant of [3, 4]) {
    for (let s = 0; s < SEEDS; s++) {
      const snaps = [];
      ref.gatherPositions(variant, BigInt(s), (snap) => snaps.push(snap));
      for (const snap of snaps) {
        const a = ref.analyzePosition(snap.W, snap.H, snap.MN, snap.mine, snap.rev, snap.flg);
        if (a.nc === 0) continue;
        const bf = ref.bruteForce(snap.W, snap.H, snap.MN, snap.rev, snap.flg, snap.num);
        /* The position came off a real board, so the real layout is one consistent
           layout: an enumeration that finds none has contradicted a board it was
           handed, and reporting zero probabilities for it would look like agreement
           with nothing behind it. */
        if (bf.total === 0) { ok = false; why = `variant ${variant} seed ${s}: brute force found no consistent layout`; break outer; }
        let compared = 0;
        for (let i = 0; i < snap.W * snap.H; i++) {
          if (a.pG[i] === null || bf.p[i] === null) continue;
          const d = Math.abs(a.pG[i] - bf.p[i]);
          if (d > worst) worst = d;
          compared++;
          if (!(d < 1e-9)) { ok = false; why = `variant ${variant} seed ${s} cell ${i}: |diff| ${d.toExponential(3)}`; break outer; }
        }
        if (compared === 0) { ok = false; why = `variant ${variant} seed ${s}: position had ${a.nc} candidates and compared no cell`; break outer; }
        if (!firstA) { firstA = a; firstB = bf; }
        positions++; perVariant[variant]++;
      }
    }
  }
  check(12, `cross-method: component marginals equal brute-force full-layout enumeration on ${positions} small-board positions ` +
    `from ${SEEDS} seeds each of 5x5 and 4x4 (${perVariant[3]} micro, ${perVariant[4]} tiny; worst |diff| ${worst.toExponential(2)})`,
    ok && positions >= 40, why);
  /* Positive control on the comparator: the same loop, against a brute force nudged
     by 1e-6 at one compared cell, must reject. A comparison that cannot fail is not
     a comparison, and this one ran vacuously for the whole of the previous round. */
  if (firstA) {
    let caughtIt = false;
    for (let i = 0; i < firstB.p.length; i++) {
      if (firstA.pG[i] === null || firstB.p[i] === null) continue;
      if (!(Math.abs(firstA.pG[i] - (firstB.p[i] + 1e-6)) < 1e-9)) caughtIt = true;
      break;
    }
    control(4, 'a 1e-6 perturbation of one compared brute-force marginal is rejected by the 1e-9 comparator', caughtIt);
  } else {
    control(4, 'a 1e-6 perturbation of one compared brute-force marginal is rejected by the 1e-9 comparator', false);
  }
}

/* ================================================================ 13. page facts */
{
  const html = readFileSync(path.join(DIR, 'index.html'), 'utf8');
  const facts = [
    ['16 \u00d7 30', 'expert board dimensions'],
    ['99 mines', 'mine count'],
    ['471', 'cells allowed to hold a mine'],
    ['552', 'aggregate record size in bytes'],
    ['2,097,152', 'enumeration node budget'],
    ['12,000', 'verifier census size, stated on the page'],
    ['50 equal bins', 'guess-quality histogram resolution'],
    [`research/${SLUG}/verify-${SLUG}.mjs`, 'the offline verifier is named'],
  ];
  for (const [needle, what] of facts) {
    check(13, `page states the fixed fact: ${what}`, html.includes(needle));
  }
}

/* ================================================================ negative controls on the verifier itself */
{
  const acc = runCensusEng(64, 0, 4);
  const mut = acc.slice();
  mut[IX.totalGuesses] += 1n;
  control(1, 'tampered accumulator (totalGuesses +1) is rejected by the fingerprint comparison',
    plan.fingerprint(acc) !== plan.fingerprint(mut));
  const actual = createHash('sha256').update(engBytes).digest('hex');
  const wrong = ('deadbeef' + actual.slice(8)).toLowerCase();
  control(2, 'tampered manifest hash is rejected by the hash assertion', actual !== wrong);
  const mut2 = acc.slice();
  mut2[IX.boardsWithGuess] += 1n;
  control(3, 'tampered decomposition total is rejected by the elementwise comparator', !accEqual(acc, mut2));
}

/* ================================================================ total */
console.log(`
${n - fails}/${n} assertions passed${fails ? `, ${fails} FAILED` : ''}`);
process.exit(fails ? 1 : 0);
