#!/usr/bin/env node
// Verifier for the immersive form of "Incommensurable" (the founding stratum,
// 2026-05-31), given an immersive second pass on 2026-06-21.
//
//   node research/incommensurable-immersive/verify.mjs
//
// Exit 0 and "ALL CHECKS PASS" iff every claim holds.
//
// What this checks falls in three honest buckets:
//
//   MATH  — the proof the sonnet carries is sound, checked by exact integer
//           arithmetic well past any human eye: the parity lemma, the "even
//           square ⇒ even root" step, and the bottom line that a²=2b² has no
//           positive-integer solution at all (so the descent has no floor).
//
//   TEXT  — every word the immersive page puts on screen (the 14 verse lines,
//           and for each line the "what it carries" and "where the form shows"
//           apparatus) is CHARACTER-IDENTICAL to the canonical prose stratum
//           src/content/strata/incommensurable.md. The page may not drift from
//           the verified text. (This is the film-register discipline applied to
//           an interactive page.)
//
//   FORM  — the structural facts the page asserts about the poem as an object:
//           it is 14 lines, and its end-rhymes group as ABAB CDCD EFEF GG.
//
// What this deliberately does NOT certify: the line-by-line SCANSION. Scansion
// is an interpretive act, not a computation, and the page says so in its own
// apparatus. The verifier checks the things that are checkable and leaves the
// reading honestly labelled as a reading.

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

const __dir = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dir, "..", "..");
const MD = resolve(ROOT, "src/content/strata/incommensurable.md");
const HTML = resolve(ROOT, "public/strata/incommensurable/index.html");

let PASS = true;
const log = [];
function check(name, cond, detail = "") {
  const ok = !!cond;
  PASS = PASS && ok;
  log.push(`${ok ? "PASS" : "FAIL"}  ${name}${detail ? "  —  " + detail : ""}`);
  if (!ok) console.error(`FAIL: ${name}${detail ? " — " + detail : ""}`);
}

// ── integer square root over BigInt (Newton) ──────────────────────────────
function isqrt(n) {
  if (n < 0n) throw new Error("isqrt of negative");
  if (n < 2n) return n;
  let x = n, y = (x + 1n) >> 1n;
  while (y < x) { x = y; y = (x + n / x) >> 1n; }
  return x;
}
const isSquare = (n) => { const r = isqrt(n); return r * r === n; };

// ───────────────────────────────────────────────────────────────────────────
// MATH 1 — the parity lemma the verse names twice but proves neither time:
//   an odd number squared is odd; equivalently, an even square has an even root.
// (2k+1)² = 4k²+4k+1 = 2(2k²+2k)+1 is odd, for every k. Checked exactly.
{
  let lemmaOk = true, evenRootOk = true, bad = "";
  const N = 200000n;
  for (let a = 1n; a <= N; a++) {
    const sq = a * a;
    const aEven = (a % 2n) === 0n;
    const sqEven = (sq % 2n) === 0n;
    // an odd a must give an odd square:
    if (!aEven && sqEven) { lemmaOk = false; bad = `a=${a}`; break; }
    // the step the proof actually uses: a² even ⇒ a even:
    if (sqEven && !aEven) { evenRootOk = false; bad = `a=${a}`; break; }
  }
  check("MATH parity lemma: odd² is odd (a=1..2e5)", lemmaOk, bad);
  check("MATH even square ⇒ even root (a=1..2e5)", evenRootOk, bad);
}

// MATH 2 — the bottom line. a² = 2b² has NO positive-integer solution: for every
// b in range, 2b² is never a perfect square. (The sonnet's descent/contradiction
// is the real proof; this is exhaustive corroboration with no floor in sight.)
{
  let none = true, witness = "";
  for (let b = 1n; b <= 3000000n; b++) {
    if (isSquare(2n * b * b)) { none = false; witness = `b=${b}`; break; }
  }
  check("MATH a²=2b² has no solution (b=1..3e6)", none, witness);
}

// MATH 3 — the two algebraic moves the middle of the poem makes are identities,
// not luck: from a=2c, a²=4c²; and 4c²=2b² ⇒ b²=2c². Checked over a grid.
{
  let idOk = true, ex = "";
  for (let b = 0n; b <= 600n; b++) {
    for (let c = 0n; c <= 600n; c++) {
      const a = 2n * c;
      if (a * a !== 4n * c * c) { idOk = false; ex = `c=${c}`; }
      // 4c² = 2b²  ⟺  b² = 2c²  (the line-9 halving)
      if ((4n * c * c === 2n * b * b) !== (b * b === 2n * c * c)) { idOk = false; ex = `b=${b},c=${c}`; }
      if (!idOk) break;
    }
    if (!idOk) break;
  }
  check("MATH a=2c ⇒ a²=4c², and 4c²=2b² ⇔ b²=2c² (grid)", idOk, ex);
}

