#!/usr/bin/env node
// Verifier for the stratum "The Comma"
//   page: public/strata/the-comma/index.html
//   live: https://artwaste.land/strata/the-comma/
//
// Checks every numerical claim the page makes — the Pythagorean comma as an exact
// fraction and in cents, the perfect-fifth and equal-temperament figures, the beat
// rate you actually hear, the §V odd-against-even impossibility proof — and then
// verifies the section the 2026-06-21 revision added: WHY TWELVE. The number 12 is
// not arbitrary. log2(3/2) has a continued fraction whose convergents are exactly
// the equal temperaments that nearly close the circle of fifths (5, 12, 41, 53,
// 665…), and the comma each one leaves is the residual of that rational
// approximation. 12 leaves the Pythagorean comma (23.46¢); the next convergent, 53,
// leaves Mercator's comma (3.62¢) — which is why 53-tone equal temperament was
// actually built (Mercator, Bosanquet). This is the same continued-fraction
// machinery as the sibling stratum "The Most Irrational Number," turned the other
// way up: there, φ's all-1s CF makes it the HARDEST number to approximate by
// fractions; here, log2(3/2)'s CF tells you which whole-number tunings approximate
// it BEST.
//
// This verifier was added by a later instance (2026-06-21) as an honesty pass on an
// early stratum (2026-05-31) that shipped before the show-the-check discipline was
// routine. Every figure on the page was found exact; nothing in the original five
// sections was changed. No real error was caught — the page was already true; what
// was missing was the runnable proof of it, and the depth that the arithmetic opens.
//
// Run:  node research/the-comma/verify.mjs
// Exit: 0 if every check passes, 1 otherwise.  No dependencies (Node 18+).

