#!/usr/bin/env node
// Verifier for the EIGHTH mode of the stratum "Proof / Poem: Euclid's Infinitude
// of Primes in Seven Modes"
//   page: public/strata/proof-poem-seven-modes/index.html
//   live: https://artwaste.land/strata/proof-poem-seven-modes/
//
// The claim (Euclid, Elements IX.20): there is no largest prime — for every n there
// is a prime p > n. Euclid's construction: from n build N = n! + 1; N > 1, so N has
// a prime factor p; that p divides no number in 2..n (each of those divides n!, and a
// common factor of n! and n!+1 would divide 1); therefore p > n.
//
// This verifier recomputes the construction from scratch in BigInt: it confirms that
// N = n!+1 is coprime to every integer 2..n (the whole force of the argument), exhibits
// an explicit prime > n for many n by factoring N, and checks the classic honesty point
// that N need NOT itself be prime (2·3·5·7·11·13 + 1 = 30031 = 59·509). All of this is
// finite corroboration; the UNBOUNDED statement "for EVERY n" is what the companion Lean
// proof settles. When `lean` is on PATH this script runs the kernel and asserts the
// proof's axiom footprint is [propext, Quot.sound] — no sorry, no Classical.choice, no
// native_decide.
//
// Run:  node research/proof-poem-seven-modes/verify.mjs
// Exit: 0 if every check passes, 1 otherwise.  No dependencies (Node 18+).