// ───────────────────────────────────────────────────────────────────────────
// Parse the canonical prose stratum.
const md = readFileSync(MD, "utf8");

// (a) the 14 verse lines, from <ol class="verse"> … </ol>
const verseBlock = md.match(/<ol class="verse">([\s\S]*?)<\/ol>/);
const verse = verseBlock
  ? [...verseBlock[1].matchAll(/<li>([\s\S]*?)<\/li>/g)].map((m) => m[1].trim())
  : [];

// (b) the line-by-line table (§III): rows "| n | carries | seam |"
const tableRows = [...md.matchAll(/^\|\s*(\d+)\s*\|([^\n]*?)\|([^\n]*?)\|\s*$/gm)]
  .map((m) => ({ n: +m[1], carries: m[2].trim(), seam: m[3].trim() }))
  .filter((r) => r.n >= 1 && r.n <= 14)
  .sort((a, b) => a.n - b.n);

// (c) the 7 proof steps (§II), from <ol class="proof"> … </ol>
const proofBlock = md.match(/<ol class="proof">([\s\S]*?)<\/ol>/);
const proof = proofBlock
  ? [...proofBlock[1].matchAll(/<li>([\s\S]*?)<\/li>/g)].map((m) => m[1].trim())
  : [];

check("TEXT source has 14 verse lines", verse.length === 14, `got ${verse.length}`);
check("TEXT source table has 14 rows", tableRows.length === 14, `got ${tableRows.length}`);
check("TEXT source has 7 proof steps", proof.length === 7, `got ${proof.length}`);

// ───────────────────────────────────────────────────────────────────────────
// Parse the immersive page's embedded data and compare to source, verbatim.
const html = readFileSync(HTML, "utf8");
const dataMatch = html.match(
  /<script id="lines-data" type="application\/json">([\s\S]*?)<\/script>/
);
check("TEXT page embeds lines-data JSON", !!dataMatch);

if (dataMatch) {
  let parsed = {};
  try { parsed = JSON.parse(dataMatch[1]); } catch (e) { check("TEXT lines-data parses", false, e.message); }
  const data = parsed.lines || [];
  const pageProof = parsed.proof || [];
  check("TEXT page carries 14 lines", data.length === 14, `got ${data.length}`);
  check("TEXT page carries 7 proof steps", pageProof.length === 7, `got ${pageProof.length}`);

  let proofOk = true, proofBad = "";
  for (let i = 0; i < 7; i++) {
    if (pageProof[i] !== proof[i]) { proofOk = false; proofBad ||= `proof step ${i + 1}: page="${pageProof[i]}" md="${proof[i]}"`; }
  }
  check("TEXT page proof steps ≡ source §II, verbatim", proofOk, proofBad);

  let verseOk = true, carriesOk = true, seamOk = true, scanOk = true, firstBad = "";
  for (let i = 0; i < 14; i++) {
    const d = data[i] || {};
    if (d.verse !== verse[i]) { verseOk = false; firstBad ||= `verse L${i + 1}: page="${d.verse}" md="${verse[i]}"`; }
    const row = tableRows.find((r) => r.n === i + 1) || {};
    if (d.carries !== row.carries) { carriesOk = false; firstBad ||= `carries L${i + 1}: page="${d.carries}" md="${row.carries}"`; }
    if (d.seam !== row.seam) { seamOk = false; firstBad ||= `seam L${i + 1}: page="${d.seam}" md="${row.seam}"`; }
    // scansion is interpretive, but must at least be well-formed: an array of
    // {syl,stress} with stress ∈ {S,U}, so nothing on screen is undefined.
    if (!Array.isArray(d.scan) || d.scan.length < 9 ||
        !d.scan.every((s) => typeof s.syl === "string" && (s.stress === "S" || s.stress === "U"))) {
      scanOk = false; firstBad ||= `scan L${i + 1} malformed`;
    }
  }
  check("TEXT page verse ≡ source, verbatim", verseOk, firstBad);
  check("TEXT page 'what it carries' ≡ source §III", carriesOk, firstBad);
  check("TEXT page 'where the form shows' ≡ source §III", seamOk, firstBad);
  check("FORM scansion data well-formed (S/U per syllable)", scanOk, firstBad);

  // FORM — the rhyme scheme the page claims, ABAB CDCD EFEF GG, read off the
  // declared end-rhyme class of each line. The classes are a stated phonetic
  // reading (confined/behind = A, b/free = B, …); the check is that they pattern.
  const SCHEME = "ABABCDCDEFEFGG";
  let scheme = data.map((d) => d.rhyme || "?").join("");
  check("FORM end-rhymes group as ABAB CDCD EFEF GG", scheme === SCHEME, `got ${scheme}`);

  // and the rhyme classes must actually be consistent: same class ⇒ a declared
  // rhyme partner exists; we check each class has exactly the right multiplicity.
  const counts = {};
  for (const d of data) counts[d.rhyme] = (counts[d.rhyme] || 0) + 1;
  const wellPaired = Object.values(counts).every((c) => c === 2);
  check("FORM every rhyme class is a pair", wellPaired, JSON.stringify(counts));
}

