import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";

const LIMIT = 12;
let checks = 0;

function fail(message) {
  console.error(`FAIL: ${message}`);
  process.exit(1);
}

function assertEqual(actual, expected, label) {
  checks += 1;
  if (actual !== expected) {
    fail(`${label}: expected ${expected}, got ${actual}`);
  }
  console.log(`ok ${label}: ${actual}`);
}

function assert(condition, label) {
  checks += 1;
  if (!condition) fail(label);
  console.log(`ok ${label}`);
}

function choose(n, k) {
  if (k < 0 || k > n) return 0n;
  let out = 1n;
  for (let i = 1; i <= k; i += 1) {
    out = (out * BigInt(n - i + 1)) / BigInt(i);
  }
  return out;
}

function multiply(a, b, maxDegree) {
  const out = Array(maxDegree + 1).fill(0n);
  for (let i = 0; i < a.length && i <= maxDegree; i += 1) {
    for (let j = 0; j < b.length && i + j <= maxDegree; j += 1) {
      out[i + j] += a[i] * b[j];
    }
  }
  return out;
}

function powerSeries(base, exponent, maxDegree) {
  let out = Array(maxDegree + 1).fill(0n);
  out[0] = 1n;
  for (let i = 0; i < exponent; i += 1) {
    out = multiply(out, base, maxDegree);
  }
  return out;
}

function factorProduct(terms, maxDegree) {
  let out = Array(maxDegree + 1).fill(0n);
  out[0] = 1n;
  for (const { step, exponent } of terms) {
    for (let n = step; n <= maxDegree; n += step) {
      const factor = Array(maxDegree + 1).fill(0n);
      if (exponent >= 0) {
        for (let k = 0; k <= exponent && k * n <= maxDegree; k += 1) {
          factor[k * n] = (k % 2 ? -1n : 1n) * choose(exponent, k);
        }
      } else {
        for (let k = 0; k * n <= maxDegree; k += 1) {
          factor[k * n] = choose(-exponent + k - 1, k);
        }
      }
      out = multiply(out, factor, maxDegree);
    }
  }
  return out;
}

function divideSeries(numerator, denominator, maxDegree) {
  if (denominator[0] !== 1n) fail("series division requires constant term 1");
  const out = Array(maxDegree + 1).fill(0n);
  for (let n = 0; n <= maxDegree; n += 1) {
    let value = numerator[n] ?? 0n;
    for (let k = 1; k <= n; k += 1) {
      value -= (denominator[k] ?? 0n) * out[n - k];
    }
    out[n] = value;
  }
  return out;
}

function sigma3(n) {
  let out = 0n;
  for (let d = 1; d <= n; d += 1) {
    if (n % d === 0) out += BigInt(d) ** 3n;
  }
  return out;
}

function computeJ(maxGrade) {
  const workDegree = maxGrade + 1;
  const e4 = Array(workDegree + 1).fill(0n);
  e4[0] = 1n;
  for (let n = 1; n <= workDegree; n += 1) {
    e4[n] = 240n * sigma3(n);
  }
  const e4Cubed = powerSeries(e4, 3, workDegree);
  const deltaOverQ = factorProduct([{ step: 1, exponent: 24 }], workDegree);
  const jShifted = divideSeries(e4Cubed, deltaOverQ, workDegree);
  if (jShifted[1] !== 744n) fail("derived j constant is not 744");
  return {
    jConstant: jShifted[1],
    coefficients: Array.from({ length: maxGrade }, (_, i) => jShifted[i + 2]),
  };
}

function plusProduct(exponent, maxDegree) {
  let out = Array(maxDegree + 1).fill(0n);
  out[0] = 1n;
  for (let n = 1; n <= maxDegree; n += 1) {
    const factor = Array(maxDegree + 1).fill(0n);
    for (let k = 0; k * n <= maxDegree; k += 1) {
      const coefficient = choose(exponent + k - 1, k);
      factor[k * n] = k % 2 ? -coefficient : coefficient;
    }
    out = multiply(out, factor, maxDegree);
  }
  return out;
}

function etaTrace(numeratorStep, numeratorPower, denominatorStep, denominatorPower, maxGrade) {
  const product = factorProduct([
    { step: numeratorStep, exponent: numeratorPower },
    { step: denominatorStep, exponent: -denominatorPower },
  ], maxGrade + 1);
  return Array.from({ length: maxGrade }, (_, i) => product[i + 2]);
}

const j = computeJ(LIMIT);
assertEqual(j.jConstant, 744n, "external anchor, j constant");

