// verify.mjs — offline re-derivation of every geometric claim on
// /strata/the-floor-that-wont-lie-flat/ ("The Floor That Won't Lie Flat").
//
// The page is standalone static HTML and cannot import this file, so it carries a
// byte-tagged copy of the canonical geometry function (between the markers
// AW_HYP_CANONICAL_START / _END) and a MODEL constants block. This verifier:
//   (1) re-derives, from first principles, the whole regular-tiling trichotomy —
//       the spherical {p,q} ARE the Platonic solids, the three Euclidean tilings,
//       and the hyperbolic Poincaré-disk construction (radii, geodesics ⊥ the
//       boundary, reflections as isometries, flood-fill, q tiles per vertex, and
//       every tile's equal hyperbolic area by Gauss–Bonnet);
//   (2) asserts every number in constants.json matches that re-derivation;
//   (3) DRIFT-GUARD: extracts the page's tagged canonical function + MODEL block and
//       asserts they agree with this math on a (p,q) grid — so page and check can
//       never silently diverge.
//
//   run:  node research/hyperbolic-tiling/verify.mjs
//   exit: 0 = all pass, 1 = any fail.
//
// Sources for the named facts are in the page's apparatus (#history-sources):
// Coxeter, "The trigonometry of Escher's woodcuts" (1996); the Schläfli
// symbol and the three regular Euclidean tilings; the five Platonic solids as the
// spherical regular tilings; Gauss's Theorema Egregium (1827).

import { readFileSync, existsSync } from 'fs';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { execFileSync } from 'child_process';

const HERE = dirname(fileURLToPath(import.meta.url));
const TAU = Math.PI * 2;

let pass = 0, fail = 0;
const bad = [];
function check(name, ok, detail) { if (ok) pass++; else { fail++; bad.push(name + (detail ? ' — ' + detail : '')); } }
const near = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
const eqn = (a, b, name, eps = 1e-9) => check(name, near(a, b, eps), `got ${a}, want ${b}`);
const section = (t) => console.log(`\n── ${t} ${'─'.repeat(Math.max(0, 60 - t.length))}`);
const skipped = [];
const skip = (why) => { skipped.push(why); console.log(`  SKIP  ${why}`); };

// ── complex helpers (Poincaré disk) ──────────────────────────────────────────
const C = (re, im = 0) => ({ re, im });
const cadd = (a, b) => C(a.re + b.re, a.im + b.im);
const csub = (a, b) => C(a.re - b.re, a.im - b.im);
const cmul = (a, b) => C(a.re * b.re - a.im * b.im, a.re * b.im + a.im * b.re);
const cconj = (a) => C(a.re, -a.im);
const cabs2 = (a) => a.re * a.re + a.im * a.im;
const cabs = (a) => Math.hypot(a.re, a.im);
const cdiv = (a, b) => { const d = cabs2(b); return C((a.re * b.re + a.im * b.im) / d, (a.im * b.re - a.re * b.im) / d); };

// ── THE CANONICAL GEOMETRY (identical to the page's tagged block) ─────────────
const cot = (x) => Math.cos(x) / Math.sin(x);
function hypGeom(p, q) {
  const g = 1 / p + 1 / q - 0.5;
  const regime = Math.abs(g) < 1e-12 ? 'euclidean' : g > 0 ? 'spherical' : 'hyperbolic';
  const interiorAngle = ((p - 2) * 180) / p;      // degrees, regular p-gon (flat)
  const vertexSum = q * interiorAngle;             // degrees, q of them at a corner
  let R = null, eucR = null, tileAreaOverPi = null;
  if (regime === 'hyperbolic') {
    R = Math.acosh(cot(Math.PI / p) * cot(Math.PI / q));  // hyperbolic circumradius
    eucR = Math.tanh(R / 2);                              // Euclidean radius in unit disk
    tileAreaOverPi = (p - 2) - (2 * p) / q;               // hyperbolic tile area / π (= defect/π)
  }
  return { g, regime, interiorAngle, vertexSum, R, eucR, tileAreaOverPi };
}