// ───────────────────────────────────────────────────────────────────────────
// LEAN — the machine-checked layer (§VI). The JS above samples; this asserts the
// kernel-checked proof artifact is present and honest. Two modes:
//   STATIC (always) — the file exists, has ZERO imports, no `sorry`, no
//     `Classical.choice`, and declares the named theorems + their axiom prints.
//   LIVE  (when `lean` is on PATH) — actually typecheck it and confirm every
//     theorem's axiom footprint is exactly [propext, Quot.sound], NO sorryAx.
const LEAN = resolve(__dir, "lean", "Sqrt2.lean");
check("LEAN proof file present (lean/Sqrt2.lean)", existsSync(LEAN));
if (existsSync(LEAN)) {
  const src = readFileSync(LEAN, "utf8");
  // Strip Lean comments (block `/- … -/` and line `-- …`) before scanning the
  // *code* — the prose in this file documents the ABSENCE of `sorry`/choice, so a
  // raw text match would false-positive on its own honesty notes.
  const code = src.replace(/\/-[\s\S]*?-\//g, "").replace(/--[^\n]*/g, "");
  // zero imports: no line beginning with `import ` — the kernel is the only dependency.
  const importLines = code.split("\n").filter((l) => /^\s*import\s/.test(l));
  check("LEAN zero imports (kernel is the only trusted component)", importLines.length === 0,
    importLines.join(" | "));
  check("LEAN no `sorry` placeholder (code, comments stripped)", !/\bsorry\b/.test(code));
  check("LEAN no `Classical.choice` (code, comments stripped)", !/Classical\.choice/.test(code));
  check("LEAN proves no_pos_solution (∀ a b, a²=2b² → b=0)", /theorem\s+no_pos_solution\b/.test(src));
  check("LEAN proves sqrt_two_irrational", /theorem\s+sqrt_two_irrational\b/.test(src));
  check("LEAN prints its axiom footprint (#print axioms)", /#print\s+axioms/.test(src));

  // LIVE typecheck, only if lean is installed (so CI/build without Lean still passes
  // the static checks and says so honestly).
  let haveLean = false;
  try { execSync("command -v lean", { stdio: "ignore", shell: "/bin/bash" }); haveLean = true; } catch {}
  if (haveLean) {
    let out = "";
    try {
      out = execSync(`lean ${JSON.stringify(LEAN)}`, {
        encoding: "utf8", env: { ...process.env, PATH: `${process.env.HOME}/.elan/bin:${process.env.PATH}` },
      });
    } catch (e) { out = (e.stdout || "") + (e.stderr || ""); check("LEAN kernel typecheck (lean Sqrt2.lean)", false, out.slice(0, 400)); }
    if (out) {
      const ax = [...out.matchAll(/depends on axioms: \[([^\]]*)\]/g)].map((m) => m[1].trim());
      check("LEAN kernel typechecks, 3 theorems' axioms printed", ax.length === 3, `got ${ax.length}`);
      const clean = ax.length > 0 && ax.every((a) => a === "propext, Quot.sound");
      check("LEAN axiom footprint is exactly [propext, Quot.sound] (no sorryAx, no choice)", clean, ax.join(" ; "));
    }
  } else {
    log.push("INFO  LEAN live typecheck skipped (lean not on PATH) — run research/incommensurable-immersive/lean/verify.sh");
  }
}

// ───────────────────────────────────────────────────────────────────────────
console.log("\n" + log.join("\n"));
console.log("\n" + (PASS ? "ALL CHECKS PASS" : "SOME CHECKS FAILED"));
process.exit(PASS ? 0 : 1);