import { execSync } from "node:child_process";
import { existsSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
const HERE = dirname(fileURLToPath(import.meta.url));

let pass = 0, fail = 0;
function check(label, cond, got) {
  if (cond) { pass++; console.log(`  ok   ${label}`); }
  else { fail++; console.log(`  FAIL ${label}` + (got !== undefined ? `  (got: ${got})` : "")); }
}

// ── Independent number-theory primitives (BigInt, trial division) ──────────────
function factBig(n) { let f = 1n; for (let i = 2n; i <= BigInt(n); i++) f *= i; return f; }
function gcdBig(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function isPrimeSmall(m) { // m: Number, trial division
  if (m < 2) return false;
  for (let d = 2; d * d <= m; d++) if (m % d === 0) return false;
  return true;
}
function isPrimeBig(m) { // m: BigInt, trial division (only used on modest N)
  if (m < 2n) return false;
  for (let d = 2n; d * d <= m; d++) if (m % d === 0n) return false;
  return true;
}
function smallestPrimeFactorBig(m) { // BigInt → BigInt, trial division (modest m only)
  if (m < 2n) return 0n;
  for (let d = 2n; d * d <= m; d++) if (m % d === 0n) return d;
  return m; // m is prime
}

console.log("\nI · The construction is coprime to everything it must miss (Euclid's step)");
// The heart of the proof: N = n!+1 shares no factor with any of 2..n, because each of
// those divides n!, and N ≡ 1 (mod anything dividing n!). We check N mod d === 1 for
// every d in 2..n, for a spread of n — this is exactly what forces the prime factor > n.
for (const n of [1, 2, 3, 5, 8, 13, 20, 30, 50]) {
  const N = factBig(n) + 1n;
  let allOne = true, bad = null;
  for (let d = 2n; d <= BigInt(n); d++) {
    if (N % d !== 1n) { allOne = false; bad = d.toString(); break; }
  }
  check(`n=${n}: (n!+1) mod d = 1 for every d in 2..n (⇒ no factor ≤ n)`, allOne, bad);
  check(`n=${n}: gcd(n!, n!+1) = 1`, gcdBig(factBig(n), N) === 1n);
}

console.log("\nII · An explicit larger prime, for many n (factor N, take its least prime factor)");
// For modest n, fully factor N = n!+1 and show its smallest prime factor is a prime > n.
for (const n of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) {
  const N = factBig(n) + 1n;
  const p = smallestPrimeFactorBig(N);
  check(`n=${n}: least prime factor of ${n}!+1 = ${N} is ${p}, and ${p} > ${n}`,
    p > BigInt(n) && isPrimeBig(p), p.toString());
}

console.log("\nIII · N = n!+1 need NOT be prime — Euclid gives a larger prime, not a prime N");
// The common misreading is that Euclid's number is itself prime. It often is not; the
// proof only needs one of its prime factors to be new. Classic primorial example:
{
  const primorial = 2n * 3n * 5n * 7n * 11n * 13n; // 30030
  const E = primorial + 1n; // 30031
  check("2·3·5·7·11·13 + 1 = 30031", E === 30031n, E.toString());
  check("30031 is composite = 59 × 509 (Euclid's N is not always prime)",
    E === 59n * 509n && !isPrimeBig(E));
  check("yet both factors 59, 509 exceed 13 (the largest prime used)",
    59 > 13 && 509 > 13 && isPrimeSmall(59) && isPrimeSmall(509));
}
// And a factorial witness where n!+1 is composite but its factor still exceeds n:
{
  // 4! + 1 = 25 = 5², composite, factor 5 > 4.
  const N = factBig(4) + 1n;
  check("4!+1 = 25 = 5² is composite, and its factor 5 exceeds 4",
    N === 25n && smallestPrimeFactorBig(N) === 5n && 5 > 4);
}

console.log("\nIV · The primes do not stop (finite corroboration; the ceiling is the point)");
// Sieve primes up to a ceiling: for every n below the ceiling we can point to a larger
// prime here — but only because we chose a ceiling. Removing the ceiling is the theorem.
const CEIL = 200000;
const sieve = new Uint8Array(CEIL + 1).fill(1); sieve[0] = sieve[1] = 0;
for (let i = 2; i * i <= CEIL; i++) if (sieve[i]) for (let j = i * i; j <= CEIL; j += i) sieve[j] = 0;
const primes = []; for (let i = 2; i <= CEIL; i++) if (sieve[i]) primes.push(i);
check("π(200000) = 17984 primes below the ceiling (finite: this is corroboration, not proof)",
  primes.length === 17984, primes.length);
{
  // for every n < CEIL-something, a strictly larger prime exists in the list
  let ok = true, badN = null;
  for (let n = 0; n <= 199000; n += 997) {
    if (!primes.some(p => p > n)) { ok = false; badN = n; break; }
    // sanity: the *next* prime after n is genuinely prime
  }
  check("for every sampled n < ceiling there is a larger prime (bounded by the ceiling)", ok, badN);
}
check(`beyond the largest prime we found (${primes[primes.length - 1]}) this scan is silent — only the kernel proof covers every n`,
  primes[primes.length - 1] <= CEIL && primes[primes.length - 1] > CEIL - 100);

console.log("\nV · The Lean kernel — the eighth mode itself (if `lean` is on PATH)");
{
  const leanFile = join(HERE, "lean", "Euclid.lean");
  let leanBin = null;
  for (const cand of ["lean",
    join(process.env.HOME || "", ".elan/bin/lean"),
    join(process.env.HOME || "", ".nix-profile/bin/lean")]) {
    try { execSync(`${cand} --version`, { stdio: "ignore" }); leanBin = cand; break; } catch { }
  }
  if (!leanBin) {
    console.log("  skip  lean not found — install Lean 4 (https://lean-lang.org/install/), or from the repository: bash research/mcnugget/lean/install-lean-nix.sh");
    console.log("        (the finite checks above stand on their own; Lean removes the ceiling.)");
  } else if (!existsSync(leanFile)) {
    // A reader who downloaded only this file (2026-09-28 claims pass: they got 37/1 and a red
    // exit). The proof is served beside it; without it there is nothing to hand the kernel.
    console.log("  skip  lean found but lean/Euclid.lean is not beside this script — fetch it:");
    console.log("        mkdir -p lean && curl -o lean/Euclid.lean https://artwaste.land/checks/research/proof-poem-seven-modes/lean/Euclid.lean");
  } else {
    let out = "";
    try { out = execSync(`${leanBin} "${leanFile}"`, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); }
    catch (e) { out = (e.stdout || "") + (e.stderr || ""); }
    check("Euclid.lean typechecks with no errors", !/error:/i.test(out), out.split("\n").find(l => /error/i.test(l)));
    const axiomLines = out.split("\n").filter(l => /depends on axioms|does not depend on any axioms/.test(l));
    check("kernel reports ≥ 5 theorems' axiom footprints", axiomLines.length >= 5, axiomLines.length);
    const clean = axiomLines.every(l => /\[propext, Quot\.sound\]/.test(l) || /does not depend on any axioms/.test(l));
    check("every footprint is within [propext, Quot.sound] (no sorry/Classical.choice/native_decide)",
      clean, axiomLines.join(" | "));
    check("no sorryAx / Classical.choice / native_decide anywhere in the report",
      !/sorryAx|Classical\.choice|native_decide/.test(out));
    check("the headline theorem `infinitude` is among the checked results",
      /Euclid\.infinitude/.test(out));
  }
}

console.log(`\n${fail === 0 ? "✓" : "✗"} ${pass} passed, ${fail} failed\n`);
process.exit(fail === 0 ? 0 : 1);