const publishedJ = [
  196884n,
  21493760n,
  864299970n,
  20245856256n,
  333202640600n,
  4252023300096n,
  44656994071935n,
  401490886656000n,
];
for (let i = 0; i < publishedJ.length; i += 1) {
  assertEqual(j.coefficients[i], publishedJ[i], `J coefficient q^${i + 1}`);
}

const twoBProduct = plusProduct(24, LIMIT + 1);
const twoB = Array.from({ length: LIMIT }, (_, i) => twoBProduct[i + 2]);
const reciprocalTwoBProduct = divideSeries(
  [1n, ...Array(LIMIT + 1).fill(0n)],
  twoBProduct,
  LIMIT + 1,
);
const twoA = twoB.map((value, i) => value + 4096n * reciprocalTwoBProduct[i]);

// External anchors for the two involution series. The 2B values are the McKay-Thompson series of
// class 2B; the 2A values are the McKay-Thompson series of class 2A (OEIS A007267, whose data is
// 1, 104, 4372, 96256, 1240002, 10698752, 74428120, 431529984, ... from n = -1, and which cites
// Conway and Norton). The 2A series is the one input the page states rather than derives:
// T_2A = R + 4096/R with R the FLM product, so these five coefficients are its whole check.
const publishedTwoA = [4372n, 96256n, 1240002n, 10698752n, 74428120n, 431529984n];
const publishedTwoB = [276n, -2048n, 11202n, -49152n, 184024n, -614400n];
for (let i = 0; i < publishedTwoA.length; i += 1) {
  assertEqual(twoB[i], publishedTwoB[i], `external anchor, 2B trace q^${i + 1}`);
  assertEqual(twoA[i], publishedTwoA[i], `external anchor, 2A trace q^${i + 1}`);
}

const classNames = ["2B", "3B", "5B", "7B", "9B", "13B", "15D"];
const traces = {
  "2B": twoB,
  "3B": etaTrace(1, 12, 3, 12, LIMIT),
  "5B": etaTrace(1, 6, 5, 6, LIMIT),
  "7B": etaTrace(1, 4, 7, 4, LIMIT),
  "9B": etaTrace(1, 3, 9, 3, LIMIT),
  "13B": etaTrace(1, 2, 13, 2, LIMIT),
  "15D": etaTrace(3, 2, 15, 2, LIMIT),
};

const publishedTraceHeads = {
  "2B": [276n, -2048n, 11202n, -49152n, 184024n],
  "3B": [54n, -76n, -243n, 1188n, -1384n],
  "5B": [9n, 10n, -30n, 6n, -25n],
  "7B": [2n, 8n, -5n, -4n, -10n],
  "9B": [0n, 5n, 0n, 0n, -7n],
  "13B": [-1n, 2n, 1n, 2n, -2n],
  "15D": [0n, -2n, 0n, 0n, -1n],
};

for (const name of classNames) {
  for (let grade = 0; grade < 5; grade += 1) {
    assertEqual(
      traces[name][grade],
      publishedTraceHeads[name][grade],
      `${name} trace q^${grade + 1}`,
    );
  }
}

const characterMatrix = [
  [1n, 1n, 1n, 1n, 1n, 1n, 1n],
  [275n, 53n, 8n, 1n, -1n, -2n, -1n],
  [-2324n, -130n, 1n, 6n, 5n, 3n, -2n],
  [12974n, -221n, -49n, -15n, -5n, 0n, 2n],
  [123004n, 1598n, 76n, 14n, 5n, 2n, -2n],
  [-58305n, 1508n, 27n, -6n, -4n, 0n, 3n],
  [98970n, -3927n, -77n, -15n, -12n, -7n, 1n],
];

function bareissDeterminant(input) {
  const a = input.map((row) => row.slice());
  let sign = 1n;
  let previous = 1n;
  for (let k = 0; k < a.length - 1; k += 1) {
    let pivotRow = k;
    while (pivotRow < a.length && a[pivotRow][k] === 0n) pivotRow += 1;
    if (pivotRow === a.length) return 0n;
    if (pivotRow !== k) {
      [a[pivotRow], a[k]] = [a[k], a[pivotRow]];
      sign = -sign;
    }
    const pivot = a[k][k];
    for (let i = k + 1; i < a.length; i += 1) {
      for (let column = k + 1; column < a.length; column += 1) {
        a[i][column] =
          (a[i][column] * pivot - a[i][k] * a[k][column]) / previous;
      }
      a[i][k] = 0n;
    }
    previous = pivot;
  }
  return sign * a.at(-1).at(-1);
}

assertEqual(
  bareissDeterminant(characterMatrix),
  35672555520n,
  "external anchor, seven-class determinant",
);

