#!/usr/bin/env node
// Verifier for the stratum "Which Square Roots Are Irrational?" (P5, 2026-06-29).
//
//   node research/which-roots-are-irrational/verify.mjs
//
// Exit 0 and "ALL CHECKS PASS" iff every claim holds. Three honest buckets:
//
//   MATH — the numbers the page recomputes live, re-derived here with exact BigInt
//          arithmetic and checked against independently-known facts: the
//          continued-fraction partial quotients and periods of √2…√14; that the
//          expansion terminates exactly for perfect squares; the convergents p/q;
//          and that the integer gap p² − n·q² is nonzero for non-squares and 0 for
//          squares (the finite witness the proof makes universal).
//
//   TEXT — key verified claims in the prose stratum
//          (src/content/strata/which-roots-are-irrational.md) are present
//          verbatim, and the immersive page asserts the same headline facts.
//
//   LEAN — the central theorem is machine-checked. STATIC: the proof file exists,
//          has zero imports, no `sorry`, no `Classical.choice`, and prints its
//          axioms. LIVE (when `lean` is on PATH): actually typecheck it and confirm
//          every theorem's footprint is exactly [propext] or [propext, Quot.sound].

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/which-roots-are-irrational.md");
const HTML = resolve(ROOT, "public/strata/which-roots-are-irrational/index.html");
const LEAN = resolve(__dir, "lean", "SqrtN.lean");

let fails = 0;
const log = [];
function check(name, ok, detail = "") {
  if (ok) { log.push(`  ok   ${name}`); }
  else { fails++; log.push(`  FAIL ${name}${detail ? "  — " + detail : ""}`); }
}

