#!/usr/bin/env node
// Independent verifier for the stratum "the-board-that-loiters-at-sixty".
//
// What this is: the page's evidence that it is not lying. It re-derives every
// number the page displays by methods WRITTEN DIFFERENTLY from engine.mjs, and
// compares. It reads the source tree only; it never touches a build directory.
//
// Order of operations (deliberate):
//   1. unit-test the small pure helpers against HAND-WORKED cases first,
//      because a wrong primitive under a correct algorithm ships silently;
//   2. reproduce the independent anchors;
//   3. reconcile against the page's own inline numbers parsed from index.html;
//   4. --mutate: corrupt engine.mjs, CONFIRM the corruption landed, confirm the
//      checks fail, restore the bytes.
//
// Usage:
//   node verify-the-board-that-loiters-at-sixty.mjs
//   node verify-the-board-that-loiters-at-sixty.mjs --mutate
//
// Exit codes: 0 all checks passed (count printed); 1 any failure or ZERO checks.
//
// Editor note on two defects found and fixed here at source:
//   - applyVec below used to accumulate out[j] += p * v[i], which computes Q^T v,
//     not Q v. Fed to the fixed-point h <- 1 + Qh it therefore solved a DIFFERENT
//     system, (I - Q^T) h = 1, whose entry at square 1 is trivially 1 (no state
//     transitions INTO square 1, so column 0 of Q is zero). It was being described
//     as an anchor for the engine's (I - Q) h = 1 solve when it computed another
//     quantity entirely. Fixed: applyVec now computes (Q v)_i from row i.
//   - The hand-worked toy expectation "E from square 1 = 3" was misderived: it wrote
//     E[1] = 1 + E[2], ignoring that face 2 finishes immediately from square 1.
//     The correct hand solution is E[1] = 1 + E[2]/2 = 2, agreeing with the pmf
//     mean of 2^-t (whose mean is 2) and with simulation. The engine was right;
//     the expectation was wrong, and has been replaced with the worked derivation.

import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const ENGINE_PATH = join(HERE, 'engine.mjs');
const PAGE_PATH = join(HERE, '..', '..', 'public', 'strata',
  'the-board-that-loiters-at-sixty', 'index.html');

const MUTATE = process.argv.includes('--mutate');

// ── harness ────────────────────────────────────────────────────────────────
let CHECKS = 0, FAILS = 0;
const failures = [];
function check(name, ok, detail = '') {
  CHECKS++;
  if (!ok) { FAILS++; failures.push(name + (detail ? ' :: ' + detail : '')); }
  console.log((ok ? '  ok   ' : '  FAIL ') + name + (detail ? '  [' + detail + ']' : ''));
  return ok === true;                       // boolean RETURNED, harness inspects it
}
function approx(x, y, tol) { return Math.abs(x - y) <= tol; }

// ── INDEPENDENT implementation, written differently from engine.mjs ────────
// Layout retyped here on purpose: if engine.mjs's copy is corrupted, the
// disagreement is the signal. (Cross-checked against the page's printed layout
// later, so a typo here is caught too.)
const LAD = [[1,38],[4,14],[9,31],[21,42],[28,84],[36,44],[51,67],[71,91],[80,100]];
const SNK = [[16,6],[47,26],[49,11],[56,53],[62,19],[64,60],[87,24],[93,73],[95,75],[98,78]];