// The three-by-three head block the page also ships and prints in bench 3. Rows are chi1, chi2,
// chi3; columns are the classes 1A, 2A, 2B. Read from GAP CTblLib 1.3.9, data/ctomonst.tbl: the
// first three irreducibles of M begin (1, 1, 1), (196883, 4371, 275), (21296876, 91884, -2324).
const headClassNames = ["1A", "2A", "2B"];
const headCharacterMatrix = [
  [1n, 1n, 1n],
  [196883n, 4371n, 275n],
  [21296876n, 91884n, -2324n],
];
const headDeterminant = bareissDeterminant(headCharacterMatrix);
assertEqual(headDeterminant, -(2n ** 36n), "head block determinant is minus two to the thirty-six");

// The eighth irreducible degree, same table, same read. It is what makes seven columns sufficient:
// nothing of degree above dim V5 can occur in V1 through V5.
const eighthDegree = 3879214937598n;

function gcd(a, b) {
  let x = a < 0n ? -a : a;
  let y = b < 0n ? -b : b;
  while (y !== 0n) [x, y] = [y, x % y];
  return x;
}

function fraction(numerator, denominator = 1n) {
  if (denominator === 0n) fail("zero rational denominator");
  let n = numerator;
  let d = denominator;
  if (d < 0n) {
    n = -n;
    d = -d;
  }
  const divisor = gcd(n, d);
  return { n: n / divisor, d: d / divisor };
}

function add(a, b) {
  return fraction(a.n * b.d + b.n * a.d, a.d * b.d);
}

function subtract(a, b) {
  return fraction(a.n * b.d - b.n * a.d, a.d * b.d);
}

function multiplyFractions(a, b) {
  return fraction(a.n * b.n, a.d * b.d);
}

function divideFractions(a, b) {
  return fraction(a.n * b.d, a.d * b.n);
}

function solve(matrix, vector) {
  const augmented = matrix.map((row, index) => [
    ...row.map((value) => fraction(value)),
    fraction(vector[index]),
  ]);
  for (let column = 0; column < matrix.length; column += 1) {
    let pivot = column;
    while (pivot < matrix.length && augmented[pivot][column].n === 0n) pivot += 1;
    if (pivot === matrix.length) fail("singular rational solve");
    [augmented[column], augmented[pivot]] = [augmented[pivot], augmented[column]];
    const pivotValue = augmented[column][column];
    for (let j = column; j <= matrix.length; j += 1) {
      augmented[column][j] = divideFractions(augmented[column][j], pivotValue);
    }
    for (let i = 0; i < matrix.length; i += 1) {
      if (i === column) continue;
      const scale = augmented[i][column];
      for (let j = column; j <= matrix.length; j += 1) {
        augmented[i][j] = subtract(
          augmented[i][j],
          multiplyFractions(scale, augmented[column][j]),
        );
      }
    }
  }
  return augmented.map((row) => row.at(-1));
}

const transposedMatrix = characterMatrix[0].map((_, column) =>
  characterMatrix.map((row) => row[column]),
);
const expectedMultiplicities = [
  [1n, 1n, 0n, 0n, 0n, 0n, 0n],
  [1n, 1n, 1n, 0n, 0n, 0n, 0n],
  [2n, 2n, 1n, 1n, 0n, 0n, 0n],
  [2n, 3n, 2n, 1n, 0n, 1n, 0n],
  [4n, 5n, 3n, 2n, 1n, 1n, 1n],
];
const irreducibleDegrees = [
  1n,
  196883n,
  21296876n,
  842609326n,
  18538750076n,
  19360062527n,
  293553734298n,
];

for (let grade = 0; grade < 5; grade += 1) {
  const vector = classNames.map((name) => traces[name][grade]);
  const result = solve(transposedMatrix, vector);
  const rendered = result.map(({ n, d }) => (d === 1n ? n.toString() : `${n}/${d}`));
  assert(
    result.every(({ n, d }, i) => d === 1n && n === expectedMultiplicities[grade][i]),
    `grade q^${grade + 1} certificate solves to [${rendered.join(", ")}]`,
  );
  const dimension = result.reduce(
    (sum, value, i) => sum + (value.n / value.d) * irreducibleDegrees[i],
    0n,
  );
  assertEqual(dimension, j.coefficients[grade], `grade q^${grade + 1} dimension`);
}