// ---------- exact integer helpers ----------
function isqrt(n) {
  n = BigInt(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;
}
function isSquare(n) { const r = isqrt(n); return r * r === BigInt(n); }
function cf(nn, max) {
  const n = BigInt(nn), a0 = isqrt(n);
  if (a0 * a0 === n) return { a0, terms: [a0], terminates: true, periodLen: 0 };
  const terms = [a0]; let m = 0n, d = 1n, a = a0, pl = 0;
  for (let i = 0; i < max; i++) {
    m = d * a - m; d = (n - m * m) / d; a = (a0 + m) / d; terms.push(a);
    if (pl === 0 && a === 2n * a0) pl = terms.length - 1;
    if (pl && terms.length - 1 >= pl * 2 + 1) break;
  }
  return { a0, terms, terminates: false, periodLen: pl };
}
function convergents(terms) {
  const out = []; let pm1 = 0n, qm1 = 1n, p0 = 1n, q0 = 0n;
  for (const a of terms) {
    const p = a * p0 + pm1, q = a * q0 + qm1;
    pm1 = p0; qm1 = q0; p0 = p; q0 = q; out.push({ p, q });
  }
  return out;
}

// ---------- MATH ----------
// Independently-known continued-fraction periods of √n (the block after a0).
// Source: standard tables (e.g. OEIS A003285 period lengths; the blocks are the
// classic expansions). Each is verified by recomputation, then matched here.
const KNOWN = {
  2: [2], 3: [1, 2], 5: [4], 6: [2, 4], 7: [1, 1, 1, 4], 8: [1, 4],
  10: [6], 11: [3, 6], 12: [2, 6], 13: [1, 1, 1, 1, 6], 14: [1, 2, 1, 6],
};
for (const [nStr, block] of Object.entries(KNOWN)) {
  const n = Number(nStr), r = cf(n, 40);
  const got = r.terms.slice(1, 1 + r.periodLen).map(Number);
  check(`MATH √${n} continued-fraction period = [${block}]`,
    !r.terminates && JSON.stringify(got) === JSON.stringify(block), `got [${got}]`);
  // the period ends with 2·a0 (a classic fact about √n)
  check(`MATH √${n} period ends with 2·⌊√${n}⌋ = ${2 * Number(r.a0)}`,
    Number(r.terms[r.periodLen]) === 2 * Number(r.a0));
}
// perfect squares terminate; non-squares do not (within the window)
for (const sq of [1, 4, 9, 16, 25, 100, 144, 10000]) {
  const r = cf(sq, 40);
  check(`MATH √${sq} terminates (= ${r.a0}, rational)`, r.terminates && r.a0 * r.a0 === BigInt(sq));
}
for (let n = 2; n <= 50; n++) {
  if (isSquare(n)) continue;
  const r = cf(n, 60);
  check(`MATH √${n} does not terminate within window`, !r.terminates && r.periodLen > 0);
}
// convergents: gap p²−n·q² is nonzero for non-squares, zero for squares
for (const n of [2, 3, 5, 6, 7, 13]) {
  const c = convergents(cf(n, 20).terms), N = BigInt(n);
  const gaps = c.map(({ p, q }) => p * p - N * q * q);
  check(`MATH √${n} every convergent gap p²−n·q² ≠ 0`, gaps.every((g) => g !== 0n));
  check(`MATH √${n} convergent gaps stay bounded (|gap| ≤ 2·⌊√n⌋+1)`,
    gaps.every((g) => (g < 0n ? -g : g) <= 2n * isqrt(n) + 1n));
}
// the classic check: √2 best fractions and their ±1 Pell gaps
{
  const c = convergents(cf(2, 8).terms);
  check("MATH √2 convergents are 1/1, 3/2, 7/5, 17/12",
    ["1/1", "3/2", "7/5", "17/12"].every((s, i) => `${c[i].p}/${c[i].q}` === s));
  check("MATH √2 Pell gaps alternate −1, +1", `${c[0].p * c[0].p - 2n}` === "-1" &&
    (c[1].p * c[1].p - 2n * c[1].q * c[1].q) === 1n);
  const exact = (3n / 2n); void exact;
}
// perfect-square: a fraction can hit exactly (gap 0)
check("MATH √9: 3/1 has gap 0 (exact)", (3n * 3n - 9n * 1n * 1n) === 0n);

// ---------- TEXT ----------
const md = existsSync(MD) ? readFileSync(MD, "utf8") : "";
check("TEXT prose stratum present", md.length > 0);
const mdClaims = [
  "the only square roots of whole numbers that come out whole are the perfect squares",
  "A whole number's square root is irrational unless the number is a perfect",
  "r = a mod b",
  "b divides a·r",
  "A² = n·r²",
  "the whole numbers cannot descend forever",
  "no parity and no prime factorisation",
  "[propext, Quot.sound]",
  "zero imports",
];
for (const c of mdClaims) check(`TEXT prose contains: "${c.slice(0, 40)}…"`, md.includes(c));

const html = existsSync(HTML) ? readFileSync(HTML, "utf8") : "";
check("TEXT immersive page present", html.length > 0);
const htmlClaims = [
  "Which square roots are irrational",
  "It isn't special",
  "descent by remainder",
  "b divides a·r",
  "A² = n·r²",
  "Checked by the kernel",
  "sqrt_rational_is_square",
  "no <code>sorryAx</code>",
  "research/which-roots-are-irrational/lean/install-lean.sh",
];
for (const c of htmlClaims) check(`TEXT page asserts: "${c.slice(0, 40)}…"`, html.includes(c));
// the page must carry the honest "this is corroboration, not the proof" caveat
check("TEXT page honestly labels the CF as corroboration, not proof",
  /Lagrange|corroboration you can watch, not the proof/.test(html));
// SEO head sanity
check("TEXT page has canonical URL", html.includes('rel="canonical" href="https://artwaste.land/strata/which-roots-are-irrational/"'));
check("TEXT page has JSON-LD Article", html.includes('"@type":"Article"'));

// ---------- LEAN ----------
check("LEAN proof file present (lean/SqrtN.lean)", existsSync(LEAN));
if (existsSync(LEAN)) {
  const src = readFileSync(LEAN, "utf8");
  const code = src.replace(/\/-[\s\S]*?-\//g, "").replace(/--[^\n]*/g, "");
  const importLines = src.split("\n").filter((l) => /^\s*import\b/.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 sqrt_rational_is_square (∀ n b a, a²=n·b² → ∃k k²=n)",
    /theorem\s+sqrt_rational_is_square\b/.test(src));
  check("LEAN proves irrational_of_not_square", /theorem\s+irrational_of_not_square\b/.test(src));
  check("LEAN proves the classic cases (√2, √3, √5, √6, √7)",
    ["two", "three", "five", "six", "seven"].every((w) => new RegExp(`irrational_sqrt_${w}\\b`).test(src)));
  check("LEAN prints its axiom footprint (#print axioms)", /#print\s+axioms/.test(src));

  let haveLean = false;
  try { execSync("command -v lean", { stdio: "ignore", shell: "/bin/bash" }); haveLean = true; } catch { /* no lean */ }
  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 SqrtN.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, axiom lines printed", ax.length >= 5, `got ${ax.length}`);
      const clean = ax.length > 0 && ax.every((a) => a === "propext" || a === "propext, Quot.sound");
      check("LEAN axiom footprint is [propext] / [propext, Quot.sound] (no sorryAx, no choice)",
        clean, ax.join(" ; "));
    }
  } else {
    log.push("  INFO LEAN live typecheck skipped (lean not on PATH) — run research/which-roots-are-irrational/lean/verify.sh");
  }
}

// ---------- report ----------
console.log("\nWHICH SQUARE ROOTS ARE IRRATIONAL — verifier\n");
console.log(log.join("\n"));
console.log("");
if (fails === 0) { console.log("ALL CHECKS PASS"); process.exit(0); }
else { console.log(`${fails} CHECK(S) FAILED`); process.exit(1); }