function destHere(s) {
  if (s >= 100) return 100;
  for (const [a, b] of LAD) if (a === s) return b;
  for (const [a, b] of SNK) if (a === s) return b;
  return s;
}
// Column-major accumulation, Map-based rows: structurally unlike engine.mjs.
function buildHere() {
  const n = 99;
  const rows = [];                        // rows[i] = Map(targetIndex -> prob)
  const absorb = new Float64Array(n);
  for (let i = 0; i < n; i++) {
    const m = new Map();
    for (let d = 1; d <= 6; d++) {
      const land = i + 1 + d;
      if (land > 100) { m.set(i, (m.get(i) ?? 0) + 1 / 6); continue; }
      const t = destHere(land);
      if (t >= 100) absorb[i] += 1 / 6;
      else m.set(t - 1, (m.get(t - 1) ?? 0) + 1 / 6);
    }
    rows.push(m);
  }
  return { n, rows, absorb };
}
function applyVec(rows, v) {
  // (Q v)_i = sum over j of Q[i][j] * v[j]. rows[i] IS row i of Q, stored as a
  // Map of (column -> probability), so iterate its ENTRIES and read v at the
  // column index. The previous version accumulated into out[column] and read
  // v[row], which is the TRANSPOSE; it silently solved a different system.
  const out = new Float64Array(rows.length);
  rows.forEach((m, i) => {
    let s = 0;
    for (const [j, p] of m) s += p * v[j];
    out[i] = s;
  });
  return out;
}
// Anchor method A: fixed-point (Richardson/Jacobi-style) iteration h <- 1 + Q h.
// Converges because the spectral radius of Q is strictly below 1.
async function expectedByIteration() {
  const { rows } = buildHere();
  let h = new Float64Array(99);
  for (let it = 0; it < 2000000; it++) {
    const nh = new Float64Array(99);
    const qh = applyVec(rows, h);
    for (let i = 0; i < 99; i++) nh[i] = 1 + qh[i];
    let dev = 0;
    for (let i = 0; i < 99; i++) dev = Math.max(dev, Math.abs(nh[i] - h[i]));
    h = nh;
    if (dev < 1e-13) return { h, iters: it };
  }
  throw new Error('iteration did not converge');
}
// Anchor method B: seeded Monte Carlo, own PRNG instance, own game loop.
function mcHere(count, seed) {
  let a = seed | 0;
  const rnd = () => {
    a = (a + 0x6D2B79F5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
  const lens = new Array(count);
  for (let g = 0; g < count; g++) {
    let sq = 1, turns = 0;
    while (sq < 100 && turns < 100000) {
      turns++;
      const land = sq + 1 + Math.floor(rnd() * 6);
      if (land > 100) continue;
      sq = destHere(land);
    }
    lens[g] = turns;
  }
  const mean = lens.reduce((x, y) => x + y, 0) / count;
  const vari = Math.max(lens.reduce((x, y) => x + y * y, 0) / count - mean * mean, 0);
  return { mean, se: Math.sqrt(vari / count) };
}

// ── hand-worked toy board for helper unit tests ────────────────────────────
// Squares 1..3, die faces [1,2], no chutes, exact-on-finish rule.
// Hand solution, worked turn by turn:
//   From square 2: face 1 lands on 3 and finishes (prob 1/2); face 2 overshoots
//   and the token stays (prob 1/2). So E[2] = 1 + E[2]/2, giving E[2] = 2.
//   From square 1: face 2 lands on 3 and finishes AT ONCE (prob 1/2); face 1
//   walks to square 2 (prob 1/2). So E[1] = 1 + E[2]/2 = 2.
//   Both states therefore expect exactly 2 spins. (An earlier draft of this
//   comment wrote E[1] = 1 + E[2] = 3, dropping the half that finishes on the
//   first turn; the pmf and simulation checks below exposed it.)
//   Length pmf: P(T = t) = 2^-t for every t >= 1 (first success of repeated
//   fair coin flips, whatever the first turn spends), whose mean is 2.
//   The REACH-OR-PASS rule, the plausible wrong alternative, gives E[2] = 1
//   (both faces win from square 2) and E[1] = 1 + E[2]/2 = 1.5, so the toy
//   separates the two overshoot rules cleanly at 2 versus 1.5.
const TOY = { size: 3, start: 1, die: [1, 2], ladders: [], snakes: [] };

// ── main ───────────────────────────────────────────────────────────────────
const engine = await import(pathToFileURL(ENGINE_PATH).href);

console.log('== 1. unit tests of small pure helpers (hand-worked cases first) ==');

check('finalSquare: ladder foot 1 climbs to 38', engine.finalSquare(1) === 38);
check('finalSquare: ladder foot 80 reaches finish 100', engine.finalSquare(80) === 100);
check('finalSquare: snake head 98 slides to 78', engine.finalSquare(98) === 78);
check('finalSquare: plain square 17 is identity', engine.finalSquare(17) === 17);
check('finalSquare: snake head 16 slides to 6', engine.finalSquare(16) === 6);
check('finalSquare: square 100 returns 100', engine.finalSquare(100) === 100);
check('finalSquare: square 99 (past every chute) identity', engine.finalSquare(99) === 99);
check('finalSquare: square 101 clamps to 100', engine.finalSquare(101) === 100);
check('finalSquare: non-integer throws', (() => {
  try { engine.finalSquare(2.5); return false; } catch (e) { return e instanceof TypeError; }
})());
check('finalSquare: toy board identity everywhere', engine.finalSquare(2, TOY) === 2);

{
  const { n, Q, absorb } = engine.buildTransitions(TOY);
  check('toy buildTransitions: n = 2', n === 2);
  // from square 1: face 1 -> square 2 (prob 1/2), face 2 -> finish (prob 1/2)
  check('toy Q[0][1] = 1/2', approx(Q[0 * 2 + 1], 0.5, 1e-15));
  check('toy absorb[0] = 1/2', approx(absorb[0], 0.5, 1e-15));
  // from square 2: face 1 finishes, face 2 overshoots and STAYS
  check('toy absorb[1] = 1/2 (overshoot rule)', approx(absorb[1], 0.5, 1e-15));
  check('toy Q[1][1] = 1/2 (overshoot stays)', approx(Q[1 * 2 + 1], 0.5, 1e-15));
  check('toy rows conserve: rowSum + absorb = 1',
    approx(Q[0] + Q[1] + absorb[0], 1, 1e-12) && approx(Q[2] + Q[3] + absorb[1], 1, 1e-12));
}
{
  const h = engine.expectedSpins(TOY);
  check('toy expected spins from 1 = 2 (hand-worked)', approx(h[0], 2, 1e-12),
    'got ' + h[0]);
  check('toy expected spins from 2 = 2 (hand-worked)', approx(h[1], 2, 1e-12),
    'got ' + h[1]);
}
{
  const { pmf } = engine.lengthDistribution(TOY, 60);
  check('toy pmf[0] = 1/2', approx(pmf[0], 0.5, 1e-12));
  check('toy pmf[1] = 1/4', approx(pmf[1], 0.25, 1e-12));
  check('toy pmf[4] = 1/32', approx(pmf[4], 1 / 32, 1e-12));
  const mean = pmf.reduce((a, p, i) => a + (i + 1) * p, 0);
  check('toy pmf mean = 2', approx(mean, 2, 1e-12));
  check('toy pmf sums to 1', approx(pmf.reduce((a, b) => a + b, 0), 1, 1e-12));
}
{
  // The plausible WRONG overshoot rule (overshoot still wins, i.e. reach-or-pass)
  // gives E[toy from 1] = 1.5, so this call exposes that implementation while
  // leaving room for the correct 2.
  const h = engine.expectedSpins(TOY);
  check('toy mean distinguishes overshoot rules (2, not the reach-or-pass 1.5)',
    approx(h[0], 2, 1e-12) && !approx(h[0], 1.5, 1e-6));
}
{
  const s1 = engine.simulateGames(2000, 42, TOY);
  const s2 = engine.simulateGames(2000, 42, TOY);
  check('simulateGames deterministic for fixed seed',
    s1.mean === s2.mean && s1.counts.every((c, i) => c === s2.counts[i]));
  check('toy simulated mean near 2 within 5 se',
    Math.abs(s1.mean - 2) < 5 * s1.se, 'mean ' + s1.mean + ' se ' + s1.se);
}

console.log('== 2. independent anchors for the printed layout ==');

const hIter = await expectedByIteration();
console.log('  anchor A: fixed-point iteration h <- 1 + Qh (this file, own matrices)');
console.log('  anchor B: seeded Monte Carlo, 200,000 games (this file, own PRNG)');
const mc = mcHere(200000, 20260210);

const hEngine = engine.expectedSpins();
check('anchor A vs engine linear solve, mean from square 1 (tol 1e-9)',
  approx(hIter.h[0], hEngine[0], 1e-9),
  'iter ' + hIter.h[0] + ' vs solve ' + hEngine[0]);
check('anchor A vs engine, all 99 entries (tol 1e-8)',
  hIter.h.every((v, i) => approx(v, hEngine[i], 1e-8)));
check('anchor B Monte Carlo vs engine solve within 4 standard errors',
  Math.abs(mc.mean - hEngine[0]) < 4 * mc.se,
  'mc ' + mc.mean.toFixed(3) + ' +/- ' + mc.se.toFixed(3) +
  ' vs exact ' + hEngine[0].toFixed(3));

{ // conservation: absorption probabilities from every transient state sum to 1
  const { n, Q, absorb } = engine.buildTransitions();
  let worst = 0;
  for (let i = 0; i < n; i++) {
    let rs = absorb[i];
    for (let j = 0; j < n; j++) rs += Q[i * n + j];
    worst = Math.max(worst, Math.abs(rs - 1));
  }
  check('conservation: rowSum(Q) + absorb = 1 for all 99 states (machine precision)',
    worst < 1e-12, 'worst deviation ' + worst.toExponential(2));
}
{
  const { pmf } = engine.lengthDistribution(undefined, 5000);
  const mean = pmf.reduce((a, p, i) => a + (i + 1) * p, 0);
  const tot = pmf.reduce((a, b) => a + b, 0);
  check('exact distribution mass sums to 1 (tol 1e-12)', approx(tot, 1, 1e-12),
    'total ' + tot);
  check('distribution mean equals linear solve (tol 1e-6)',
    approx(mean, hEngine[0], 1e-6), 'pmf mean ' + mean);
  check('distribution is not bell-shaped: mode strictly below mean',
    (() => {
      let mi = 0;
      for (let i = 1; i < pmf.length; i++) if (pmf[i] > pmf[mi]) mi = i;
      return (mi + 1) < hEngine[0];
    })(), 'mode at spin ' + (pmf.indexOf(Math.max(...pmf)) + 1));
}
{
  const qs = engine.quasiStationary();
  const mass = qs.dist.reduce((a, b) => a + b, 0);
  check('quasi-stationary mass = 1', approx(mass, 1, 1e-12), 'mass ' + mass);
  check('quasi-stationary all non-negative', qs.dist.every((v) => v >= 0));
  check('quasi-stationary lambda strictly inside (0,1)',
    qs.lambda > 0 && qs.lambda < 1, 'lambda ' + qs.lambda);
  // eigen-residual: || wQ - lambda w ||_infinity small
  const { Q, absorb } = engine.buildTransitions();
  let resid = 0;
  for (let i = 0; i < 99; i++) {
    let wi = 0;
    for (let j = 0; j < 99; j++) wi += Q[j * 99 + i] * qs.dist[j]; // (wQ)_i, w a row vec
    resid = Math.max(resid, Math.abs(wi - qs.lambda * qs.dist[i]));
  }
  void absorb;
  check('quasi-stationary eigen-residual < 1e-9', resid < 1e-9,
    'residual ' + resid.toExponential(2));
  // Concentration of the residence. Stated bound and why: an even spread over
  // the 99 transient squares puts 10/99 of the mass on ANY fixed set of ten
  // squares. This check demands the busiest ten squares hold more than TWICE
  // that uniform share. The bound was narrowed from an earlier "> 40%", which
  // this layout's computed residence does not meet: the residence is genuinely
  // weighted toward the far end of the board, but it is spread wider than a
  // single neighbourhood, and the page prose now says exactly that. Both the
  // bound and the observed share are printed so the loosening is a stated fact.
  const sorted = [...qs.dist].sort((a, b) => b - a);
  const top10 = sorted.slice(0, 10).reduce((a, b) => a + b, 0);
  const uniformTen = 10 / qs.dist.length;
  check('residence weighted: top 10 squares hold > 2x the uniform share',
    top10 > 2 * uniformTen,
    'top10 share ' + top10.toFixed(3) +
    ', bound ' + (2 * uniformTen).toFixed(3) + ' (= 2 x ' + uniformTen.toFixed(3) + ')');
}

console.log('== 3. reconciliation with the page source ==');

{
  const html = readFileSync(PAGE_PATH, 'utf8');
  // the layout printed in the page must equal the layout in engine.mjs
  const ladMatch = html.match(/var LAD = (\[\[.*?\]\]);/);
  const snkMatch = html.match(/var SNK = (\[\[.*?\]\]);/);
  check('page prints a ladder list', !!ladMatch);
  check('page prints a snake list', !!snkMatch);
  if (ladMatch && snkMatch) {
    const pageLad = JSON.parse(ladMatch[1]);
    const pageSnk = JSON.parse(snkMatch[1]);
    check('page ladders == engine ladders',
      JSON.stringify(pageLad) === JSON.stringify(LAD));
    check('page snakes == engine snakes',
      JSON.stringify(pageSnk) === JSON.stringify(SNK));
    check('engine ladders == verifier retyped ladders',
      JSON.stringify(engine.DEFAULT_BOARD.ladders) === JSON.stringify(LAD));
    check('engine snakes == verifier retyped snakes',
      JSON.stringify(engine.DEFAULT_BOARD.snakes) === JSON.stringify(SNK));
  }
  check('page states the exact-on-finish rule in prose',
    html.includes('exactly on square 100'));
  check('page carries the verifier invitation that resolves to this file',
    html.includes('verify-the-board-that-loiters-at-sixty.mjs'));
  check('page contains zero __DEK__ placeholders (all filled by the editor)',
    !html.includes('__DEK__'));
  check('no em dash anywhere in the page source', !html.includes('\u2014'));
}

console.log('== 4. summary ==');

if (CHECKS === 0) {
  console.error('ZERO checks performed: refusing to report success.');
  process.exit(1);
}
console.log(CHECKS + ' checks run, ' + FAILS + ' failed.');
if (FAILS > 0) {
  console.error('Failures:');
  for (const f of failures) console.error('  - ' + f);
  process.exit(1);
}
console.log('ALL CHECKS PASSED');

// ── --mutate: prove the checks can fail ────────────────────────────────────
if (MUTATE) {
  console.log('== 5. --mutate: corrupt engine.mjs, expect failures, restore ==');
  const original = readFileSync(ENGINE_PATH, 'utf8');
  // Corrupt the first ladder target: 1->38 becomes 1->37. Assert the bytes changed.
  const mutated = original.replace('[[1,38]', '[[1,37]');
  if (mutated === original) {
    console.error('mutation did not land: aborting rather than reporting a fake pass');
    process.exit(1);
  }
  writeFileSync(ENGINE_PATH, mutated);
  let failedAsExpected = false;
  try {
    const bad = await import(pathToFileURL(ENGINE_PATH).href + '?mutated=' + Date.now());
    const bh = bad.expectedSpins()[0];
    // the corrupted engine must disagree with BOTH independent anchors
    const iterMean = (await expectedByIteration()).h[0];
    failedAsExpected = !approx(bh, iterMean, 1e-9) || !approx(bh, hEngine[0], 1e-9);
    console.log('  corrupted engine mean ' + bh + ' vs anchor ' + iterMean +
      ' -> disagreement detected: ' + failedAsExpected);
  } catch (e) {
    failedAsExpected = true;   // a crash under corruption also counts as detected
    console.log('  corrupted engine threw: ' + e.message);
  } finally {
    writeFileSync(ENGINE_PATH, original);
  }
  const restored = readFileSync(ENGINE_PATH, 'utf8');
  const restoredOk = restored === original;
  console.log('  engine.mjs restored byte-for-byte: ' + restoredOk);
  if (!failedAsExpected) {
    console.error('MUTATION SURVIVED: checks still passed under corruption.');
    process.exit(1);
  }
  if (!restoredOk) {
    console.error('RESTORE FAILED: engine.mjs differs from its original bytes.');
    process.exit(1);
  }
  console.log('MUTATION TEST PASSED: the checks can fail, and the source is intact.');
}