// The head block solves the first two graded pieces on its own, from three classes only. This is
// what bench 3 of the page prints, and until now nothing here compared against it.
const transposedHead = headCharacterMatrix[0].map((_, column) =>
  headCharacterMatrix.map((row) => row[column]),
);
const expectedHeadMultiplicities = [
  [1n, 1n, 0n],
  [1n, 1n, 1n],
];
for (let grade = 0; grade < expectedHeadMultiplicities.length; grade += 1) {
  const vector = [j.coefficients[grade], twoA[grade], twoB[grade]];
  const result = solve(transposedHead, vector);
  assert(
    result.every(({ n, d }, i) => d === 1n && n === expectedHeadMultiplicities[grade][i]),
    `head block at q^${grade + 1} solves to (${expectedHeadMultiplicities[grade].join(", ")})`,
  );
}

// Seven columns determine V1 through V5 because there is no eighth candidate to hide in them.
const dimensionOfV5 = j.coefficients[4];
assert(
  eighthDegree > dimensionOfV5,
  `eighth irreducible degree ${eighthDegree} exceeds dim V5 ${dimensionOfV5}`,
);

let brokenMutations = 0;
for (let grade = 0; grade < 5; grade += 1) {
  const original = classNames.map((name) => traces[name][grade]);
  for (let column = 0; column < classNames.length; column += 1) {
    const mutated = original.slice();
    mutated[column] += 1n;
    const result = solve(transposedMatrix, mutated);
    if (result.some(({ n, d }) => d !== 1n || n < 0n)) brokenMutations += 1;
  }
}
assertEqual(brokenMutations, 35, "all one-trace mutations break integrality or positivity");

function recurrence4(series, squareSeries) {
  return series[2] + (series[0] ** 2n - squareSeries[0]) / 2n;
}

function recurrence6(series) {
  return series[3] + series[0] * series[1];
}

function recurrence8(series, squareSeries) {
  return (
    series[4] +
    (series[1] ** 2n - squareSeries[1]) / 2n +
    series[0] * series[2]
  );
}

assertEqual(recurrence4(twoB, j.coefficients), twoB[3], "recurrence 9.1 forces 2B q^4");
assertEqual(recurrence6(twoB), twoB[5], "recurrence 9.1 forces 2B q^6");
assertEqual(recurrence8(twoB, j.coefficients), twoB[7], "recurrence 9.1 forces 2B q^8");

// ───────────────────────────────────────────────────────────────────────────────
// PAGE COUPLING.
//
// Everything above re-derives the mathematics from scratch. That is worth nothing
// to a reader unless the numbers the SHIPPED PAGE puts on screen are the same ones.
// So this section reads public/strata/moonshine-196884/index.html, lifts out the
// page's own arithmetic engine (the block between the ENGINE START / ENGINE END
// markers, which is DOM-free by construction), executes it, and compares its
// outputs against the values computed above. It also scrapes the page's static
// text for the anchors it prints in prose, building the expected strings from the
// recomputed values rather than from literals typed here.
//
// If someone edits a number on the page, this fails. That is the whole point.
// ───────────────────────────────────────────────────────────────────────────────

const here = dirname(fileURLToPath(import.meta.url));
const pagePath = resolve(here, "../../public/strata/moonshine-196884/index.html");
const html = readFileSync(pagePath, "utf8");

const engineStart = html.indexOf("===== MOONSHINE ENGINE START =====");
const engineEnd = html.indexOf("===== MOONSHINE ENGINE END =====");
if (engineStart < 0 || engineEnd < 0 || engineEnd < engineStart) {
  fail("could not find the MOONSHINE ENGINE markers in the shipped page");
}
// the markers sit inside block comments, so restore the delimiters the slice cut off
const engineSource = `/*${html.slice(engineStart, engineEnd)}*/`;
const page = new Function(`${engineSource}\n;return MOONSHINE;`)();
assert(page && typeof page.series === "function", "page engine extracted and executed");

function bigList(values) {
  return values.map((value) => value.toString()).join(",");
}

// --- the page's sourced fixtures are the ones this file verified ---------------
assertEqual(
  page.CHARACTER_MATRIX.map(bigList).join(" | "),
  characterMatrix.map(bigList).join(" | "),
  "page ships the same 7 by 7 character matrix",
);
assertEqual(
  bigList(page.DEGREES),
  bigList(irreducibleDegrees),
  "page ships the same seven irreducible degrees",
);
assertEqual(
  page.CLASSES.join(","),
  classNames.join(","),
  "page ships Borcherds's seven separating classes",
);
assertEqual(
  page.HEAD_MATRIX.map(bigList).join(" | "),
  headCharacterMatrix.map(bigList).join(" | "),
  "page ships the same 3 by 3 head character block",
);
assertEqual(
  page.HEAD_CLASSES.join(","),
  headClassNames.join(","),
  "page ships the same three head classes",
);
assertEqual(page.DEGREE_CHI8, eighthDegree, "page ships the same eighth irreducible degree");
assertEqual(
  Object.entries(page.SQUARE_OF).map(([k, v]) => `${k}->${v}`).join(","),
  "1A->1A,2A->1A,2B->1A,3B->3B,5B->5B,7B->7B,9B->9B,13B->13B,15D->15D",
  "page ships the ATLAS squaring power map",
);