// ── 1. THE TRICHOTOMY: two conditions agree everywhere ───────────────────────
for (let p = 3; p <= 12; p++) for (let q = 3; q <= 12; q++) {
  const g = 1 / p + 1 / q - 0.5;
  const d = 4 - (p - 2) * (q - 2);
  check(`sign agreement {${p},${q}}`, Math.sign(g) === Math.sign(d) || (near(g, 0) && d === 0), `g=${g}, d=${d}`);
}
for (const [p, q] of [[4, 4], [3, 6], [6, 3]]) check(`{${p},${q}} euclidean`, hypGeom(p, q).regime === 'euclidean');
for (const [p, q] of [[3, 3], [4, 3], [3, 4], [5, 3], [3, 5]]) check(`{${p},${q}} spherical`, hypGeom(p, q).regime === 'spherical');
for (const [p, q] of [[7, 3], [3, 7], [4, 5], [5, 4], [5, 5], [4, 6], [6, 4], [8, 3]]) check(`{${p},${q}} hyperbolic`, hypGeom(p, q).regime === 'hyperbolic');
// exactly three regular Euclidean tilings
{
  const euc = [];
  for (let p = 3; p <= 20; p++) for (let q = 3; q <= 20; q++) if (near((p - 2) * (q - 2), 4)) euc.push(`{${p},${q}}`);
  check('exactly three regular Euclidean tilings', euc.join(' ') === '{3,6} {4,4} {6,3}', euc.join(' '));
}

// ── 2. SPHERICAL {p,q} ARE THE PLATONIC SOLIDS ───────────────────────────────
function platonic(p, q) {
  const denom = 4 - (p - 2) * (q - 2);
  return { V: (4 * p) / denom, E: (4 * p * q) / (2 * denom), F: (4 * q) / denom };
}
{
  const want = { '3,3': [4, 6, 4], '4,3': [8, 12, 6], '3,4': [6, 12, 8], '5,3': [20, 30, 12], '3,5': [12, 30, 20] };
  for (const key in want) {
    const [p, q] = key.split(',').map(Number);
    const { V, E, F } = platonic(p, q);
    const [wV, wE, wF] = want[key];
    eqn(V, wV, `{${p},${q}} V`); eqn(E, wE, `{${p},${q}} E`); eqn(F, wF, `{${p},${q}} F`);
    eqn(V - E + F, 2, `{${p},${q}} Euler V−E+F=2`);
    const faceArea = p * (TAU / q) - (p - 2) * Math.PI;   // unit-sphere excess
    check(`{${p},${q}} spherical face area > 0`, faceArea > 0);
    eqn(F * faceArea, 4 * Math.PI, `{${p},${q}} F faces cover the sphere (4π)`);
  }
}

// ── 3. HYPERBOLIC right triangle (π/p, π/q, π/2): the radii close ─────────────
function hypRadii(p, q) {
  const a = Math.PI / p, b = Math.PI / q;
  return { R: Math.acosh(cot(a) * cot(b)), rin: Math.acosh(Math.cos(b) / Math.sin(a)) };
}
for (const [p, q] of [[7, 3], [4, 5], [5, 4], [8, 3], [5, 5], [4, 6]]) {
  const a = Math.PI / p;
  check(`{${p},${q}} cosh(R)=cot·cot > 1`, cot(a) * cot(Math.PI / q) > 1);
  const { R, rin } = hypRadii(p, q);
  check(`{${p},${q}} R > r_in > 0`, R > rin && rin > 0);
  const s = Math.acosh(Math.cosh(R) / Math.cosh(rin));           // half-edge, hyp-Pythagoras
  check(`{${p},${q}} half-edge s>0`, s > 0);
  eqn(Math.atan(Math.tanh(s) / Math.sinh(rin)), a, `{${p},${q}} center angle = π/p`);
}

