#!/usr/bin/env node
// Verifier for the stratum "The McNugget Number"
//   page: public/strata/the-mcnugget-number/index.html
//   live: https://artwaste.land/strata/the-mcnugget-number/
//
// The claim: with packs of 6, 9, and 20, the totals you CANNOT buy exactly are
// {1,2,3,4,5,7,8,10,11,13,14,16,17,19,22,23,25,28,31,34,37,43} — twenty-two of
// them — and 43 is the largest (the "McNugget number", i.e. the Frobenius number
// of the set {6,9,20}). Every total from 44 up is buyable.
//
// This verifier recomputes all of that from scratch by exhaustive search, and
// cross-checks the gap set against the value catalogued in OEIS A065003. The search
// is only ever finite (it stops after seeing 6 consecutive buyable totals, which is
// a valid stopping rule — once six in a row are buyable, adding 6-packs covers
// everything above). The UNBOUNDED statement ("every total >= 44 is buyable, with
// no ceiling") is what the companion Lean proof settles; when `lean` is on PATH this
// script also runs the kernel and asserts the proof's axiom footprint.
//
// Run:  node research/mcnugget/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})` : "")); }
}

const PACKS = [6, 9, 20];

// buyable(n): is n an exact nonnegative combination of the packs? (exhaustive)
function buyable(n) {
  for (let c = 0; c * 20 <= n; c++) {
    const r2 = n - 20 * c;
    for (let b = 0; b * 9 <= r2; b++) {
      if ((r2 - 9 * b) % 6 === 0) return true;
    }
  }
  return false;
}

console.log("\nI · The pack set and the predicate");
check("packs are 6, 9, 20", PACKS.join(",") === "6,9,20");
check("gcd(6,9,20) = 1 (setwise coprime ⇒ a largest gap exists)",
  (function g(a, b) { while (b) { [a, b] = [b, a % b]; } return a; })(
    (function g2(a, b) { while (b) { [a, b] = [b, a % b]; } return a; })(6, 9), 20) === 1);
check("6 and 9 are NOT coprime (can't shortcut via a sub-pair)",
  (function g(a, b) { while (b) { [a, b] = [b, a % b]; } return a; })(6, 9) === 3);

console.log("\nII · Enumerate the impossible totals (finite scan, valid stopping rule)");
// scan until 6 consecutive buyable totals seen
const gaps = [];
{
  let n = 1, run = 0;
  while (run < 6 && n < 100000) {
    if (buyable(n)) run++; else { gaps.push(n); run = 0; }
    n++;
  }
}
const EXPECTED = [1, 2, 3, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 22, 23, 25, 28, 31, 34, 37, 43];
check("exactly 22 impossible totals (the genus)", gaps.length === 22, gaps.length);
check("gap set matches OEIS A065003 exactly", JSON.stringify(gaps) === JSON.stringify(EXPECTED),
  gaps.join(","));
check("largest impossible total is 43 (the McNugget number / Frobenius number)",
  gaps[gaps.length - 1] === 43, gaps[gaps.length - 1]);
check("43 itself is not buyable", !buyable(43));

console.log("\nIII · Every total from 44 to 10000 is buyable (finite corroboration)");
{
  let allBuyable = true, firstBad = null;
  for (let n = 44; n <= 10000; n++) {
    if (!buyable(n)) { allBuyable = false; firstBad = n; break; }
  }
  check("no impossible total in 44..10000", allBuyable, firstBad);
}

console.log("\nIV · The mod-6 construction the proof uses (the six column-bases)");
// smallest buyable total in each residue class mod 6
const bases = { 0: 0, 1: 49, 2: 20, 3: 9, 4: 40, 5: 29 };
for (const r of [0, 1, 2, 3, 4, 5]) {
  const base = bases[r];
  const smallest = (function () { let n = r === 0 ? 0 : r; while (!buyable(n)) n += 6; return n; })();
  check(`residue ${r}: smallest buyable ≡ ${r} (mod 6) is ${base}`, smallest === base, smallest);
}
check("the stubborn class is residue 1 (base 49) ⇒ last gap 43 = 49-6",
  bases[1] === 49 && 49 - 6 === 43);

console.log("\nV · The receipts the page shows for the buyable totals 1..43");
// each representable value ≤ 43 has an explicit small witness
const witnesses = {
  6: [1, 0, 0], 9: [0, 1, 0], 12: [2, 0, 0], 15: [1, 1, 0], 18: [3, 0, 0], 20: [0, 0, 1],
  21: [2, 1, 0], 24: [4, 0, 0], 26: [1, 0, 1], 27: [0, 3, 0], 29: [0, 1, 1], 30: [5, 0, 0],
  32: [2, 0, 1], 33: [4, 1, 0], 35: [1, 1, 1], 36: [6, 0, 0], 38: [3, 0, 1], 39: [5, 1, 0],
  40: [0, 0, 2], 41: [2, 1, 1], 42: [7, 0, 0],
};
let witnessOk = true, witnessBad = null;
for (const [n, [x, y, z]] of Object.entries(witnesses)) {
  if (6 * x + 9 * y + 20 * z !== Number(n)) { witnessOk = false; witnessBad = n; break; }
}
check("all 21 receipts for buyable totals ≤ 43 are correct", witnessOk, witnessBad);
check("witnesses cover exactly the buyable totals in 1..43",
  Object.keys(witnesses).map(Number).sort((a, b) => a - b).join(",") ===
  Array.from({ length: 43 }, (_, i) => i + 1).filter(buyable).join(","));

console.log("\nVI · Menu-change sanity (the honesty caveats on the page)");
// with a 4-pack added, the largest gap drops to 11
function buyableSet(packs, n) {
  // generic DP reachability up to n
  const reach = new Array(n + 1).fill(false); reach[0] = true;
  for (let i = 1; i <= n; i++) for (const p of packs) if (i - p >= 0 && reach[i - p]) { reach[i] = true; break; }
  return reach;
}
{
  const reach = buyableSet([4, 6, 9, 20], 200);
  let last = 0; for (let i = 1; i <= 200; i++) if (!reach[i]) last = i;
  check("adding a 4-pack drops the largest gap to 11", last === 11, last);
}
{
  // with 10 replacing 9, all packs even ⇒ every odd total impossible ⇒ no largest gap
  const reach = buyableSet([4, 6, 10, 20], 999);
  check("with 4,6,10,20 (all even) 999 is unbuyable ⇒ no largest gap", reach[999] === false);
}

console.log("\nVII · The Lean kernel (the unbounded proof) — if `lean` is on PATH");
{
  const leanFile = join(HERE, "lean", "McNugget.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), or in 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 has no proof to check: skip, as when
    // Lean is absent (claims pass 2026-10-13: this used to count as a FAIL).
    console.log(`  skip  ${leanFile} not found — download lean/McNugget.lean beside this file to run the kernel check`);
  } else {
    let out = "";
    try { out = execSync(`${leanBin} "${leanFile}"`, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); }
    catch (e) { out = (e.stdout || "") + (e.stderr || ""); }
    check("McNugget.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/.test(l));
    check("kernel reports ≥ 5 theorems' axiom footprints", axiomLines.length >= 5, axiomLines.length);
    const clean = axiomLines.every(l => /\[propext, Quot\.sound\]/.test(l));
    check("every footprint is exactly [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));
  }
}

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