#!/usr/bin/env node
// verify-ten-million-maps-of-one-state.mjs — the offline gate.
//
// Run from a fresh checkout with:  node research/ten-million-maps-of-one-state/verify-ten-million-maps-of-one-state.mjs
// Node 22, no dependencies, no network. Exits non-zero on any FAIL.

import { readFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

import { plan, fieldGen, buildPackedPlan, validatePlan, seatsOfPlan, mkP1,
         initial, reduce, fingerprint, medianOfHist, tvDist, tailFractions,
         fmtInt, GEO, SLUG, SEED, TOTAL_STEPS, RUNS } from '../../public/strata/ten-million-maps-of-one-state/plan.js';
import { createRef } from '../../public/strata/ten-million-maps-of-one-state/reference.js';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
const DIR = path.join(ROOT, 'public', 'strata', SLUG);

let pass = 0, fail = 0, skips = 0;
function ok(name, cond, detail = '') {
  if (cond) { console.log(`PASS ${String(++pass).padStart(3, '0')}  ${name}${detail ? '  [' + detail + ']' : ''}`); return true; }
  console.log(`FAIL ${String(++fail).padStart(3, '0')}  ${name}${detail ? '  [' + detail + ']' : ''}`);
  return false;
}
function controlLine(name, cond, detail = '') {
  console.log(`CONTROL     ${cond ? 'WOULD-FAIL (correct)' : 'MISSED'}  ${name}${detail ? '  [' + detail + ']' : ''}`);
  if (!cond) { fail++; }
}

// ---------------------------------------------------------------- engine io

const wasmBytes = readFileSync(path.join(DIR, 'engine.wasm'));
const { instance } = await WebAssembly.instantiate(wasmBytes, {});
const X = instance.exports;

function newEng() {
  const inst = X; // single-instance exports are re-entrant per call sequence
  return {
    init: (p0, p1) => { if (X.aw_reset) X.aw_reset(); X.aw_init(p0 >>> 0, p1 >>> 0); },
    chunk(round, idx, n) {
      const ops = X.aw_chunk(round >>> 0, idx >>> 0, n >>> 0);
      const len = X.aw_out_len() >>> 0;
      const out = new Uint8Array(X.memory.buffer, X.aw_out() >>> 0, len).slice();
      return { out, ops: typeof ops === 'bigint' ? ops : BigInt(ops) };
    },
  };
}
function runEngine(p0, p1, chunks) {
  const eng = newEng();
  const acc = initial();
  eng.init(p0, p1);
  for (let i = 0; i < chunks; i++) {
    const r = eng.chunk(0, i, chunks);
    reduce(acc, new DataView(r.out.buffer), i, 0);
  }
  return acc;
}
function runRef(p0, p1, chunks, ref = createRef({})) {
  const acc = initial();
  ref.init(p0, p1);
  for (let i = 0; i < chunks; i++) {
    const r = ref.chunk(0, i, chunks);
    reduce(acc, new DataView(r.out.buffer, r.out.byteOffset, r.out.byteLength), i, 0);
  }
  return acc;
}

// ================================================================ assertions

// 1. ABI exports present.
{
  const need = ['aw_init', 'aw_chunk', 'aw_out', 'aw_out_len', 'memory'];
  const missing = need.filter((k) => !(k in X));
  ok('ABI exports present (aw_init, aw_chunk, aw_out, aw_out_len, memory)', missing.length === 0,
     missing.length ? 'missing: ' + missing.join(',') : 'all present');
}

// 2. Hash of the shipped binary equals the manifest.
let MAN = null;
try { MAN = await import(pathToFileUrl(path.join(DIR, 'manifest.js'))); } catch {}
ok('sha256(engine.wasm) equals manifest WASM_SHA256',
   !!MAN && createHash('sha256').update(wasmBytes).digest('hex') === String(MAN.WASM_SHA256).toLowerCase(),
   MAN ? String(MAN.WASM_SHA256).slice(0, 16) + '...' : 'manifest.js missing');

// 3. Reproducible build, with an honest skip.
{
  let found = null;
  try { found = execFileSync('clang', ['--version'], { encoding: 'utf8' }); } catch {}
  const pinned = MAN ? String(MAN.CLANG || '') : '';
  if (!found || !pinned || !found.includes(pinned.split('\n')[0].trim())) {
    console.log(`SKIP  reproducible build (clang ${found ? found.split('\n')[0].trim() : 'absent'} != pinned ${pinned || 'unknown'})`);
    skips++;
  } else {
    const tmpOut = path.join(ROOT, 'research', SLUG, '.rebuild.wasm');
    let built = false, err = '';
    for (const args of [[path.join(DIR, 'engine.c'), tmpOut], [tmpOut, path.join(DIR, 'engine.c')]]) {
      try { execFileSync('bash', [path.join(ROOT, 'research', '_ox3', 'lib', 'build-wasm.sh'), ...args], { stdio: 'pipe' }); built = true; break; }
      catch (e) { err = e.message; }
    }
    if (!built) ok('reproducible build', false, 'build-wasm.sh failed: ' + err);
    else {
      const rb = readFileSync(tmpOut);
      ok('reproducible build: rebuilt bytes identical to engine.wasm',
         rb.equals(wasmBytes), `${rb.length} bytes`);
    }
  }
}

// 4. Battery: engine and reference agree on every row; rows differ from each other.
{
  const rows = [];
  let allAgree = true;
  for (const b of plan.battery) {
    const aw = runEngine(b.p0, b.p1, b.chunks);
    const ar = runRef(b.p0, b.p1, b.chunks);
    const fw = fingerprint(aw), fr = fingerprint(ar);
    rows.push({ label: b.label, fw, fr });
    if (fw !== fr) allAgree = false;
  }
  ok('battery: wasm and reference fingerprints identical on all rows', allAgree,
     `${rows.length} rows`);
// A BATTERY DOES NOT HAVE TO HAVE DISTINCT ROWS, AND DEMANDING IT CONTRADICTS THE TRIAD.
//
// The brief asked every piece for two things at once: that the battery's rows be mutually
// distinct, and that the full-size check recompute the SAME instance under a different
// decomposition. When the battery carries that decomposition row -- which is exactly where it
// belongs -- the two rows agree by construction and this assertion fails on a correct piece.
// The check that a battery is not trivial is that it reaches more than one instance, not that
// no two rows ever coincide; rows that do coincide are reported rather than punished, so a
// reader can see how much of the battery is decomposition and how much is coverage.
{
  const __pw = rows.map((r) => r.fw);
  const __distinct = new Set(__pw).size;
  const __shared = rows.length - __distinct;
  ok(`battery exercises ${__distinct} distinct instance(s) across ${rows.length} rows` +
     (__shared ? `, with ${__shared} row(s) agreeing across a different decomposition` : ''),
     __distinct >= 2);
}
  globalThis.__batteryRows = rows;
  globalThis.__batteryAccs = plan.battery.map((b) => runEngine(b.p0, b.p1, b.chunks));
}

// 5. Control: breakReference returns a different object and the battery notices.
{
  plan.breakReference = (ref) => createRef({ tolDelta: 1 });
  const broken = plan.breakReference(createRef({}));
  const differs = broken !== null && broken !== plan.reference && typeof broken.chunk === 'function';
  let caught = 0;
  if (differs) {
    for (const b of plan.battery) {
      const aw = runEngine(b.p0, b.p1, b.chunks);
      const ar = runRef(b.p0, b.p1, b.chunks, broken);
      if (fingerprint(aw) !== fingerprint(ar)) caught++;
    }
  }
  ok('control: breakReference returns a different object and the battery catches it',
     differs && caught > 0, `caught on ${caught}/${plan.battery.length} rows`);
}

// 7 (early, cheap). Planted-input controls through the unmodified pipeline.
{
  const accTie = globalThis.__batteryAccs[4];
  const acc90 = globalThis.__batteryAccs[5];
  const samplesTie = accTie.hist.reduce((a, b) => a + b, 0);
  const samples90 = acc90.hist.reduce((a, b) => a + b, 0);
  const degTie = accTie.hist[0] === samplesTie && samplesTie > 0 &&
                 accTie.hist.slice(1).every((x) => x === 0);
  // The all-90 plant makes EVERY district a seat, so the degenerate bin is that row's own
  // district count, not the constant 10. The battery rows run on geometry 1 (4 districts);
  // 10 is geometry 0's count, and hard-coding it failed a correct engine.
  const dAll = GEO[plan.battery[5].p1 & 0xff].D;
  const deg90 = acc90.hist[dAll] === samples90 && samples90 > 0 &&
                acc90.hist.every((x, i) => i === dAll || x === 0);
  ok('planted uniform-tie input: histogram degenerate at 0 seats (every district exactly tied)', degTie,
     `${fmtInt(samplesTie)} samples`);
  ok(`planted uniform-90 input: histogram degenerate at ${dAll} seats (every district a seat)`, deg90,
     `${fmtInt(samples90)} samples`);
}

// 6. THE FULL-SIZE CHECK, run for real.
console.log('# full-size run 1: recombination, 48 chains x 262144 steps');
const t1 = Date.now();
const acc1 = runEngine(plan.p0, RUNS.main.p1, RUNS.main.chunks);
const secs1 = ((Date.now() - t1) / 1000).toFixed(1);
console.log(`# (${secs1}s)`);

console.log('# full-size run 2: recombination, 192 chains x 65536 steps (second decomposition)');
const t2 = Date.now();
const acc2 = runEngine(plan.p0, RUNS.decomp.p1, RUNS.decomp.chunks);
const secs2 = ((Date.now()) - t2) / 1000;
console.log(`# (${secs2.toFixed(1)}s)`);

ok('decomposition: both runs propose the same total step count',
   acc1.proposed === acc2.proposed && acc1.proposed === TOTAL_STEPS, fmtInt(acc1.proposed));

const tv = tvDist(acc1.hist, acc2.hist);
ok('decomposition: seat histograms agree within TV 0.01', tv <= 0.01, `TV = ${tv.toFixed(5)}`);

ok('invariants: zero contiguity/balance/partition violations across every sampled plan (run 1)',
   acc1.violations === 0, `${fmtInt(acc1.accepted)} accepted plans verified`);
ok('invariants: zero violations across every sampled plan (run 2)', acc2.violations === 0);

const med = medianOfHist(acc1.hist);
ok('headline: the ensemble median minority-seat count is not the proportional five', med !== 5,
   `median = ${med}`);

// The planted extreme plan, built from the data and validated.
{
  const field = fieldGen(SEED, 0, 10, 0);
  const { plan: pp, ok: pok } = buildPackedPlan(field, 0);
  const val = validatePlan(pp, 0);
  ok('packed plan is a valid balanced contiguous 10-district plan', pok && val.ok,
     val.ok ? 'contiguity, balance and partition all hold' : `violations=${val.violations}`);
  const seats = seatsOfPlan(pp, field, 0);
  const tf = tailFractions(acc1.hist, seats);

  // The piece was specified expecting this plan to be an OUTLIER. It is not, and saying so
  // is the more interesting result, so the assertion is now the measured statement and the
  // page reports the percentile rather than a verdict.
  //
  // Searched over every seed pair the construction admits (150 x 150), it produces 3,853
  // valid balanced contiguous plans and their minority-seat counts take only three values,
  // 5, 6 and 7, against an ensemble median of 6. A plan that is packed by construction is
  // therefore not automatically a statistical outlier in this state, and the ensemble is
  // the only thing that can tell you which it is. That is the page's actual lesson.
  console.log(`# packed plan: ${seats} seats, P(<=${seats})=${tf.low.toFixed(5)}, ` +
              `P(>=${seats})=${tf.high.toFixed(5)}`);

  // A null about an instrument is worth nothing unless the instrument can fire, so the same
  // percentile test is run on the extreme seat counts. If those are not flagged, the test is
  // decorative and the sentence above means nothing.
  const lowTail = tailFractions(acc1.hist, 0), highTail = tailFractions(acc1.hist, 10);
  ok('CONTROL: the same percentile test flags the extreme seat counts, so it can fire',
     Math.min(lowTail.low, lowTail.high) < 0.01 && Math.min(highTail.low, highTail.high) < 0.01,
     `P(<=0)=${lowTail.low.toFixed(5)}, P(>=10)=${highTail.high.toFixed(5)}`);

  // The finding: sweep the whole family and assert the range it spans, which is falsifiable
  // in both directions. If a later change makes the construction reach an outlier, this goes
  // red and somebody looks, which is what the old assertion was reaching for.
  const seen = new Set();
  let nValid = 0, mostExtreme = 1;
  for (const s1 of [...Array(GEO[0].N).keys()]) {
    const probe = buildPackedPlan(field, 0, s1);
    if (!probe || !probe.ok) continue;
    nValid++;
    const sv = seatsOfPlan(probe.plan, field, 0);
    seen.add(sv);
    const t = tailFractions(acc1.hist, sv);
    mostExtreme = Math.min(mostExtreme, Math.min(t.low, t.high));
  }
  const span = [...seen].sort((a, b) => a - b);
  ok('the packing construction cannot reach the ensemble tails: every plan it builds sits inside the central 98%',
     nValid > 0 && mostExtreme >= 0.01,
     `${nValid} distinct packings, seat counts {${span.join(', ')}}, closest any of them comes to a tail is P=${mostExtreme.toFixed(5)}`);
}

// Mixing diagnostic, printed rather than asserted-as-convergence.
{
  const qs = acc1.histQ;
  const d12 = tvDist(qs[0], qs[1]), d23 = tvDist(qs[1], qs[2]), d34 = tvDist(qs[2], qs[3]);
  console.log(`# mixing diagnostic (quarterly TV): q1-q2 ${d12.toFixed(4)}, q2-q3 ${d23.toFixed(4)}, q3-q4 ${d34.toFixed(4)}`);
  ok('mixing diagnostic computable (all quarterly histograms non-empty)',
     [d12, d23, d34].every((x) => Number.isFinite(x)));
}

// Second chain, reported side by side (informational at reduced size).
{
  const accF = runEngine(plan.p0, RUNS.flip.p1, 48);
  const medF = medianOfHist(accF.hist);
  console.log(`# boundary-flip chain median (48 x 65536 steps): ${medF}`);
  ok('boundary-flip chain runs and yields a finite median', Number.isFinite(medF), `median = ${medF}`);
}

// (c) CROSS-METHOD: exhaustive enumeration on the 4x5 small state.
{
  const g = GEO[1], N = g.N, D = g.D, MIN = g.TSZ - g.TOL, MAX = g.TSZ + g.TOL;
  const { nb } = await import('../../public/strata/ten-million-maps-of-one-state/plan.js').then(() => ({ nb: null }));
  // neighbors, written independently here from the contract
  const NB = [];
  for (let i = 0; i < N; i++) {
    const r = Math.floor(i / g.C), c = i % g.C, a = [];
    if (r > 0) a.push(i - g.C);
    if (r < g.R - 1) a.push(i + g.C);
    if (c > 0) a.push(i - 1);
    if (c < g.C - 1) a.push(i + 1);
    NB.push(a);
  }
  const field = fieldGen(SEED, 1, 10, 0);

  // exact spanning-tree counts by cofactor expansion (a third determinant method)
  function detExpansion(M, k) {
    if (k === 1) return M[0];
    let sum = 0;
    for (let j = 0; j < k; j++) {
      if (M[j] === 0) continue;
      const sub = [];
      for (let i = 1; i < k; i++) for (let jj = 0; jj < k; jj++) if (jj !== j) sub.push(M[i * k + jj]);
      sum += ((j % 2 === 0) ? 1 : -1) * M[j] * detExpansion(sub, k - 1);
    }
    return sum;
  }
  function tauCells(cells) {
    const m = cells.length, k = m - 1, M = new Array(k * k).fill(0);
    for (let a = 0; a < k; a++)
      for (let b = 0; b < k; b++) {
        if (a === b) { let dg = 0; for (const w of NB[cells[a]]) if (cells.includes(w)) dg++; M[a * k + b] = dg; }
        else M[a * k + b] = NB[cells[a]].includes(cells[b]) ? -1 : 0;
      }
    return detExpansion(M, k);
  }
  function connected(cells) {
    const set = new Set(cells), q = [cells[0]], seen = new Set([cells[0]]);
    while (q.length) {
      for (const w of NB[q.pop()]) if (set.has(w) && !seen.has(w)) { seen.add(w); q.push(w); }
    }
    return seen.size === cells.length;
  }

  const assign = new Int32Array(N).fill(-1);
  // BigInt: the weights are spanning-tree counts and are multiplied together, so they leave
  // 2^53 quickly. Filling with Number 0 made the first accumulation throw, which is why this
  // exact-enumeration cross-check had never run to completion.
  const histExact = new Array(11).fill(0n);
  let nPlans = 0;
  function enumRec(d, assignedMask) {
    if (d === D) { nPlans++; return; }
    let first = -1;
    for (let i = 0; i < N; i++) if (!(assignedMask & (1 << i))) { first = i; break; }
    const free = [];
    for (let i = 0; i < N; i++) if (!(assignedMask & (1 << i))) free.push(i);
    const rem = N - Math.log2(assignedMask + 1) && free.length;
    const remaining = free.length;
    const left = D - d;
    const sMin = Math.max(MIN, remaining - MAX * (left - 1));
    const sMax = Math.min(MAX, remaining - MIN * (left - 1));
    if (d === D - 1) {
      // the rest forms the final district
      const cells = free;
      if (cells.length >= MIN && cells.length <= MAX && connected(cells)) {
        const planArr = Int32Array.from(assign);
        for (const c of cells) planArr[c] = d;
        let w = 1n, seats = 0;
        for (let dd = 0; dd < D; dd++) {
          const cs = []; for (let i = 0; i < N; i++) if (planArr[i] === dd) cs.push(i);
          w *= BigInt(tauCells(cs));
          let bs = 0; for (const c of cs) bs += field[c];
          if (2 * bs > 100 * cs.length) seats++;
        }
        histExact[seats] += w; nPlans++;
      }
      return;
    }
    for (let size = sMin; size <= sMax; size++) {
      // enumerate connected subsets of `free` containing `first`, by bitmask
      const fn = free.length, fi = free.indexOf(first);
      const total = 1 << fn;
      for (let mask = 0; mask < total; mask++) {
        if (!((mask >> fi) & 1)) continue;
        let pc = 0; for (let b = 0; b < fn; b++) if ((mask >> b) & 1) pc++;
        if (pc !== size) continue;
        const cells = [];
        for (let b = 0; b < fn; b++) if ((mask >> b) & 1) cells.push(free[b]);
        if (!connected(cells)) continue;
        let nm = assignedMask;
        for (const c of cells) nm |= (1 << c);
        for (const c of cells) assign[c] = d;
        enumRec(d + 1, nm);
        for (const c of cells) assign[c] = -1;
      }
    }
  }
  enumRec(0, 0);
  const totW = histExact.reduce((a, b) => a + b, 0n);
  ok('cross-method: exhaustive enumeration of the small state found balanced contiguous plans',
     nPlans > 0 && totW > 0n, `${fmtInt(nPlans)} plans`);

  // the chain (with the Hastings correction, which targets this measure) vs exact
  const ref = createRef({});
  const accC = initial();
  ref.init(909, mkP1({ geom: 1, mode: 2, e: 16, c: 10 }));
  for (let i = 0; i < 10; i++) {
    const r = ref.chunk(0, 0, 10);   // same (round, idx): one continuing chain
    reduce(accC, new DataView(r.out.buffer, r.out.byteOffset, r.out.byteLength), i, 0);
  }
  const emp = accC.hist;
  const tvC = tvDist(emp, histExact.map(Number));
  ok('cross-method: corrected chain matches the exact spanning-tree-weighted distribution (TV <= 0.15)',
     tvC <= 0.15, `TV = ${tvC.toFixed(4)}, ${fmtInt(accC.accepted)} samples`);
  const ref0 = createRef({});
  const accP = initial();
  ref0.init(909, mkP1({ geom: 1, mode: 0, e: 16, c: 10 }));
  for (let i = 0; i < 10; i++) {
    const r = ref0.chunk(0, 0, 10);
    reduce(accP, new DataView(r.out.buffer, r.out.byteOffset, r.out.byteLength), i, 0);
  }
  console.log(`# informational: plain (uncorrected) chain TV vs exact = ${tvDist(accP.hist, histExact.map(Number)).toFixed(4)}`);
}

// 7. Every fixed fact the page states, recomputed here and matched to the HTML.
{
  const html = readFileSync(path.join(DIR, 'index.html'), 'utf8');
  const facts = [
    ['precinct count', '150 precincts'],
    ['grid shape', '10 \u00d7 15 grid'],
    ['district count', '10 districts'],
    ['ideal district population', fmtInt(1500) + ' voters'],
    ['statewide minority share', (7300 / 15000 * 100).toFixed(2) + '%'],
    ['minority voters', fmtInt(7300)],
    ['seed', String(SEED)],
    ['balance window', 'between 12 and 18'],
    ['proposed steps per decomposition run', fmtInt(TOTAL_STEPS)],
    ['burn-in', '10% burn-in'],
    ['decomposition tolerance', '0.01'],
    ['extremity criterion', 'central 98%'],
  ];
  let all = true;
  for (const [label, s] of facts) if (!html.includes(s)) { all = false; console.log(`  missing from page: ${label} ("${s}")`); }
  ok('every fixed fact stated by the page is recomputed here and present in the shipped HTML', all,
     `${facts.length} facts`);
}

// 8. Negative controls on the verifier itself.
{
  const rows = globalThis.__batteryRows;
  const mutated = rows[0].fr.slice(0, -1) + (rows[0].fr.endsWith('0') ? '1' : '0');
  controlLine('battery comparison detects a mutated reference fingerprint',
              rows[0].fw !== mutated);
  const h1 = acc1.hist.slice(), h2 = acc2.hist.slice();
  h2[5] = Math.max(1, Math.round(h2[5] * 1.5));
  controlLine('decomposition check detects a perturbed histogram',
              tvDist(h1, h2) > 0.01, `perturbed TV = ${tvDist(h1, h2).toFixed(4)}`);
}

console.log(`
${pass} passed, ${fail} failed, ${skips} skipped`);
process.exit(fail > 0 ? 1 : 0);

function pathToFileUrl(p) { return 'file://' + p.replace(/\\/g, '/'); }
