#!/usr/bin/env node
// verify.mjs — the offline check behind the portal "Past the Last Case".
//
// The portal's whole claim is that a finite test corroborates and a kernel proof
// closes the gap. This verifier holds BOTH sides honest:
//
//   1. It RE-DERIVES, from scratch, every finite check the page demonstrates
//      (the √2 non-solution sweep, the √n verdicts, Cassini's ±1, the mutilated
//      board's 30≠32, Nim progress/closure by retrograde, the zero-one reduction,
//      the crystallographic pivot) — so the numbers on the page are reproduced,
//      not asserted.
//   2. It checks the SOURCE-LEVEL invariants of all seven Lean proofs that could
//      rot: the file exists, has ZERO `import` lines, and contains no `sorry`,
//      `admit`, or `native_decide`; and it has a verify.sh. It greps each theorem
//      name in its file, and cross-checks the served page carries every member
//      title, theorem name, and axiom footprint.
//   3. If `lean` is on PATH, it RUNS each proof's verify.sh and asserts the axiom
//      footprint — so the check is complete the moment a reader has Lean. (This
//      build could not reach the Lean toolchain host; see ground-truth.json →
//      build_honesty. The kernel re-check is one command away.)
//
//   node research/past-the-last-case/verify.mjs        # all checks
//   node research/past-the-last-case/verify.mjs --lean # force-require lean present
//
// Zero dependencies. Exit code 0 iff every check passes.

import { readFileSync, existsSync } from 'node:fs';
import { execSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, '..', '..');
const GT = JSON.parse(readFileSync(join(HERE, 'ground-truth.json'), 'utf8'));
const FORCE_LEAN = process.argv.includes('--lean');

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) { pass++; console.log(`  ✓ ${name}${extra ? '  ' + extra : ''}`); }
  else { fail++; console.log(`  ✗ ${name}${extra ? '  ' + extra : ''}`); }
};
const section = (s) => console.log(`\n${s}`);

// ---------- small integer helpers (BigInt where a product can exceed 2^53) ----------
const isqrt = (n) => { if (n < 2n) return n; let x = n, y = (x + 1n) / 2n; while (y < x) { x = y; y = (x + n / x) / 2n; } return x; };
const isPerfectSquare = (n) => { const r = isqrt(n); return r * r === n; };

// =====================================================================
section('THE FINITE CHECKS — re-derived from scratch (the pages’ numbers)');
// =====================================================================

// (1) √2 irrational, sampled: no b in [1, bound] makes 2b² a perfect square.
{
  const bound = BigInt(GT.finite_checks.sqrt2_no_solution_bound);
  let found = null;
  for (let b = 1n; b <= bound; b++) { if (isPerfectSquare(2n * b * b)) { found = b; break; } }
  ok(`incommensurable  no a²=2b² for b ≤ ${bound}`, found === null, `(the check the proof outruns)`);
}

// (2) √n verdicts: the single theorem's two outcomes.
{
  const irr = GT.finite_checks.sqrt_verdicts.irrational;
  const rat = GT.finite_checks.sqrt_verdicts.rational;
  let good = true, note = [];
  for (const n of irr) if (isPerfectSquare(BigInt(n))) { good = false; note.push(`${n} is square!`); }
  for (const [n, k] of Object.entries(rat)) { const r = isqrt(BigInt(n)); if (!(r * r === BigInt(n) && r === BigInt(k))) { good = false; note.push(`${n}→${k}?`); } }
  ok('which-roots  non-squares irrational, squares = k', good, note.join(' '));
}

// (3) Cassini: fib(n+1)² − fib(n)·fib(n+2) = (−1)ⁿ, hence never 0.
{
  const R = GT.finite_checks.cassini_range;
  const fib = [0n, 1n]; for (let i = 2; i <= R + 2; i++) fib[i] = fib[i - 1] + fib[i - 2];
  let allPM1 = true, neverZero = true;
  for (let n = 0; n <= R; n++) {
    const c = fib[n + 1] * fib[n + 1] - fib[n] * fib[n + 2];
    const want = (n % 2 === 0) ? 1n : -1n;
    if (c !== want) allPM1 = false;
    if (c === 0n) neverZero = false;
  }
  ok(`the-missing-square  gap = (−1)ⁿ and ≠ 0 for n ≤ ${R}`, allPM1 && neverZero);
  // the two named dissection cases
  const c = (n) => fib[n + 1] * fib[n + 1] - fib[n] * fib[n + 2];
  const cases = GT.finite_checks.cassini_cases;
  ok('the-missing-square  n=6 gap +1, n=5 gap −1 (8×8 vs 5×13)', Number(c(6)) === cases['6'] && Number(c(5)) === cases['5']);
}