// ── 4. POINCARÉ DISK placement + geodesics ⊥ boundary ────────────────────────
const toEuc = (d) => Math.tanh(d / 2);
const hypDist = (z, w) => Math.acosh(1 + (2 * cabs2(csub(z, w))) / ((1 - cabs2(z)) * (1 - cabs2(w))));
function centralPolygon(p, q, theta0 = 0) {
  const rv = toEuc(hypRadii(p, q).R), out = [];
  for (let k = 0; k < p; k++) { const th = theta0 + (TAU * k) / p; out.push(C(rv * Math.cos(th), rv * Math.sin(th))); }
  return out;
}
function circleThrough3(a, b, c) {
  const d = 2 * (a.re * (b.im - c.im) + b.re * (c.im - a.im) + c.re * (a.im - b.im));
  if (near(d, 0)) return { line: true };
  const ua = cabs2(a), ub = cabs2(b), uc = cabs2(c);
  const ox = (ua * (b.im - c.im) + ub * (c.im - a.im) + uc * (a.im - b.im)) / d;
  const oy = (ua * (c.re - b.re) + ub * (a.re - c.re) + uc * (b.re - a.re)) / d;
  const O = C(ox, oy);
  return { O, s: cabs(csub(a, O)), line: false };
}
const geodesicThrough = (z1, z2) => circleThrough3(z1, z2, cdiv(C(1, 0), cconj(z1)));  // via inverse point
for (const [p, q] of [[7, 3], [4, 5], [5, 5], [8, 3]]) {
  const V = centralPolygon(p, q), { R } = hypRadii(p, q);
  for (const v of V) { check(`{${p},${q}} vertex in disk`, cabs(v) < 1); eqn(hypDist(C(0, 0), v), R, `{${p},${q}} vertex at hyp-dist R`); }
  for (let k = 0; k < p; k++) {
    const g = geodesicThrough(V[k], V[(k + 1) % p]);
    check(`{${p},${q}} edge ${k} is a proper arc`, !g.line);
    eqn(cabs2(g.O), 1 + g.s * g.s, `{${p},${q}} edge ${k} ⊥ boundary`, 1e-7);
  }
}