// The cycle-shape strings beside the six eta quotients are not decoration: parse each one and
// require the numeric fields to be its reciprocal, which is Borcherds's f = 1 / eta_g. A label
// that drifted away from the series it names would fail here.
const publishedCycleShapes = {
  "3B": "3^12 1^-12",
  "5B": "5^6 1^-6",
  "7B": "7^4 1^-4",
  "9B": "9^3 1^-3",
  "13B": "13^2 1^-2",
  "15D": "15^2 3^-2",
};
for (const [name, shape] of Object.entries(publishedCycleShapes)) {
  const entry = page.ETA[name];
  assertEqual(entry.cycleShape, shape, `page ships Borcherds's cycle shape for ${name}`);
  const parsed = /^(\d+)\^(\d+) (\d+)\^-(\d+)$/.exec(shape);
  if (!parsed) fail(`could not parse cycle shape ${shape}`);
  const [, denText, denPowText, numText, numPowText] = parsed;
  assert(
    entry.den === Number(denText) &&
      entry.denPow === Number(denPowText) &&
      entry.num === Number(numText) &&
      entry.numPow === Number(numPowText),
    `page ${name} series is the reciprocal of the eta product of its own cycle shape ${shape}`,
  );
}

// --- the page's modular engine reproduces this file's expansions ---------------
assertEqual(page.constantOfJ(), 744n, "page derives the same j constant");
assertEqual(
  bigList(Array.from({ length: LIMIT }, (_, i) => page.coefficient("1A", i + 1))),
  bigList(j.coefficients),
  "page J expansion equals this file's J expansion",
);
assertEqual(
  bigList(Array.from({ length: LIMIT }, (_, i) => page.coefficient("2A", i + 1))),
  bigList(twoA),
  "page 2A expansion equals this file's 2A expansion",
);
for (const name of classNames) {
  assertEqual(
    bigList(Array.from({ length: LIMIT }, (_, i) => page.coefficient(name, i + 1))),
    bigList(traces[name]),
    `page ${name} expansion equals this file's ${name} expansion`,
  );
}

// --- the page's certificate lands where this file's certificate lands ----------
const pageDeterminant = page.determinant();
assertEqual(
  pageDeterminant,
  bareissDeterminant(characterMatrix),
  "page determinant equals this file's determinant",
);
assertEqual(
  page.headDeterminant(),
  headDeterminant,
  "page head determinant equals this file's head determinant",
);
const pageHeadSolves = [];
for (let grade = 1; grade <= expectedHeadMultiplicities.length; grade += 1) {
  const head = page.headDecompose(grade);
  assertEqual(
    bigList(head.used),
    bigList([j.coefficients[grade - 1], twoA[grade - 1], twoB[grade - 1]]),
    `page head bench at V${grade} uses the traces this file expanded`,
  );
  const rendered = head.solution.map((f) => (f.d === 1n ? f.n.toString() : `${f.n}/${f.d}`));
  assertEqual(
    rendered.join(","),
    bigList(expectedHeadMultiplicities[grade - 1]),
    `page head bench at V${grade} solves to this file's multiplicities`,
  );
  pageHeadSolves.push(rendered);
}

for (let grade = 1; grade <= 5; grade += 1) {
  const solved = page.decompose(grade, -1, 0);
  assertEqual(
    solved.solution.map((f) => (f.d === 1n ? f.n.toString() : `${f.n}/${f.d}`)).join(","),
    bigList(expectedMultiplicities[grade - 1]),
    `page V${grade} multiplicities equal this file's V${grade} multiplicities`,
  );
  assertEqual(
    solved.dimension,
    j.coefficients[grade - 1],
    `page V${grade} rebuilt dimension equals this file's J coefficient`,
  );
  assert(
    solved.residual.every((f) => f.n === 0n),
    `page V${grade} residual vector is exactly zero`,
  );
}

const pageSweepUp = page.mutationSweep(1);
assertEqual(pageSweepUp.total, brokenMutations, "page sweeps the same 35 one-unit mutations");
assertEqual(pageSweepUp.broken, brokenMutations, "page rejects the same 35 mutations this file rejects");
const pageSweepDown = page.mutationSweep(-1);
assertEqual(pageSweepDown.broken, pageSweepDown.total, "page also rejects every minus-one mutation");