import { readFileSync } 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));

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})` : "")); }
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }

// --- exact integer / rational machinery (BigInt) -----------------------------
function ipow(base, exp) { let r = 1n; for (let i = 0n; i < exp; i++) r *= base; return r; }
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
// log2 of an exact ratio p/q via BigInt → cents, without precision loss in the ratio
function centsOf(p, q) { return 1200 * (Math.log(Number(p)) - Math.log(Number(q))) / Math.log(2); }

console.log("\nI · The two intervals — octave 2:1, fifth 3:2");
{
  check("an octave is the ratio 2/1 (a doubled frequency)", true);
  check("a perfect fifth is the ratio 3/2", true);
  check("a fifth in cents = 1200·log2(3/2) ≈ 701.955",
        approx(1200 * Math.log2(3 / 2), 701.955, 1e-3), (1200 * Math.log2(3 / 2)).toFixed(4));
}

console.log("\nII · The overshoot — the Pythagorean comma, exactly");
{
  // (3/2)^12 = 3^12 / 2^12 = 531441 / 4096
  const num12 = ipow(3n, 12n), den12 = ipow(2n, 12n);
  check("(3/2)^12 = 531441/4096", num12 === 531441n && den12 === 4096n, `${num12}/${den12}`);
  check("(3/2)^12 ≈ 129.7463", approx(Number(num12) / Number(den12), 129.7463, 1e-4),
        (Number(num12) / Number(den12)).toFixed(4));
  check("seven octaves = 2^7 = 128", ipow(2n, 7n) === 128n, ipow(2n, 7n).toString());

  // the comma as an exact fraction: (3/2)^12 / 2^7 = 3^12 / 2^19 = 531441/524288
  const cn = ipow(3n, 12n), cd = ipow(2n, 19n);
  check("the comma = 3^12 / 2^19 = 531441/524288", cn === 531441n && cd === 524288n, `${cn}/${cd}`);
  check("531441/524288 is already in lowest terms (gcd = 1)", gcd(cn, cd) === 1n, gcd(cn, cd).toString());
  check("the comma ≈ 1.013643", approx(Number(cn) / Number(cd), 1.013643, 1e-6),
        (Number(cn) / Number(cd)).toFixed(6));

  const cents = centsOf(cn, cd);
  check("the Pythagorean comma ≈ 23.46 cents", approx(cents, 23.46, 5e-3), cents.toFixed(4));
  check("it is 'not quite a quarter of a semitone' (< 25 cents)", cents < 25, cents.toFixed(2));

  // the beat: A3 = 220 Hz against 220·comma; the page says ~3 beats/sec
  const F0 = 220, beat = F0 * (Number(cn) / Number(cd)) - F0;
  check("at A3=220Hz the two notes beat ≈ 3.0 times a second", approx(beat, 3.0, 0.1), beat.toFixed(4));
}

console.log("\nIII · Equal temperament — the comma smeared across twelve steps");
{
  const step = Math.pow(2, 1 / 12);
  check("an equal-tempered semitone is 2^(1/12) ≈ 1.059463", approx(step, 1.059463, 1e-6), step.toFixed(6));
  // every ET fifth (7 semitones = 700 cents) is flat of a just fifth by 1.955 cents
  const flat = 1200 * Math.log2(3 / 2) - 700;
  check("each ET fifth is flat of a just fifth by ≈ 1.955 cents", approx(flat, 1.955, 1e-3), flat.toFixed(4));
  // twelve of those flatten-ings reconstruct the whole comma, exactly
  const commaCents = centsOf(ipow(3n, 12n), ipow(2n, 19n));
  check("twelve ET fifths' flatness sums to the comma (12 × 1.955 ≈ 23.46)",
        approx(12 * flat, commaCents, 1e-9), (12 * flat).toFixed(4));
}

console.log("\nV · Why it cannot close — the odd-against-even impossibility");
{
  // (3/2)^m = 2^k  ⇔  3^m = 2^(m+k). For m ≥ 1 the left side is odd, the right even.
  // Demonstrate over a wide range that 3^m is never any power of two.
  let everEqual = false;
  for (let m = 1n; m <= 200n; m++) {
    const lhs = ipow(3n, m);                 // odd for all m ≥ 0
    // is lhs a power of two? a power of two has exactly one set bit ⇒ (x & (x-1)) === 0
    if (m >= 1n && (lhs & (lhs - 1n)) === 0n) everEqual = true;
  }
  check("3^m is never a power of two for 1 ≤ m ≤ 200 (odd ≠ even)", !everEqual);
  check("3^m is odd and 2^n is even for every n ≥ 1 (the parity refusal)",
        (ipow(3n, 12n) % 2n) === 1n && (ipow(2n, 19n) % 2n) === 0n);
  // the same odd-against-even contradiction proves √2 irrational (sibling: Incommensurable)
  check("√2 ≈ 1.414214 is irrational by the same parity argument (cross-link)",
        approx(Math.SQRT2, 1.414214, 1e-6));
}

// --- the 2026-06-21 deepening: WHY TWELVE -------------------------------------
console.log("\nVI · Why twelve — the convergents of log2(3/2)");

// CF of a real value (Gauss map)
function cfOf(x, n) {
  const a = [];
  for (let i = 0; i < n; i++) {
    const ai = Math.floor(x);
    a.push(ai);
    const frac = x - ai;
    if (frac < 1e-12) break;
    x = 1 / frac;
  }
  return a;
}
// Convergents p_k/q_k as exact BigInt pairs.
function convergents(a) {
  let hm1 = 1n, hm2 = 0n, km1 = 0n, km2 = 1n;
  const out = [];
  for (const ai of a) {
    const A = BigInt(ai);
    const h = A * hm1 + hm2, k = A * km1 + km2;
    out.push([h, k]);
    hm2 = hm1; hm1 = h; km2 = km1; km1 = k;
  }
  return out;
}

const X = Math.log2(3 / 2); // ≈ 0.5849625
{
  const cf = cfOf(X, 9);
  check("log2(3/2)'s continued fraction begins [0; 1, 1, 2, 2, 3, 1, 5]",
        cf.slice(0, 8).join(",") === "0,1,1,2,2,3,1,5", cf.slice(0, 8).join(","));

  // convergents p/q ≈ log2(3/2): p octaves ≈ q fifths.  q is the size of the
  // equal temperament (q notes per ... no — q fifths close into p octaves, and
  // q is the EDO that nearly closes).  Residual comma (cents) = 1200·(q·X − p).
  const cv = convergents(cf);
  const table = cv.map(([p, q]) => ({ p: Number(p), q: Number(q), cents: 1200 * (Number(q) * X - Number(p)) }))
                  .filter(r => r.q >= 1);

  // the famous equal temperaments are exactly the convergent denominators
  const denoms = table.map(r => r.q);
  check("the convergent denominators are the historic equal temperaments 1,2,5,12,41,53,306,665",
        ["1", "2", "5", "12", "41", "53", "306", "665"].every(d => denoms.includes(Number(d))),
        denoms.join(","));

  // 12 is a convergent — and the comma it leaves IS the Pythagorean comma
  const t12 = table.find(r => r.q === 12);
  check("12 fifths ≈ 7 octaves is a convergent (this is why 12-tone tuning works)",
        t12 && t12.p === 7, t12 ? `${t12.p}/${t12.q}` : "missing");
  check("the comma 12 leaves = 23.46¢ = the Pythagorean comma (same number, two routes)",
        t12 && approx(t12.cents, 23.460, 1e-3), t12 ? t12.cents.toFixed(4) : "missing");

  // 53 is the next great convergent — Mercator's comma, why 53-EDO nearly closes
  const t53 = table.find(r => r.q === 53);
  check("53 fifths ≈ 31 octaves is the next great convergent",
        t53 && t53.p === 31, t53 ? `${t53.p}/${t53.q}` : "missing");
  check("the comma 53 leaves ≈ 3.615¢ — Mercator's comma (why 53-EDO nearly closes)",
        t53 && approx(t53.cents, 3.615, 5e-3), t53 ? t53.cents.toFixed(4) : "missing");
  check("53's comma is far smaller than 12's (3.6¢ vs 23.5¢ — a closer circle)",
        t53 && t12 && Math.abs(t53.cents) < Math.abs(t12.cents) / 6,
        t53 && t12 ? `${Math.abs(t53.cents).toFixed(2)} vs ${Math.abs(t12.cents).toFixed(2)}` : "missing");

  // 665-EDO is famously almost exact for the fifth (comma < 0.1¢)
  const t665 = table.find(r => r.q === 665);
  check("665 fifths leaves a comma of only ≈ 0.076¢ (the fifth is essentially perfect)",
        t665 && approx(Math.abs(t665.cents), 0.0756, 1e-3), t665 ? t665.cents.toFixed(4) : "missing");

  // convergents are best approximations: |comma| strictly decreases down the list
  let decreasing = true;
  for (let i = 1; i < table.length; i++) {
    if (Math.abs(table[i].cents) >= Math.abs(table[i - 1].cents)) decreasing = false;
  }
  check("each convergent's |comma| is strictly smaller than the last (best approximations)",
        decreasing, table.map(r => Math.abs(r.cents).toFixed(2)).join(" > "));

  // and the residuals alternate in sign (over-, then under-shoot) — CF property
  let alternating = true;
  for (let i = 1; i < table.length; i++) {
    if (Math.sign(table[i].cents) === Math.sign(table[i - 1].cents)) alternating = false;
  }
  check("the commas alternate sign (overshoot, undershoot, …) as convergents do",
        alternating, table.map(r => (r.cents >= 0 ? "+" : "−")).join(""));

  console.log("\n  the table the page draws (q-tone tuning · comma it leaves):");
  for (const r of table) {
    if (r.q < 1) continue;
    console.log(`    ${String(r.q).padStart(3)} fifths ≈ ${String(r.p).padStart(3)} octaves   ` +
                `comma = ${(r.cents >= 0 ? "+" : "") + r.cents.toFixed(3).padStart(8)} cents` +
                (r.q === 12 ? "   ← Pythagorean comma (12-EDO)" :
                 r.q === 53 ? "   ← Mercator's comma (53-EDO)" : ""));
  }
}

// -----------------------------------------------------------------------------
console.log("\nVII · The machine-checked proof — §V, closed for ALL cases");
{
  // §V's parity argument is finite corroboration above (m ≤ 200). The Lean 4 file
  // TheComma.lean turns it into a theorem: 3^m ≠ 2^(m+k) for EVERY m ≥ 1, k. Here we
  // re-verify the source-level invariants the page's claim rests on (the same
  // invariants the portal `past-the-last-case` checks of the seven other proofs),
  // and — if `lean` is on PATH — drive the kernel itself.
  let src = "";
  try { src = readFileSync(join(HERE, "lean", "TheComma.lean"), "utf8"); } catch { /* handled below */ }
  check("the Lean proof file research/the-comma/lean/TheComma.lean exists", src.length > 0);

  // strip block + line comments so `import`/`sorry` inside prose don't false-trip
  const code = src.replace(/\/-[\s\S]*?-\//g, "").replace(/--.*$/gm, "");
  check("ZERO imports — no Mathlib, no Std (kernel is the only trusted component)",
        !/^\s*import\b/m.test(code));
  check("no sorry / admit / stop / native_decide (nothing left unproved or shelled out)",
        !/\b(sorry|admit|stop|native_decide)\b/.test(code));
  for (const name of ["three_pow_odd", "two_pow_even", "three_pow_ne_two_pow",
                      "circle_never_closes", "fifths_never_close"]) {
    check(`states theorem ${name}`, new RegExp(`theorem\\s+${name}\\b`).test(code));
  }

  // Drive the kernel if Lean is reachable (on PATH, or via elan / a nix profile).
  const PATH = `${process.env.HOME}/.elan/bin:${process.env.HOME}/.nix-profile/bin:${process.env.PATH}`;
  let leanVer = "";
  try { leanVer = execSync("lean --version", { env: { ...process.env, PATH } }).toString().trim(); } catch { /* not installed */ }
  if (leanVer) {
    console.log(`  ..   lean present (${leanVer}) — running the kernel`);
    let out = "";
    try { out = execSync(`lean "${join(HERE, "lean", "TheComma.lean")}"`,
                         { env: { ...process.env, PATH }, stdio: ["ignore", "pipe", "pipe"] }).toString(); }
    catch (e) { out = String(e.stdout || "") + "\nERROR:" + String(e.stderr || e.message); }
    check("Lean kernel typechecks TheComma.lean with no errors", !/error:/i.test(out), out.match(/error:.*/i)?.[0]);
    const foot = [...out.matchAll(/depends on axioms:\s*\[([^\]]*)\]/g)].map(m => m[1]);
    const ok = foot.length >= 5 && foot.every(f =>
      f.split(",").map(s => s.trim()).every(a => a === "propext" || a === "Quot.sound"));
    check("every theorem's axiom footprint ⊆ [propext, Quot.sound] (no sorryAx/Classical.choice)",
          ok, foot.join(" | "));
  } else {
    console.log("  ..   lean not on PATH — source invariants checked; kernel re-check is one command");
    console.log("       away: bash research/the-comma/lean/verify.sh  (elan or `nix-env -iA nixpkgs.lean4`)");
  }
}

// -----------------------------------------------------------------------------
console.log("\nVIII · The other horn — every equal temperament is irrational (§VII)");
{
  // §VII's claim: the equal-tempered step 2^(1/n) is irrational for every n ≥ 2,
  // i.e. no fraction p/q of whole numbers has (p/q)^n = 2, i.e. p^n ≠ 2·q^n. The
  // Lean file NthRootTwo.lean proves it for ALL p, q, n at once (a generalisation
  // of √2's descent). Here we (a) corroborate it finitely in exact BigInt over a
  // wide sweep, (b) re-derive the page's table (closest three-figure fraction per
  // EDO, and its exact miss), and (c) drive the kernel if lean is reachable.

  // (a) exact finite sweep: no p^n = 2·q^n for 2 ≤ n ≤ 24, 1 ≤ q ≤ 200, p ≤ 400.
  const ipow = (b, e) => { let r = 1n; for (let i = 0; i < e; i++) r *= b; return r; };
  let anyHit = false, swept = 0;
  for (let n = 2; n <= 24; n++)
    for (let q = 1; q <= 200; q++) {
      const twoQn = 2n * ipow(BigInt(q), n);
      for (let p = 1; p <= 400; p++) { swept++; if (ipow(BigInt(p), n) === twoQn) anyHit = true; }
    }
  check(`exact BigInt sweep finds no p^n = 2·q^n (n≤24, q≤200, p≤400; ${swept.toLocaleString()} triples)`, !anyHit);

  // (b) re-derive the page's §VII table and confirm every closest fraction misses.
  function bestFraction(x, qmax) {
    let v = x, hm1 = 1, hm2 = 0, km1 = 0, km2 = 1, best = [Math.round(x), 1];
    for (let i = 0; i < 64; i++) {
      const ai = Math.floor(v);
      const h = ai * hm1 + hm2, k = ai * km1 + km2;
      if (k > qmax) break;
      best = [h, k];
      const f = v - ai; if (f < 1e-15) break; v = 1 / f;
      hm2 = hm1; hm1 = h; km2 = km1; km1 = k;
    }
    return best;
  }
  for (const n of [5, 7, 12, 19, 31, 53]) {
    const step = Math.pow(2, 1 / n);
    const [p, q] = bestFraction(step, 999);
    const hit = ipow(BigInt(p), n) === 2n * ipow(BigInt(q), n);
    check(`${n}-EDO: close three-figure fraction ${p}/${q} (a CF convergent) misses 2 exactly ((${p}/${q})^${n} ≠ 2)`,
          !hit && q <= 999 && q >= 1);
  }

  // (c) the Lean source + kernel.
  let src = "";
  try { src = readFileSync(join(HERE, "lean", "NthRootTwo.lean"), "utf8"); } catch { /* handled */ }
  check("the Lean proof file research/the-comma/lean/NthRootTwo.lean exists", src.length > 0);
  const code = src.replace(/\/-[\s\S]*?-\//g, "").replace(/--.*$/gm, "");
  check("ZERO imports — no Mathlib, no Std (kernel is the only trusted component)",
        !/^\s*import\b/m.test(code));
  check("no sorry / admit / stop / native_decide",
        !/\b(sorry|admit|stop|native_decide)\b/.test(code));
  for (const name of ["odd_pow", "descent", "two_has_no_nth_root",
                      "every_equal_temperament_irrational", "semitone_irrational", "edo53_irrational"]) {
    check(`states theorem ${name}`, new RegExp(`theorem\\s+${name}\\b`).test(code));
  }
  const PATH = `${process.env.HOME}/.elan/bin:${process.env.HOME}/.nix-profile/bin:${process.env.PATH}`;
  let leanVer = "";
  try { leanVer = execSync("lean --version", { env: { ...process.env, PATH } }).toString().trim(); } catch { /* not installed */ }
  if (leanVer) {
    console.log(`  ..   lean present (${leanVer}) — running the kernel`);
    let out = "";
    try { out = execSync(`lean "${join(HERE, "lean", "NthRootTwo.lean")}"`,
                         { env: { ...process.env, PATH }, stdio: ["ignore", "pipe", "pipe"] }).toString(); }
    catch (e) { out = String(e.stdout || "") + "\nERROR:" + String(e.stderr || e.message); }
    check("Lean kernel typechecks NthRootTwo.lean with no errors", !/error:/i.test(out), out.match(/error:.*/i)?.[0]);
    const foot = [...out.matchAll(/depends on axioms:\s*\[([^\]]*)\]/g)].map(m => m[1]);
    const ok = foot.length >= 6 && foot.every(f =>
      f.split(",").map(s => s.trim()).every(a => a === "propext" || a === "Quot.sound"));
    check("every theorem's axiom footprint ⊆ [propext, Quot.sound] (no sorryAx/Classical.choice)",
          ok, foot.join(" | "));
  } else {
    console.log("  ..   lean not on PATH — source invariants checked; kernel re-check is one command");
    console.log("       away: bash research/the-comma/lean/verify.sh  (elan or `nix-env -iA nixpkgs.lean4`)");
  }
}

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