// ── 5. REFLECTIONS ARE ISOMETRIES; flood-fill; q tiles per vertex ────────────
function reflect(z, g) { const d = csub(z, g.O), f = (g.s * g.s) / cabs2(d); return cadd(g.O, C(d.re * f, d.im * f)); }
for (const [p, q] of [[7, 3], [4, 5]]) {
  const V = centralPolygon(p, q), g = geodesicThrough(V[0], V[1]);
  const S = [C(0, 0), C(0.3, 0.1), C(-0.2, 0.4), V[2], V[3]];
  for (const z of S) check(`{${p},${q}} reflect stays in disk`, cabs(reflect(z, g)) < 1 + 1e-9);
  for (let i = 0; i < S.length; i++) for (let j = i + 1; j < S.length; j++)
    eqn(hypDist(reflect(S[i], g), reflect(S[j], g)), hypDist(S[i], S[j]), `{${p},${q}} reflection preserves hyp-dist`, 1e-7);
  eqn(hypDist(reflect(V[0], g), V[0]), 0, `{${p},${q}} shared vertex 0 fixed`, 1e-7);
}
const centroidEuc = (v) => { let x = 0, y = 0; for (const z of v) { x += z.re; y += z.im; } return C(x / v.length, y / v.length); };
// Dedup in the HYPERBOLIC metric, not the Euclidean one: reflect-flood accumulates
// path-dependent float error, so a tile reached two ways has centroids that differ
// by ~1e-6 Euclidean (escaping a rounded key) yet ~0 in hyp-distance. Distinct tile
// centres are ≥ 2·inradius apart, so a threshold of one inradius merges the
// near-duplicates without ever merging genuine neighbours — and near the boundary,
// where Euclidean spacing collapses, the hyperbolic metric stays uniform.
function floodTiling(p, q, depth) {
  const epsC = hypRadii(p, q).rin;                 // < 2·inradius (min centre separation)
  const V0 = centralPolygon(p, q), tiles = [V0], centres = [centroidEuc(V0)];
  const isNew = (c) => { for (const k of centres) if (hypDist(c, k) < epsC) return false; return true; };
  let frontier = [V0];
  for (let d = 0; d < depth; d++) {
    const next = [];
    for (const t of frontier) for (let k = 0; k < t.length; k++) {
      const g = geodesicThrough(t[k], t[(k + 1) % t.length]); if (g.line) continue;
      const refl = t.map((z) => reflect(z, g)), c = centroidEuc(refl);
      if (!isNew(c)) continue; centres.push(c); next.push(refl); tiles.push(refl);
    }
    frontier = next;
  }
  return tiles;
}
function hypTriangleArea(A, B, Cc) {
  const ang = (P, Q, R) => {
    const a = hypDist(Q, R), b = hypDist(P, R), c = hypDist(P, Q);
    return Math.acos(Math.max(-1, Math.min(1, (Math.cosh(b) * Math.cosh(c) - Math.cosh(a)) / (Math.sinh(b) * Math.sinh(c)))));
  };
  return Math.PI - (ang(A, B, Cc) + ang(B, A, Cc) + ang(Cc, A, B));
}
const polygonAreaNumeric = (v) => { let a = 0; for (let k = 1; k < v.length - 1; k++) a += hypTriangleArea(v[0], v[k], v[k + 1]); return a; };
for (const [p, q, depth] of [[7, 3, 3], [4, 5, 3], [5, 4, 2], [8, 3, 2]]) {
  const tiles = floodTiling(p, q, depth);
  check(`{${p},${q}} flood produced ${tiles.length} tiles`, tiles.length > p);
  const aForm = ((p - 2) - (2 * p) / q) * Math.PI;             // Gauss–Bonnet
  eqn(polygonAreaNumeric(tiles[0]), aForm, `{${p},${q}} central tile area (numeric vs Gauss–Bonnet)`, 1e-6);
  const far = tiles[tiles.length - 1];
  eqn(polygonAreaNumeric(far), aForm, `{${p},${q}} far tile equal hyp-area`, 1e-5);
  const eucSize = (t) => { const c = centroidEuc(t); return cabs(csub(t[0], c)); };
  check(`{${p},${q}} far tile is Euclid-smaller (shrinks only to the outside eye)`, eucSize(far) < eucSize(tiles[0]));
}
// q tiles meet at an interior vertex — the defining property of {p,q}. Cluster the
// generated vertices in the hyperbolic metric (same reason as the tile dedup), then
// the busiest (fully-surrounded, interior) vertex must carry exactly q tiles.
for (const [p, q] of [[7, 3], [4, 5], [5, 4], [8, 3]]) {
  const tiles = floodTiling(p, q, 5);
  const epsV = Math.acosh(Math.cosh(hypRadii(p, q).R) / Math.cosh(hypRadii(p, q).rin)); // half-edge s < full edge 2s
  const verts = [], counts = [];
  for (const t of tiles) for (const v of t) {
    let idx = -1;
    for (let i = 0; i < verts.length; i++) if (hypDist(v, verts[i]) < epsV) { idx = i; break; }
    if (idx < 0) { verts.push(v); counts.push(1); } else counts[idx]++;
  }
  const maxAt = Math.max(...counts);
  check(`{${p},${q}} interior vertices carry exactly q tiles`, maxAt === q, `busiest vertex has ${maxAt}, want ${q}`);
  // the central polygon's own vertex is interior once the flood is deep enough
  const v0 = centralPolygon(p, q)[0];
  let n0 = 0; for (let i = 0; i < verts.length; i++) if (hypDist(verts[i], v0) < epsV) n0 = counts[i];
  check(`{${p},${q}} central vertex closes up with q tiles`, n0 === q, `got ${n0}`);
}