// --- the page's recurrence output is checked against series expanded HERE ------
assertEqual(
  page.recurrence("2B", 4).predicted,
  recurrence4(twoB, j.coefficients),
  "page recurrence at 2B q^4 equals this file's recurrence",
);
assertEqual(
  page.recurrence("2B", 6).predicted,
  recurrence6(twoB),
  "page recurrence at 2B q^6 equals this file's recurrence",
);
assertEqual(
  page.recurrence("2B", 8).predicted,
  recurrence8(twoB, j.coefficients),
  "page recurrence at 2B q^8 equals this file's recurrence",
);

let forced = 0;
const pageTargets = page.REC_TARGETS;
for (const name of classNames) {
  for (const target of pageTargets) {
    const predicted = page.recurrence(name, target).predicted;
    if (predicted === traces[name][target - 1]) forced += 1;
    else fail(`page recurrence ${name} n=${target}: predicted ${predicted}, this file expanded ${traces[name][target - 1]}`);
  }
}
assertEqual(
  forced,
  classNames.length * pageTargets.length,
  "every page recurrence prediction matches a series expanded independently here",
);
assertEqual(
  page.recurrenceSweep().ok,
  forced,
  "page's own recurrence tally equals the tally checked here",
);

// --- the page's STATIC text carries the anchors, spelled from recomputed values -
const subs = ["&#8320;", "&#8321;", "&#8322;", "&#8323;", "&#8324;", "&#8325;", "&#8326;", "&#8327;"];
const normalised = html.replace(/\s+/g, " ");

// The four decomposition strings in the check panel are REBUILT here from the page engine's own
// multiplicity vectors and then looked for in the page's static prose. Editing "2chi1" to "7chi1"
// in the prose no longer passes quietly, which was the exact hole this gate was written to close.
function decompositionSpan(grade, multiplicities) {
  const terms = [];
  for (let i = 0; i < multiplicities.length; i += 1) {
    const a = multiplicities[i];
    if (a === 0n) continue;
    terms.push(`${a === 1n ? "" : a.toString()}&#967;${subs[i + 1]}`);
  }
  return `<span class="mono">V${subs[grade]} = ${terms.join(" + ")}</span>`;
}
for (const grade of [1, 2, 3, 5]) {
  const multiplicities = page.decompose(grade, -1, 0).solution.map((f) => {
    if (f.d !== 1n) fail(`page V${grade} multiplicity is not an integer`);
    return f.n;
  });
  const span = decompositionSpan(grade, multiplicities);
  assert(
    normalised.includes(span.replace(/\s+/g, " ")),
    `check panel prints V${grade} exactly as the engine solves it: ${span}`,
  );
}

const headSolveText = pageHeadSolves.map((row) => `(${row.join(", ")})`);
const staticAnchors = [
  [`${j.coefficients[0]} = ${irreducibleDegrees[1]} + 1`, "the headline split, in the page's prose"],
  [`${j.coefficients[1]}`, "the q^2 coefficient, in the page's prose"],
  [`${pageDeterminant}`, "the determinant, in the page's prose"],
  [`${irreducibleDegrees[1]}`, "the degree 196883, in the page's prose"],
  [`${pageDeterminant}n`, "the determinant, as the page's own comparison constant"],
  [`j - ${j.jConstant}`, "the definition of J, in the page's prose"],
  // the head block, which the page prints in bench 3 and quotes in the check panel
  [`(${headCharacterMatrix[1].join(", ")})`, "the chi2 row of the head block"],
  [`(${headCharacterMatrix[2].join(", ")})`, "the chi3 row of the head block"],
  [`${headDeterminant}`, "the head block determinant"],
  [headSolveText[0], "the head solve at V1"],
  [headSolveText[1], "the head solve at V2"],
  // the seven-columns-are-enough bound
  [`${eighthDegree}`, "the eighth irreducible degree"],
  [`${dimensionOfV5}`, "dim V5, which the eighth degree exceeds"],
  // the two involution series, whose heads are the only check on the quoted 2A formula
  [publishedTwoA.slice(0, 5).join(", "), "the published 2A head"],
  [publishedTwoB.slice(0, 5).join(", "), "the published 2B head"],
];
const factorText = (() => {
  let remaining = pageDeterminant;
  const parts = [];
  for (let p = 2n; p * p <= remaining; p += 1n) {
    let e = 0;
    while (remaining % p === 0n) { remaining /= p; e += 1; }
    if (e) parts.push(`${p}^${e}`);
  }
  if (remaining > 1n) parts.push(`${remaining}^1`);
  return parts.join(" ");
})();
staticAnchors.push([
  `${pageDeterminant} = ${factorText}`,
  "Borcherds's printed factorisation, quoted on the page",
]);
for (const [needle, label] of staticAnchors) {
  assert(normalised.includes(needle.replace(/\s+/g, " ")), `page text contains ${label}: ${needle}`);
}