// (4) Mutilated chessboard: remove two opposite corners → 30 light, 32 dark.
{
  const light = (x, y) => (x + y) % 2 === 0;
  let L = 0, D = 0;
  for (let x = 0; x < 8; x++) for (let y = 0; y < 8; y++) {
    if ((x === 0 && y === 0) || (x === 7 && y === 7)) continue; // opposite corners
    if (light(x, y)) L++; else D++;
  }
  const exp = GT.finite_checks.chessboard;
  ok(`the-mutilated-chessboard  ${L} light ≠ ${D} dark (need equal)`, L === exp.light && D === exp.dark);
}

// (5) Nim: by retrograde analysis over a finite box, P-position ⇔ nim-sum = 0.
{
  const M = GT.finite_checks.nim_retrograde_max_heap, K = GT.finite_checks.nim_heaps;
  const size = M + 1;
  const idx = (h) => h.reduce((a, v) => a * size + v, 0);
  const total = size ** K;
  const win = new Array(total).fill(null); // true = N (win for mover), false = P (loss)
  // enumerate positions in nondecreasing total-stone order via BFS-free DP:
  const heapsOf = (id) => { const h = []; for (let i = 0; i < K; i++) { h.unshift(id % size); id = Math.floor(id / size); } return h; };
  // memoized: a position is a WIN if some move leads to a LOSS.
  const solve = (id) => {
    if (win[id] !== null) return win[id];
    const h = heapsOf(id);
    win[id] = false; // provisional (empty position is a loss for the mover)
    for (let i = 0; i < K; i++) {
      for (let take = 1; take <= h[i]; take++) {
        const nh = h.slice(); nh[i] -= take;
        if (solve(idx(nh)) === false) { win[id] = true; return true; }
      }
    }
    return win[id];
  };
  let agree = true, n = 0;
  for (let id = 0; id < total; id++) {
    const h = heapsOf(id);
    const nimsum = h.reduce((a, v) => a ^ v, 0);
    const isP = solve(id) === false;
    if (isP !== (nimsum === 0)) agree = false;
    n++;
  }
  ok(`the-strategy...binary  P-position ⇔ nim-sum=0 over ${n} positions (heaps ${K}×[0..${M}])`, agree);
}

// (6) Zero-one principle: on a finite width, (sorts all 0/1) ⇔ (sorts all inputs).
{
  const n = GT.finite_checks.zero_one_width;
  // run a comparator network (list of [i,j], i<j → ascending) on a vector.
  const run = (net, v) => { v = v.slice(); for (const [i, j] of net) if (v[i] > v[j]) { const t = v[i]; v[i] = v[j]; v[j] = t; } return v; };
  const sorted = (v) => v.every((x, k) => k === 0 || v[k - 1] <= x);
  // all 2^n binary inputs
  const bins = []; for (let m = 0; m < (1 << n); m++) bins.push(Array.from({ length: n }, (_, k) => (m >> k) & 1));
  // all n! permutations of 0..n-1
  const perms = (() => { const out = []; const go = (a, r) => { if (!r.length) { out.push(a); return; } r.forEach((x, k) => go(a.concat(x), r.slice(0, k).concat(r.slice(k + 1)))); }; go([], [...Array(n).keys()]); return out; })();
  const sortsAll01 = (net) => bins.every((b) => sorted(run(net, b)));
  const sortsAll = (net) => perms.every((p) => sorted(run(net, p)));
  // sample random networks (deterministic LCG so the run is reproducible)
  let seed = 0x2545F491, rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
  let agree = true, tested = 0;
  for (let t = 0; t < 4000; t++) {
    const len = 2 + Math.floor(rnd() * 10);
    const net = [];
    for (let g = 0; g < len; g++) { let i = Math.floor(rnd() * n), j = Math.floor(rnd() * n); if (i === j) { j = (j + 1) % n; } if (i > j) { const s = i; i = j; j = s; } net.push([i, j]); }
    if (sortsAll01(net) !== sortsAll(net)) { agree = false; break; }
    tested++;
  }
  ok(`two-symbols-are-enough  sorts-all-0/1 ⇔ sorts-all, ${tested} random nets (n=${n})`, agree);
}