// ── 6. THE FLOW is a hyperbolic isometry of the disk ─────────────────────────
// Two kinds. A translation along the x-axis (the Escher "zoom"), and the rotation
// about the centre that the live page uses to keep the disk always full — both are
// isometries, so the drift never distorts a single tile.
function translateX(z, t) { const a = C(Math.tanh(t / 2), 0); return cdiv(cadd(z, a), cadd(C(1, 0), cmul(a, z))); }
function rotate(z, th) { const c = Math.cos(th), s = Math.sin(th); return C(z.re * c - z.im * s, z.re * s + z.im * c); }
const FLOW_PTS = [C(0, 0), C(0.5, 0.2), C(-0.3, -0.4), C(0.1, 0.6)];
for (const t of [0.4, 1.0, -0.7]) {
  for (const z of FLOW_PTS) check(`translation stays in disk (t=${t})`, cabs(translateX(z, t)) < 1 + 1e-9);
  for (let i = 0; i < FLOW_PTS.length; i++) for (let j = i + 1; j < FLOW_PTS.length; j++)
    eqn(hypDist(translateX(FLOW_PTS[i], t), translateX(FLOW_PTS[j], t)), hypDist(FLOW_PTS[i], FLOW_PTS[j]), `translation preserves hyp-dist (t=${t})`, 1e-7);
  eqn(hypDist(C(0, 0), translateX(C(0, 0), t)), Math.abs(t), `translation moves origin by t=${t}`, 1e-7);
}
for (const th of [0.3, 1.7, -2.2]) {          // the page's actual drift
  for (const z of FLOW_PTS) check(`rotation stays in disk (θ=${th})`, cabs(rotate(z, th)) < 1 + 1e-9);
  for (let i = 0; i < FLOW_PTS.length; i++) for (let j = i + 1; j < FLOW_PTS.length; j++)
    eqn(hypDist(rotate(FLOW_PTS[i], th), rotate(FLOW_PTS[j], th)), hypDist(FLOW_PTS[i], FLOW_PTS[j]), `page rotation preserves hyp-dist (θ=${th})`, 1e-9);
}

// ── 7. EUCLIDEAN knife-edge: the defect vanishes exactly at g=0 ──────────────
for (const [p, q] of [[4, 4], [3, 6], [6, 3]]) {
  eqn((p - 2) * Math.PI - p * (TAU / q), 0, `{${p},${q}} euclidean angle defect = 0`, 1e-12);
  eqn(q * (TAU / q), TAU, `{${p},${q}} vertex angles sum to 2π`);
}

// ── 8. constants.json matches the re-derivation ──────────────────────────────
{
  const K = JSON.parse(readFileSync(join(HERE, 'constants.json'), 'utf8'));
  const round = (x, n = 6) => Number(x.toFixed(n));
  for (const row of K.reference.tilings) {
    const { p, q } = row, geo = hypGeom(p, q);
    check(`constants {${p},${q}} regime`, geo.regime === row.regime, `${geo.regime} vs ${row.regime}`);
    eqn(round(geo.interiorAngle), row.interiorAngleDeg, `constants {${p},${q}} interior angle`, 1e-6);
    eqn(round(geo.vertexSum), row.vertexSumDeg, `constants {${p},${q}} vertex sum`, 1e-6);
    if (row.regime === 'hyperbolic') {
      eqn(round(geo.R), row.hypCircumRadius, `constants {${p},${q}} R`, 1e-6);
      eqn(round(geo.eucR), row.poincareEucRadius, `constants {${p},${q}} eucR`, 1e-6);
      eqn(round(geo.tileAreaOverPi), row.tileAreaOverPi, `constants {${p},${q}} tileArea/π`, 1e-6);
    }
    if (row.regime === 'spherical') { const pl = platonic(p, q); eqn(pl.V, row.V, `constants {${p},${q}} V`); eqn(pl.E, row.E, `constants {${p},${q}} E`); eqn(pl.F, row.F, `constants {${p},${q}} F`); }
  }
  const h = K.reference.headline;
  eqn(round(hypGeom(7, 3).vertexSum), h.threeMeetSumDeg, 'headline: three heptagons at a corner (deg)', 1e-6);
  eqn(round(hypGeom(7, 3).vertexSum - 360), h.overshootDeg, 'headline: overshoot past 360°', 1e-6);
  eqn(round(hypGeom(7, 3).tileAreaOverPi), h.tileAreaOverPi, 'headline: {7,3} tile area/π', 1e-6);
}