// The headline split is the page's single most quotable sentence, so it is checked by
// shape as well as by presence: every "A = B + 1" written anywhere on the page must be
// the recomputed one, and it must appear in both the meta description and the dek.
const splitText = `${j.coefficients[0]} = ${irreducibleDegrees[1]} + 1`;
const allSplits = html.match(/\d{4,} = \d{4,} \+ 1/g) || [];
assert(
  allSplits.length >= 2 && allSplits.every((text) => text === splitText),
  `every "A = B + 1" on the page is the recomputed split (found ${allSplits.length}: ${[...new Set(allSplits)].join(" / ")})`,
);

// ---------------------------------------------------------------------------------
// THE NUMERAL GATES. The page has three text regions and each gets its own rule.
//   engine  : every value in it is compared against a re-derivation above, so no textual
//             gate is needed or would add anything.
//   prose   : every run of four or more digits must be a value recomputed above or a
//             declared, labelled exception. Character entities are stripped first, since
//             &#8321; is markup and not a number.
//   render  : the DOM layer. It must never invent a number, so the rule is stricter: no
//             quoted digit string and no multi-digit literal beyond a short declared list,
//             plus the cell-writing expressions have to be present verbatim.
// This is a pattern check on the render layer, not an execution of it. Named as such in
// the check panel and in the README.
// ---------------------------------------------------------------------------------
const renderStart = html.indexOf("===== RENDER LAYER START =====");
const renderEnd = html.indexOf("===== RENDER LAYER END =====");
if (renderStart < 0 || renderEnd < 0 || renderEnd < renderStart) {
  fail("could not find the RENDER LAYER markers in the shipped page");
}
assert(renderStart > engineEnd, "the render layer follows the engine block");
const renderRegion = html.slice(renderStart, renderEnd);
const proseRegion = (
  html.slice(0, engineStart) +
  html.slice(engineEnd, renderStart) +
  html.slice(renderEnd)
)
  .replace(/<style>[\s\S]*?<\/style>/g, "")
  .replace(/&#\d+;/g, "")
  .replace(/#[0-9a-fA-F]{3,8}/g, "");

const recomputedLongNumbers = new Set();
for (const value of [
  ...j.coefficients,
  ...irreducibleDegrees,
  eighthDegree,
  ...twoA,
  ...twoB,
  ...headCharacterMatrix.flat(),
  ...classNames.flatMap((name) => traces[name]),
  headDeterminant,
  bareissDeterminant(characterMatrix),
]) {
  const text = (value < 0n ? -value : value).toString();
  if (text.length >= 4) recomputedLongNumbers.add(text);
}
const declaredExceptions = new Map([
  ["8675309", "the reader's default input in the padding bench, not a claim"],
  ["196882", "quoted, not computed here: the smallest faithful representation over GF(2)"],
  ["4096", "the quoted Conway-Norton constant in T_2A = R + 4096/R; its check is the 2A head above"],
  ["1112", "part of the BLMS DOI 10.1112/blms/11.3.308"],
  ["1073", "part of the PNAS DOI 10.1073/pnas.81.10.3256"],
  ["3256", "first page of the PNAS paper, and part of its DOI"],
  ["3260", "last page of the PNAS paper"],
  ["1007", "part of the Inventiones DOI 10.1007/BF01232032"],
  ["01232032", "part of the Inventiones DOI 10.1007/BF01232032"],
  ["853199", "part of the ATLAS ISBN 0-19-853199-0"],
  ["2412", "part of arXiv:2412.12182"],
  ["12182", "part of arXiv:2412.12182"],
  ["1978", "the year McKay noticed the addition"],
  ["1979", "the year of the Conway-Norton paper"],
  ["1984", "the year of the Frenkel-Lepowsky-Meurman announcement"],
  ["1985", "the year of the ATLAS"],
  ["1992", "the year of Borcherds's proof"],
  ["2024", "the year of the Breuer-Magaard-Wilson preprint"],
  ["2026", "the page's own publication date in the metadata"],
  ["1200", "the declared og:image width in pixels"],
]);
const undeclaredProse = [...new Set(proseRegion.match(/[0-9]{4,}/g) || [])].filter(
  (text) => !recomputedLongNumbers.has(text) && !declaredExceptions.has(text),
);
assert(
  undeclaredProse.length === 0,
  `every four-digit-or-longer number in the page's prose is recomputed or declared (undeclared: ${undeclaredProse.join(", ") || "none"})`,
);
for (const [text, why] of declaredExceptions) {
  assert(
    proseRegion.includes(text),
    `declared exception still present and labelled: ${text} (${why})`,
  );
}

// the render layer's declared numerals, each with the reason it is allowed to be a literal
const renderNumerals = new Map([
  [pageDeterminant.toString(), "the page's comparison against Borcherds's printed determinant"],
  ["22", "the exponent inside the quoted factorisation, itself gated by the anchor above"],
  [String(page.CLASSES.length * page.REC_TARGETS.length), "the count of recurrence targets, checked below"],
  ["3200", "reduced-motion step delay in milliseconds"],
  ["1300", "default step delay in milliseconds"],
]);
assertEqual(
  Number(page.CLASSES.length * page.REC_TARGETS.length),
  56,
  "the walk really does have 56 steps, so the button may say so",
);
assert(
  Number(3200) > Number(1300),
  "the reduced-motion delay is longer than the default, never zero",
);
const renderDigitRuns = [
  ...new Set(renderRegion.replace(/#[0-9a-fA-F]{3,8}/g, "").match(/[0-9]{2,}/g) || []),
].filter((text) => !renderNumerals.has(text));
assert(
  renderDigitRuns.length === 0,
  `the render layer holds no undeclared multi-digit literal (found: ${renderDigitRuns.join(", ") || "none"})`,
);
const quotedDigits = [
  ...new Set((renderRegion.match(/(['"])\d+\1/g) || []).map((t) => t.slice(1, -1))),
].filter((text) => text !== "0");
assert(
  quotedDigits.length === 0,
  `the render layer holds no quoted numeral other than the '0' input guard (found: ${quotedDigits.join(", ") || "none"})`,
);

// Every table cell the page fills has to be written from an engine value. These are the
// expressions that do it; if one is replaced by a literal, this fails.
const cellWriters = [
  "M.coefficient('1A', n).toString()",
  "td(M.HEAD_MATRIX[c][r].toString())",
  "td(M.DEGREES[r].toString())",
  "td(M.CHARACTER_MATRIX[r][k].toString())",
  "td(d.used[r].toString())",
  "td(r.terms[i].value.toString())",
  "td(r.predicted.toString())",
];
for (const expression of cellWriters) {
  assert(
    renderRegion.includes(expression),
    `render layer still writes a cell from the engine: ${expression}`,
  );
}

assert(
  html.includes('<link rel="canonical" href="https://artwaste.land/strata/moonshine-196884/" />'),
  "page carries the honest canonical link",
);
assert(html.includes('"@type":"Article"'), "page carries JSON-LD");

// The social card the head tags promise has to exist, and at the size they promise. This page
// shipped once with the tags pointing at a file that was never generated.
const cardBytes = readFileSync(resolve(here, "../../public/og/moonshine-196884.png"));
assertEqual(cardBytes.subarray(1, 4).toString("latin1"), "PNG", "the declared og:image is a PNG");
const cardWidth = cardBytes.readUInt32BE(16);
const cardHeight = cardBytes.readUInt32BE(20);
assert(
  html.includes(`<meta property="og:image:width" content="${cardWidth}" />`) &&
    html.includes(`<meta property="og:image:height" content="${cardHeight}" />`),
  `the og:image tags declare the card's real size, ${cardWidth} by ${cardHeight}`,
);
assert(
  html.includes('content="https://artwaste.land/og/moonshine-196884.png"') &&
    html.includes('name="twitter:image" content="https://artwaste.land/og/moonshine-196884.png"'),
  "both card tags point at the file that exists",
);
assert(
  (html.match(/<script/g) || []).length === (html.match(/<\/script>/g) || []).length,
  "every script tag on the page is closed",
);
assert(html.trimEnd().endsWith("-->") && html.includes("</body>\n</html>"), "page closes body and html");
assert(!/src="https?:/.test(html) && !/<link[^>]+stylesheet[^>]+https?:/.test(html), "page makes no third-party requests");

console.log("");
console.log(`PASS: ${checks} exact checks`);
console.log(`J head: ${j.coefficients.slice(0, 8).join(", ")}`);
console.log(`2B head: ${twoB.slice(0, 8).join(", ")}`);
console.log(`certificate determinant: ${bareissDeterminant(characterMatrix)}`);
console.log(`mutation sweep: ${brokenMutations} of ${classNames.length * 5} rejected`);
console.log(`page coupling: engine executed, ${forced} recurrence predictions matched`);