// (7) Crystallographic pivot: p(t) = t⁴ − 3t² + 1 is never 0 over ℤ; 5 is not a square.
{
  const R = GT.finite_checks.pivot_range;
  let neverZero = true, identity = true;
  for (let t = -R; t <= R; t++) {
    const T = BigInt(t);
    const p = T ** 4n - 3n * T * T + 1n;
    if (p === 0n) neverZero = false;
    // 4·p(t) = (2t²−3)² − 5
    if (4n * p !== (2n * T * T - 3n) ** 2n - 5n) identity = false;
  }
  let noSqrt5 = true; for (let m = -R; m <= R; m++) if (m * m === 5) noSqrt5 = false;
  ok(`seventeen-and-no-more  p(t)=t⁴−3t²+1 ≠ 0, 4p=(2t²−3)²−5, no m²=5 (|t|≤${R})`, neverZero && identity && noSqrt5);
}

// =====================================================================
section('THE SEVEN PROOFS — source-level invariants (what could rot)');
// =====================================================================
for (const m of GT.members) {
  const fp = join(ROOT, m.proofFile);
  const vs = join(ROOT, m.verifyScript);
  if (!existsSync(fp)) { ok(`${m.slug}  proof file present`, false, m.proofFile); continue; }
  const src = readFileSync(fp, 'utf8');
  const importLines = (src.match(/^import\s/gm) || []).length;
  // Strip Lean comments first: the proofs' own docstrings *mention* "sorry" /
  // "native_decide" in prose (to say they avoid them). We check the CODE only.
  const code = src.replace(/\/-[\s\S]*?-\//g, '').replace(/--[^\n]*/g, '');
  const holes = /\bsorry\b|\badmit\b|native_decide/.test(code);
  const hasThm = src.includes(m.theoremName);
  const hasVs = existsSync(vs);
  ok(`${m.slug}  zero imports · no sorry/admit/native_decide · ${m.theoremName} present · verify.sh`,
    importLines === 0 && !holes && hasThm && hasVs,
    `(imports=${importLines})`);
}

// =====================================================================
section('THE SERVED PAGE — carries every member, theorem name, footprint');
// =====================================================================
{
  const pagePath = join(ROOT, 'public', 'strata', 'past-the-last-case', 'index.html');
  if (!existsSync(pagePath)) { ok('index.html present', false); }
  else {
    const html = readFileSync(pagePath, 'utf8');
    for (const m of GT.members) {
      const hasTitle = html.includes(m.title);
      const hasThm = html.includes(m.theoremName);
      ok(`page carries "${m.title}" + ${m.theoremName}`, hasTitle && hasThm);
    }
    ok('page states the [propext, Quot.sound] footprint', html.includes('propext') && html.includes('Quot.sound'));
    ok('page states the finite-vs-proof thesis (no last case)', /last case/i.test(html));
    ok('page is honest about the un-run kernel this build', /github|toolchain|could not|one command away/i.test(html));
  }
}

// =====================================================================
section('THE KERNEL — run each verify.sh iff `lean` is on PATH');
// =====================================================================
{
  let leanPresent = false;
  try { execSync('command -v lean', { stdio: 'ignore' }); leanPresent = true; } catch { }
  if (!leanPresent && !FORCE_LEAN) {
    console.log('  • lean not on PATH — skipping the kernel re-run (the reproducible check).');
    console.log('    Install it and re-run, or run any `bash <proofDir>/verify.sh` yourself.');
  } else if (!leanPresent && FORCE_LEAN) {
    ok('lean present (--lean required)', false);
  } else {
    for (const m of GT.members) {
      try {
        const out = execSync(`bash ${join(ROOT, m.verifyScript)}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
        // Judge by the ACTUAL `#print axioms` lines, not by prose: each verify.sh
        // echoes a reminder ("NO sorryAx, NO Classical.choice") and "no errors
        // above", so a naive /sorryAx|Classical.choice|error/ match false-fails on
        // its own text. Parse the real footprints and detect only genuine Lean
        // errors (file.lean:L:C: error:).
        const axLists = [...out.matchAll(/depends on axioms:\s*\[([^\]]*)\]/g)].map(x => x[1]);
        const hasLeanError = /\.lean:\d+:\d+: error:/i.test(out);
        const footprintClean = axLists.length > 0 && axLists.every(f =>
          f.split(',').map(s => s.trim()).filter(Boolean).every(a => a === 'propext' || a === 'Quot.sound'));
        ok(`${m.slug}  kernel typecheck + footprint`, footprintClean && !hasLeanError);
      } catch (e) {
        ok(`${m.slug}  kernel typecheck`, false, (e.stdout || e.message || '').toString().split('\n')[0]);
      }
    }
  }
}

// ---------- tally ----------
console.log(`\n${'─'.repeat(56)}`);
console.log(`  ${pass} passed, ${fail} failed`);
if (fail) { console.log('  FAIL'); process.exit(1); }
console.log('  ALL CHECKS PASS');