// ── 9. DRIFT GUARD: the live page agrees with this math ──────────────────────
{
  const pagePath = join(HERE, '..', '..', 'public', 'strata', 'the-floor-that-wont-lie-flat', 'index.html');
  if (!existsSync(pagePath)) {
    check('page drift guard (page not built yet — skipped)', true);
  } else {
    const html = readFileSync(pagePath, 'utf8');
    // (a) extract the tagged canonical function and run it
    const m = html.match(/\/\*AW_HYP_CANONICAL_START\*\/([\s\S]*?)\/\*AW_HYP_CANONICAL_END\*\//);
    check('page carries the tagged canonical function', !!m);
    if (m) {
      let pageGeom = null;
      try { pageGeom = new Function(m[1] + '\n;return hypGeom;')(); } catch (e) { check('page canonical fn evaluates', false, String(e)); }
      if (pageGeom) {
        let drift = 0;
        for (let p = 3; p <= 10; p++) for (let q = 3; q <= 10; q++) {
          const a = pageGeom(p, q), b = hypGeom(p, q);
          if (a.regime !== b.regime || !near(a.interiorAngle, b.interiorAngle, 1e-9) || !near(a.vertexSum, b.vertexSum, 1e-9)) drift++;
          if (b.regime === 'hyperbolic' && (!near(a.R, b.R, 1e-9) || !near(a.eucR, b.eucR, 1e-9) || !near(a.tileAreaOverPi, b.tileAreaOverPi, 1e-9))) drift++;
        }
        check('page canonical fn matches verifier on the whole (p,q) grid', drift === 0, `${drift} disagreements`);
      }
    }
    // (b) the page's MODEL block equals constants.json headline
    const mm = html.match(/\/\*AW_HYP_MODEL_START\*\/([\s\S]*?)\/\*AW_HYP_MODEL_END\*\//);
    check('page carries the tagged MODEL block', !!mm);
    if (mm) {
      let MODEL = null;
      try { MODEL = new Function('return (' + mm[1] + ');')(); } catch (e) { check('page MODEL evaluates', false, String(e)); }
      if (MODEL) {
        const K = JSON.parse(readFileSync(join(HERE, 'constants.json'), 'utf8')).reference.headline;
        for (const key of ['p', 'q', 'interiorAngleDeg', 'threeMeetSumDeg', 'overshootDeg', 'tileAreaOverPi'])
          eqn(MODEL[key], K[key], `page MODEL.${key} === constants headline`, 1e-6);
      }
    }
  }
}

// ── 9. THE PROOF PAST THE LAST CASE (Lean 4, zero imports) ───────────────────
// Sections 1 and 2 settle the trichotomy by RUNNING it: p = 3..12 against q = 3..12,
// and a second sweep to 20 for the Euclidean census. Both are windows. The claims the
// page states — "exactly three flat regular tilings and no others", "the five spherical
// floors ARE the Platonic solids" — are about every p and every q, and no double loop
// can reach them. research/hyperbolic-tiling/lean/SchlafliTrichotomy.lean closes both.
// This section (a) re-derives the theorems' content over a far wider grid than the page
// ever shows, by a route that shares no code with §1, and (b) checks the proof file
// itself: zero imports, no holes, the theorem names present, and — if `lean` is on the
// PATH — the kernel re-run, live.
section('9. The proof past the last case (Lean 4)');
{
  // (a) an independent census over a grid 25x wider than §1's, from the vertex
  //     condition in whole numbers only: q*(p-2) against 2p. No floats, no 1/p.
  const sph = [], euc = [];
  let hyp = 0, tri = 0;
  for (let p = 3; p <= 500; p++) {
    for (let q = 3; q <= 500; q++) {
      const lhs = q * (p - 2), rhs = 2 * p;
      if (lhs < rhs) sph.push(`{${p},${q}}`); else if (lhs === rhs) euc.push(`{${p},${q}}`); else hyp++;
      // the Schlafli index of the Lean file, D(a,b) with a = p-3, b = q-3
      const a = p - 3, b = q - 3, D = a * b + a + b;
      if ((lhs < rhs) === (D < 3) && (lhs === rhs) === (D === 3)) tri++;
    }
  }
  check('vertex condition and the Lean file’s index D agree on every pair to 500',
    tri === 498 * 498, `${tri}/${498 * 498}`);
  check('exactly five spherical {p,q} up to 500 — the Platonic solids',
    sph.join(' ') === '{3,3} {3,4} {3,5} {4,3} {5,3}', sph.join(' '));
  check('exactly three Euclidean {p,q} up to 500',
    euc.join(' ') === '{3,6} {4,4} {6,3}', euc.join(' '));
  check('every other pair to 500 is hyperbolic', hyp === 498 * 498 - 8, String(hyp));
  // the infinitude the theorem states, witnessed: {N+4, 7} is hyperbolic for every N here
  let inf = 0;
  for (let N = 0; N <= 5000; N++) { const p = N + 4, q = 7; if (q * (p - 2) > 2 * p) inf++; }
  check('the witness family {N+4,7} is hyperbolic for every N to 5000', inf === 5001, String(inf));

  // (b) the proof file's own source-level invariants
  const leanPath = join(HERE, 'lean', 'SchlafliTrichotomy.lean');
  check('Lean proof file exists', existsSync(leanPath));
  if (existsSync(leanPath)) {
    const src = readFileSync(leanPath, 'utf8');
    check('Lean file has ZERO imports (only Lean’s kernel is trusted)',
      !/^\s*import\s/m.test(src));
    // Strip Lean's comments before hunting for holes: this file DISCUSSES `native_decide`
    // in its own header (it promises not to use one), and a naive grep reads that promise
    // as the thing it forbids.
    const code = src.replace(/\/-[\s\S]*?-\//g, ' ').replace(/--.*$/gm, ' ');
    for (const hole of ['sorry', 'admit', 'native_decide']) {
      check(`Lean file contains no \`${hole}\``, !new RegExp(`\\b${hole}\\b`).test(code));
    }
    for (const name of ['vertex_expand', 'vertex_lt', 'vertex_eq', 'vertex_gt', 'three_le_D',
      'D_eq_three_of_pos', 'spherical_iff', 'euclidean_iff', 'trichotomy',
      'hyperbolic_infinite', 'defect_eq', 'defect_link']) {
      check(`Lean file states theorem \`${name}\``, new RegExp(`theorem\\s+${name}\\b`).test(src));
    }
    check('Lean file prints its axiom footprint for every theorem',
      (src.match(/#print axioms/g) || []).length >= 12);

    // (c) the kernel itself, if it is here. Never asserted from a record.
    let leanBin = null;
    for (const cand of ['lean', `${process.env.HOME}/.elan/bin/lean`, `${process.env.HOME}/.nix-profile/bin/lean`]) {
      try { execFileSync(cand, ['--version'], { stdio: 'pipe' }); leanBin = cand; break; } catch { /* not here */ }
    }
    if (leanBin) {
      let out = '';
      try { out = execFileSync(leanBin, [leanPath], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 300000 }); }
      catch (e) { out = String(e.stdout || '') + String(e.stderr || ''); }
      const foot = out.match(/depends on axioms: \[([^\]]*)\]/g) || [];
      check('the Lean kernel accepts the file (no error lines)', !/error:/.test(out), out.slice(0, 300));
      check('the kernel reported a footprint for every theorem', foot.length >= 12, `${foot.length} footprints`);
      const dirty = foot.filter((f) => /sorryAx|Classical\.choice|native_decide/.test(f));
      check('no footprint contains sorryAx, Classical.choice or native_decide',
        dirty.length === 0, dirty.join(' | ').slice(0, 200));
    } else {
      skip('Lean kernel re-run (no `lean` on PATH — install: bash research/sorting-networks/lean/install-lean.sh)');
    }
  }
}

console.log(`\nthe-floor-that-wont-lie-flat · verify`);
console.log(`  ${pass}/${pass + fail} checks pass`);
if (skipped.length) { console.log('  skipped:'); skipped.forEach((x) => console.log('   • ' + x)); }
if (fail) { console.log('  FAILURES:'); bad.forEach((b) => console.log('   ✗ ' + b)); process.exit(1); }
