// verify-the-evenest-way.mjs
//
// Recomputes what /strata/the-evenest-way/ prints, twice: once with the page's own engine.js
// (floating point, the code the reader's browser runs) and once with exact integer arithmetic
// that never rounds, and requires the two to agree.
//
//   node research/the-evenest-way/verify-the-evenest-way.mjs
//   node research/the-evenest-way/verify-the-evenest-way.mjs --mutate
//
// --mutate plants a fault behind each class of assertion (a sort that mis-orders two marks, a
// gap tolerance that merges two lengths, a wrong fifth, a doctored figure in the prose, a
// broken evenness test) and requires the suite to go red on every one. An assertion that cannot
// fail is a sentence, not a check.
//
// Outside a checkout it needs two served files beside it at their repository paths,
// public/strata/the-evenest-way/engine.js and index.html; the page gives the three curl lines.
//
// HOW THE EXACT HALF WORKS. Every question the page asks of a chain of N marks at step x comes
// down to one kind of comparison: is c·x bigger or smaller than the whole number t? For the
// pure fifth x = log2(3/2), and c·x > t exactly when 3^c > 2^(c+t), which BigInt settles with
// no rounding at all. The meantone fifths are log2(5)/4 and log2(10/3)/3 and reduce the same
// way; the golden step (3 − √5)/2 reduces to comparing two squares of integers. From that one
// comparison: where each mark sits, which mark follows which, every arc as an exact pair
// (d, m) meaning d·x − m, and the continued fraction by walking the Stern–Brocot tree.
//
// WHAT THIS DOES NOT CHECK: the history. Who divided the octave into 17, 19, 31 or 53, and
// when, is checked against sources in research/the-evenest-way/SOURCES.md, by reading, not by
// this program. It checks arithmetic, and that the page says what the arithmetic says.

import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
// The page's own engine, imported by the path it has in the repository. A reader outside a
// checkout downloads it (and the page) to the same paths first: the recipe on the page and in
// /checks/manifest.json lists all three files.
import * as REAL from '../../public/strata/the-evenest-way/engine.js';

const HERE = dirname(fileURLToPath(import.meta.url));
const HTML_REAL = readFileSync(join(HERE, '../../public/strata/the-evenest-way/index.html'), 'utf8');

// ---------------------------------------------------------------------------------------------
// The exact oracle: sgn(c, t) = sign(c·x − t) for whole numbers c, t, with no rounding.

const B = (n) => BigInt(n);
const pow = (b, e) => B(b) ** B(e);

// x = log2(P/Q) / m.  c·x > t  <=>  (P/Q)^c > 2^(m·t)  (for c >= 0)
function logOracle(P, Q, m) {
  const s = (c, t) => {
    c = B(c); t = B(t);
    if (c < 0n) return -s(-c, -t);
    const L = P ** c, R = Q ** c;
    const e = B(m) * t;
    const lhs = e >= 0n ? L : L * 2n ** -e;
    const rhs = e >= 0n ? R * 2n ** e : R;
    return lhs > rhs ? 1 : lhs < rhs ? -1 : 0;
  };
  return s;
}
// x = (3 − √5)/2 = 2 − φ.  c·x − t = ((3c − 2t) − c√5)/2.
function goldenOracle() {
  const s = (c, t) => {
    c = B(c); t = B(t);
    if (c < 0n) return -s(-c, -t);
    const u = 3n * c - 2n * t;
    if (c === 0n) return u > 0n ? 1 : u < 0n ? -1 : 0;
    if (u <= 0n) return -1;
    const a = u * u, b = 5n * c * c;
    return a > b ? 1 : -1; // √5 is irrational, so never equal
  };
  return s;
}
// x = p/q exactly.
function ratOracle(p, q) {
  return (c, t) => { const v = B(c) * B(p) - B(t) * B(q); return v > 0n ? 1 : v < 0n ? -1 : 0; };
}

const EXACT = {
  pythagorean: { sgn: logOracle(3n, 2n, 1), irrational: true },
  quarter: { sgn: logOracle(5n, 1n, 4), irrational: true },
  third: { sgn: logOracle(10n, 3n, 3), irrational: true },
  equal: { sgn: ratOracle(7, 12), irrational: false, value: (d, m) => d * 7 - m * 12 },
  golden: { sgn: goldenOracle(), irrational: true },
};

function floorOf(sgn, k, approx) {
  let f = Math.floor(k * approx);
  while (sgn(k, f) < 0) f--;
  while (sgn(k, f + 1) >= 0) f++;
  return f;
}

// Exact chains for N = 1..Nmax, built by inserting one mark at a time. The float position only
// proposes where the new mark goes; the exact oracle must then confirm it sits strictly between
// its two neighbours, or the run stops and says so.
function exactChains(id, xf, Nmax) {
  const { sgn } = EXACT[id];
  const fl = [];
  const order = []; // mark indices in circular order, by exact position
  const less = (a, b) => sgn(a - b, fl[a] - fl[b]); // sign(frac(a x) − frac(b x))
  const out = [];
  let closedAt = null;
  for (let k = 0; k < Nmax; k++) {
    fl[k] = floorOf(sgn, k, xf);
    // binary search on the float, then confirm exactly
    const pos = k * xf - Math.floor(k * xf);
    let lo = 0, hi = order.length;
    while (lo < hi) { const mid = (lo + hi) >> 1; const p = order[mid] * xf - Math.floor(order[mid] * xf); if (p < pos) lo = mid + 1; else hi = mid; }
    for (const nb of [order[lo - 1], order[lo]]) {
      if (nb === undefined) continue;
      if (less(k, nb) === 0) { closedAt = k; break; }
    }
    if (closedAt !== null) break;
    if (lo > 0 && less(order[lo - 1], k) !== -1) throw new Error(`${id}: exact order disagrees at k=${k}`);
    if (lo < order.length && less(k, order[lo]) !== -1) throw new Error(`${id}: exact order disagrees at k=${k}`);
    order.splice(lo, 0, k);
    const N = k + 1;
    const gaps = [];
    for (let i = 0; i < order.length; i++) {
      const a = order[i], b = order[(i + 1) % order.length];
      let d = b - a, m = fl[b] - fl[a];
      if (i === order.length - 1) m -= 1; // wrapping past the start adds one whole turn
      gaps.push([d, m]);
    }
    if (N === 1) { out.push({ N, classes: 1, gaps }); continue; }
    // For an irrational x, d·x − m = d'·x − m' forces d = d' and m = m', so the pair names the
    // length. For a fraction it does not (7·7/12 − 4 and −5·7/12 + 3 are both 1/12), so a
    // rational step keys each arc by its exact value instead.
    const keys = new Map();
    const { value } = EXACT[id];
    for (const [d, m] of gaps) { const key = value ? String(value(d, m)) : `${d},${m}`; keys.set(key, (keys.get(key) || 0) + 1); }
    out.push({ N, classes: keys.size, keys, order: [...order] });
  }
  return { chains: out, closedAt, sgn };
}

// Continued fraction of x by walking the Stern–Brocot tree with the exact oracle.
// A term is known only once the walk turns, so it stops as soon as `need` terms are complete.
function exactContfrac(sgn, need) {
  let [a, b, c, d] = [0, 1, 1, 0];
  const runs = [];
  let dir = null, run = 0;
  for (let step = 0; step < 100000 && runsToCf(runs).length < need; step++) {
    const p = a + c, q = b + d;
    const s = sgn(q, p);
    if (s === 0) { if (dir !== null) runs.push({ dir, run }); return { terms: runsToCf(runs), exact: true }; }
    const nd = s > 0 ? 'R' : 'L';
    if (nd === dir) run++;
    else { if (dir !== null) runs.push({ dir, run }); dir = nd; run = 1; }
    if (s > 0) { a = p; b = q; } else { c = p; d = q; }
  }
  return { terms: runsToCf(runs) };
}
function runsToCf(runs) {
  const t = runs.map((r) => r.run);
  if (runs.length && runs[0].dir === 'L') t.unshift(0);
  return t;
}

// ---------------------------------------------------------------------------------------------

function run(E, HTML, quiet) {
  let pass = 0, fail = 0;
  const failures = [];
  const ok = (name, cond, detail = '') => {
    if (cond) pass++;
    else { fail++; failures.push(`${name}${detail ? ' :: ' + detail : ''}`); }
  };
  const P = Object.fromEntries(E.PRESETS.map((p) => [p.id, p]));
  const NMAX = 400;

  // 1. The generators are the numbers the page says they are.
  ok('pure fifth is 1200·log2(3/2) cents', Math.abs(P.pythagorean.cents - 701.955000865) < 1e-6, P.pythagorean.cents);
  ok('quarter-comma fifth: four of them are two octaves and a 5:4', Math.abs(4 * P.quarter.cents - 2400 - 1200 * Math.log2(5 / 4)) < 1e-9);
  ok('third-comma fifth: two octaves less three of them is a 6:5', Math.abs(2400 - 3 * P.third.cents - 1200 * Math.log2(6 / 5)) < 1e-9);
  ok('the equal fifth is 700 cents', P.equal.cents === 700);
  ok('golden step is 360°·(2 − φ) = 137.5077…°', Math.abs(P.golden.cents / 1200 * 360 - 137.50776405) < 1e-7, P.golden.cents / 1200 * 360);

  // 2. Float engine against exact arithmetic, every N up to 400 (or until the chain closes).
  const exact = {};
  for (const id of Object.keys(EXACT)) {
    const xf = P[id].cents / 1200;
    let ex;
    try { ex = exactChains(id, xf, NMAX); } catch (e) { ok(`${id}: exact insertion agrees with float order`, false, e.message); continue; }
    exact[id] = ex;
    let agree = true, where = '';
    for (const c of ex.chains) {
      const f = E.chain(xf, c.N);
      if (f.classes.length !== c.classes || f.closedAt !== null) { agree = false; where = `N=${c.N}: float ${f.classes.length} classes, exact ${c.classes}`; break; }
    }
    ok(`${id}: float engine and exact arithmetic give the same number of arc lengths for every N`, agree, where);
    const floatTwo = E.twoGapMoments(xf, NMAX);
    const exactTwo = ex.chains.filter((c) => c.classes === 2).map((c) => c.N);
    ok(`${id}: two-length moments agree (float vs exact)`, JSON.stringify(floatTwo) === JSON.stringify(exactTwo), `${floatTwo} vs ${exactTwo}`);
    exact[id].two = exactTwo;
    // never a fourth length, and when there are three the longest is the sum of the other two
    let three = true, sum = true, bad = '';
    for (const c of ex.chains) {
      if (c.classes > 3) { three = false; bad = `N=${c.N}`; }
      if (c.classes === 3) {
        if (EXACT[id].value) {
          const v = [...c.keys.keys()].map(Number).sort((a, b) => b - a);
          if (v[0] !== v[1] + v[2]) { sum = false; bad = `N=${c.N}`; }
        } else {
          const ks = [...c.keys.keys()].map((k) => k.split(',').map(Number));
          ks.sort((u, v) => -ex.sgn(u[0] - v[0], u[1] - v[1])); // longest first, compared exactly
          if (!(ks[0][0] === ks[1][0] + ks[2][0] && ks[0][1] === ks[1][1] + ks[2][1])) { sum = false; bad = `N=${c.N}`; }
        }
      }
    }
    ok(`${id}: never a fourth arc length, N ≤ ${NMAX} (exact)`, three, bad);
    ok(`${id}: with three lengths the longest is exactly the sum of the other two (exact)`, sum, bad);
  }
  let mx = 0;
  for (let N = 1; N <= 3000; N++) mx = Math.max(mx, E.chain(P.pythagorean.cents / 1200, N).classes.length);
  ok('pure fifth, float: never a fourth arc length up to 3,000 marks', mx === 3);

  const TWO = {
    pythagorean: [2, 3, 5, 7, 12, 17, 29, 41, 53, 94, 147, 200, 253, 306, 359],
    quarter: [2, 3, 5, 7, 12, 19, 31, 50, 81, 112, 143, 174, 205, 379],
    golden: [2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377],
  };
  for (const [id, want] of Object.entries(TWO)) {
    ok(`${id}: the two-length moments up to ${NMAX} are ${want.join(', ')}`, exact[id] && JSON.stringify(exact[id].two) === JSON.stringify(want), exact[id] && exact[id].two.join(','));
  }
  ok('third-comma: 19 and 31 are two-length moments and 17, 41, 53 are not', exact.third && [19, 31].every((n) => exact.third.two.includes(n)) && ![17, 41, 53].some((n) => exact.third.two.includes(n)));
  ok('equal fifth: the chain closes on its 13th mark (the 13th fifth lands on the first)', exact.equal && exact.equal.closedAt === 12, exact.equal && exact.equal.closedAt);
  ok('equal fifth: two step sizes at 2, 3, 5, 7, 8, 9, 10, 11 marks', exact.equal && JSON.stringify(exact.equal.two) === '[2,3,5,7,8,9,10,11]');

  // 3. Continued fractions, exactly, and the theorem the page leans on: the two-length moments
  //    are precisely the denominators of the best fractions (convergents and intermediates).
  const CF = {
    pythagorean: [0, 1, 1, 2, 2, 3, 1, 5, 2, 23],
    quarter: [0, 1, 1, 2, 1, 1, 1, 1, 5, 1, 3],
    golden: [0, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  };
  for (const [id, want] of Object.entries(CF)) {
    const got = exactContfrac(EXACT[id].sgn, want.length).terms.slice(0, want.length);
    ok(`${id}: continued fraction begins [${want[0]}; ${want.slice(1).join(', ')}] (exact)`, JSON.stringify(got) === JSON.stringify(want), got.join(','));
    const fl = E.contfrac(P[id].cents / 1200, want.length);
    ok(`${id}: the page's float continued fraction matches for ${want.length} terms`, JSON.stringify(fl) === JSON.stringify(want), fl.join(','));
    const { conv, semi } = E.fractions(want);
    const dens = [...new Set([...conv, ...semi].map((f) => f.q))].filter((q) => q >= 2 && q <= NMAX).sort((a, b) => a - b);
    ok(`${id}: two-length moments = denominators of convergents and intermediate fractions, N ≤ ${NMAX}`, exact[id] && JSON.stringify(dens) === JSON.stringify(exact[id].two), `${dens} vs ${exact[id] && exact[id].two}`);
  }
  const conv5 = E.fractions(CF.pythagorean).conv.map((f) => `${f.p}/${f.q}`);
  ok('pure fifth convergents include 7/12, 24/41, 31/53 and 179/306', ['7/12', '24/41', '31/53', '179/306'].every((s) => conv5.includes(s)), conv5.join(' '));

  // 4. The step sizes at each moment, in cents.
  const steps = (id, N) => E.chain(P[id].cents / 1200, N).classes.map((c) => [+(c.len * 1200).toFixed(3), c.count]);
  const STEP = [
    ['pythagorean', 5, [[294.135, 2], [203.91, 3]]],
    ['pythagorean', 7, [[203.91, 5], [90.225, 2]]],
    ['pythagorean', 12, [[113.685, 5], [90.225, 7]]],
    ['pythagorean', 17, [[90.225, 12], [23.46, 5]]],
    ['pythagorean', 53, [[23.46, 41], [19.845, 12]]],
    ['quarter', 19, [[76.049, 12], [41.059, 7]]],
    ['quarter', 31, [[41.059, 19], [34.99, 12]]],
  ];
  for (const [id, N, want] of STEP) {
    const got = steps(id, N);
    ok(`${id} ×${N}: steps ${want.map(([c, n]) => `${c}¢×${n}`).join(' + ')}`, JSON.stringify(got) === JSON.stringify(want), JSON.stringify(got));
  }
  ok('the 7-note steps are the ratios 9:8 and 256:243', Math.abs(1200 * Math.log2(9 / 8) - 203.91) < 1e-3 && Math.abs(1200 * Math.log2(256 / 243) - 90.225) < 1e-3);
  ok('the 17-note small step is the Pythagorean comma, 3^12/2^19', Math.abs(1200 * Math.log2(3 ** 12 / 2 ** 19) - 23.46) < 1e-3);
  const merc = 53 * P.pythagorean.cents - 31 * 1200;
  ok('53 pure fifths overshoot 31 octaves by 3.615 cents', Math.abs(merc - 3.615) < 5e-4, merc);
  ok('54 marks: a third length appears, and it is that 3.615-cent gap', (() => { const c = E.chain(P.pythagorean.cents / 1200, 54); return c.classes.length === 3 && Math.abs(c.classes[2].len * 1200 - merc) < 1e-6; })());
  const ratio = (id, N) => { const c = E.chain(P[id].cents / 1200, N).classes; return c.length > 1 ? c[0].len / c[1].len : NaN; };
  const RATIOS = { 2: 1.409, 3: 2.442, 5: 1.442, 7: 2.26, 12: 1.26, 17: 3.846, 29: 2.846, 41: 1.846, 53: 1.182 };
  for (const [N, r] of Object.entries(RATIOS)) ok(`pure fifth ×${N}: long step / short step = ${r}`, +ratio('pythagorean', +N).toFixed(3) === r, ratio('pythagorean', +N));
  const nearest = Object.entries(RATIOS).sort((a, b) => a[1] - b[1]).slice(0, 2).map((e) => +e[0]).sort((a, b) => a - b);
  ok('of the moments up to 53, the two whose steps are nearest equal are 12 and 53', JSON.stringify(nearest) === '[12,53]', nearest);

  // 5. On the twelve-step grid: which chains of equal fifths are the evenest way to choose.
  const ME = [];
  for (let k = 1; k <= 12; k++) if (E.maximallyEven(Array.from({ length: k }, (_, i) => 7 * i), 12)) ME.push(k);
  ok('chains of equal fifths that are maximally even in 12: 1, 5, 7, 11, 12', JSON.stringify(ME) === '[1,5,7,11,12]', ME);
  ok('evenness test rejects a lopsided set ({0,1,2,3,4,5,6} is not maximally even)', !E.maximallyEven([0, 1, 2, 3, 4, 5, 6], 12));
  ok('evenness test accepts every E(k,12)', Array.from({ length: 12 }, (_, i) => i + 1).every((k) => E.maximallyEven(E.euclid(k, 12), 12)));
  const white = Array.from({ length: 7 }, (_, i) => (5 + 7 * i) % 12).sort((a, b) => a - b);
  ok('seven fifths from F are the white keys {0,2,4,5,7,9,11}', JSON.stringify(white) === '[0,2,4,5,7,9,11]', white);
  ok('the white keys and the rhythm E(7,12) are one necklace', E.sameNecklace(white, E.euclid(7, 12), 12) !== null);
  ok('five fifths are the black keys, and E(5,12) is the same necklace', E.sameNecklace(Array.from({ length: 5 }, (_, i) => (6 + 7 * i) % 12), E.euclid(5, 12), 12) !== null);
  // every generated set of k in 12 by fifths that has two step sizes, and whether each is even
  const eqTwoNotEven = exact.equal ? exact.equal.two.filter((k) => !ME.includes(k)) : null;
  ok('two step sizes is not the same as evenest: 2, 3, 8, 9, 10 fifths have two sizes and are not maximally even', JSON.stringify(eqTwoNotEven) === '[2,3,8,9,10]', eqTwoNotEven);

  // 6. The flower: nearest neighbours around the 2,000th seed.
  const FL = { pythagorean: 53, quarter: 31, third: 19, equal: 12 };
  for (const [id, want] of Object.entries(FL)) {
    const t = E.neighbourTally(P[id].cents / 1200, 2000, 2400);
    ok(`${id} flower: every seed from 2,000 to 2,399 has its nearest neighbour ${want} seeds away`, t.length === 1 && t[0][0] === want && t[0][1] === 400, JSON.stringify(t));
  }
  const gt = E.neighbourTally(P.golden.cents / 1200, 2000, 2400);
  ok('golden flower: nearest neighbours 89 or 144 seeds away, both Fibonacci', gt.length === 2 && gt.map((x) => x[0]).sort((a, b) => a - b).join() === '89,144', JSON.stringify(gt));
  ok('golden flower: 268 of 400 seeds at 89, 132 at 144', gt[0][0] === 89 && gt[0][1] === 268 && gt[1][1] === 132, JSON.stringify(gt));

  // 7a. Claims the prose makes in words.
  ok('pure fifth, 8 marks: a third length appears', E.chain(P.pythagorean.cents / 1200, 8).classes.length === 3);
  const between = [];
  for (let n = 2; n <= 53; n++) if (!TWO.pythagorean.includes(n) && E.chain(P.pythagorean.cents / 1200, n).classes.length !== 3) between.push(n);
  ok('pure fifth: every count from 2 to 53 that is not a two-length moment has exactly three', between.length === 0, between);
  let outside = 0;
  for (let i = 1; i < 4000; i++) {
    const c = 1200 * 4 / 7 + (720 - 1200 * 4 / 7) * i / 4000;
    const m = E.twoGapMoments(c / 1200, 12);
    if (!(m.includes(5) && m.includes(7) && m.includes(12))) outside++;
  }
  ok('every fifth strictly between 685.714 and 720 cents (3,999 sampled) has two lengths at 5, 7 and 12', outside === 0, outside);
  ok('the window ends are 4/7 and 3/5 of an octave', (1200 * 4 / 7).toFixed(3) === '685.714' && 1200 * 3 / 5 === 720);
  ok('685 cents: 12 is not a two-length count', !E.twoGapMoments(685 / 1200, 12).includes(12));
  ok('721 cents: 7 is not a two-length count', !E.twoGapMoments(721 / 1200, 12).includes(7));
  const black = Array.from({ length: 5 }, (_, i) => (6 + 7 * i) % 12).sort((a, b) => a - b);
  ok('five fifths from F♯ are the black keys {1,3,6,8,10}', JSON.stringify(black) === '[1,3,6,8,10]', black);
  const nearestEqual = (id) => {
    const g = P[id].cents / 1200;
    let best = null;
    for (const n of E.twoGapMoments(g, NMAX)) { const c = E.chain(g, n).classes; const r = c.length > 1 ? c[0].len / c[1].len : Infinity; if (!best || r < best[1]) best = [n, r]; }
    return best;
  };
  const q = nearestEqual('quarter'), t = nearestEqual('third'), py = nearestEqual('pythagorean');
  ok('quarter-comma: of its two-length counts up to 400, the steps are nearest equal at 31 (1.173)', q[0] === 31 && q[1].toFixed(3) === '1.173', q);
  ok('third-comma: nearest equal at 19 (1.015)', t[0] === 19 && t[1].toFixed(3) === '1.015', t);
  ok('pure fifth: of all its two-length counts up to 400, 53 is the nearest equal', py[0] === 53, py);
  const PAGEWIN = { pythagorean: 53, quarter: 31, third: 19, equal: 12, golden: 89 };
  for (const [id, want] of Object.entries(PAGEWIN)) {
    const tl = E.neighbourTally(P[id].cents / 1200, 1100, 1300);
    ok(`${id} flower, the page's own window (seeds 1,100 to 1,299): all 200 nearest neighbours ${want} away`, tl.length === 1 && tl[0][0] === want && tl[0][1] === 200, JSON.stringify(tl));
  }
  // The historical numbers the page quotes, checked as arithmetic (their provenance is in SOURCES.md).
  const gz = [81, 108, 72, 96, 64];
  ok('Guanzi: 81, 108, 72, 96, 64 alternate a third more and a third less', gz.every((v, i) => i === 0 || v * 3 === gz[i - 1] * (i % 2 ? 4 : 2)));
  const gzCents = gz.map((v) => ((1200 * Math.log2(81 / v)) % 1200 + 1200) % 1200).sort((a, b) => a - b);
  const gzSteps = gzCents.map((c, i) => ((gzCents[(i + 1) % 5] - c + 1200) % 1200).toFixed(3)).sort();
  ok('Guanzi: the five tones fold into one octave with steps 203.910 ×3 and 294.135 ×2', gzSteps.join() === '203.910,203.910,203.910,294.135,294.135', gzSteps);
  const URM = [[1, 1], [256, 243], [65536, 59049], [9, 8], [32, 27], [8192, 6561], [81, 64], [4, 3], [1024, 729], [262144, 177147], [3, 2], [128, 81], [32768, 19683], [27, 16], [16, 9], [4096, 2187], [1048576, 531441], [2, 1]].map(([a, b]) => [B(a), B(b)]);
  let urmOk = true, L = 0, C = 0;
  for (let i = 1; i < URM.length; i++) {
    const [a, b] = URM[i - 1], [c, d] = URM[i];
    const num = c * b, den = d * a; // step ratio = (c/d)/(a/b)
    if (num * 243n === den * 256n) L++;
    else if (num * 524288n === den * 531441n) C++;
    else urmOk = false;
  }
  ok('al-Urmawi: his 17 steps are exactly 12 limmas (256:243) and 5 commas (3^12:2^19)', urmOk && L === 12 && C === 5, `${L} L, ${C} C`);
  const threeExp = URM.slice(0, 17).map(([a, b]) => { let e = 0; for (let x = a; x % 3n === 0n; x /= 3n) e++; for (let x = b; x % 3n === 0n; x /= 3n) e--; return e; }).sort((x, y) => x - y);
  ok('al-Urmawi: his 17 notes are one unbroken chain of fifths (powers of 3 from −12 to +4)', threeExp.every((e, i) => e === -12 + i), threeExp);
  ok('Jing Fang: the first pitch 177,147 is 3^11', 177147 === 3 ** 11);
  const jf = 1200 * Math.log2(177147 / 176776);
  ok('Jing Fang: 176,776 against 177,147 is 3.63 cents', jf.toFixed(2) === '3.63', jf);
  const d19 = P.third.cents - 1200 * 11 / 19, d31 = 1200 * 18 / 31 - P.quarter.cents;
  ok('third-comma fifth is within 0.049 cents of the 19-step fifth', d19.toFixed(3) === '0.049', d19);
  ok('quarter-comma fifth is 0.196 cents from the 31-step fifth', d31.toFixed(3) === '0.196', d31);

  // The table on the page, row by row.
  const rows = [...HTML.matchAll(/<tr data-n="(\d+)" data-long="([\d.]+)" data-nlong="(\d+)" data-short="([\d.]+)" data-nshort="(\d+)" data-ratio="([\d.]+)"><td>(\d+)<\/td><td class="num">([\d.]+) × (\d+)<\/td><td class="num">([\d.]+) × (\d+)<\/td><td>([\d.]+)<\/td>/g)];
  ok('the page\'s table has a row for each two-length count up to 53', rows.map((r) => +r[1]).join() === TWO.pythagorean.slice(0, 9).join(), rows.map((r) => r[1]).join());
  for (const r of rows) {
    const n = +r[1];
    const c = E.chain(P.pythagorean.cents / 1200, n).classes;
    if (c.length < 2) { ok(`table row ${n}: the chain has two lengths`, false); continue; }
    const want = [n, (c[0].len * 1200).toFixed(3), c[0].count, (c[1].len * 1200).toFixed(3), c[1].count, (c[0].len / c[1].len).toFixed(3)].join('|');
    const attr = [r[1], r[2], r[3], r[4], r[5], r[6]].join('|');
    const shown = [r[7], r[8], r[9], r[10], r[11], r[12]].join('|');
    ok(`table row ${n}: data and visible cells both match the chain`, attr === want && shown === want, `${attr} / ${shown} / want ${want}`);
  }

  // 7. The page says what the arithmetic says. Each figure below is looked for, verbatim, in the
  //    page, and each was computed above or is computed here.
  const text = HTML.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ').replace(/<[^>]+>/g, ' ').replace(/&nbsp;|&#8202;|&thinsp;/g, ' ').replace(/\s+/g, ' ');
  const FIG = [
    ['701.955', P.pythagorean.cents.toFixed(3)],
    ['696.578', P.quarter.cents.toFixed(3)],
    ['694.786', P.third.cents.toFixed(3)],
    ['137.508°', (P.golden.cents / 1200 * 360).toFixed(3) + '°'],
    ['2, 3, 5, 7, 12, 17, 29, 41, 53', TWO.pythagorean.slice(0, 9).join(', ')],
    ['5, 7, 12, 19, 31', [5, 7, 12, 19, 31].filter((n) => exact.quarter && exact.quarter.two.includes(n)).join(', ')],
    ['2, 3, 5, 8, 13, 21, 34, 55, 89', exact.golden ? exact.golden.two.slice(0, 9).join(', ') : ''],
    ['203.910', (1200 * Math.log2(9 / 8)).toFixed(3)],
    ['90.225', (1200 * Math.log2(256 / 243)).toFixed(3)],
    ['113.685', (steps('pythagorean', 12)[0] || [NaN])[0].toFixed(3)],
    ['23.460', (steps('pythagorean', 17)[1] || [NaN])[0].toFixed(3)],
    ['19.845', (steps('pythagorean', 53)[1] || [NaN])[0].toFixed(3)],
    ['3.615', merc.toFixed(3)],
    ['1.260', ratio('pythagorean', 12).toFixed(3)],
    ['1.182', ratio('pythagorean', 53).toFixed(3)],
    ['2.260', ratio('pythagorean', 7).toFixed(3)],
    ['3.846', ratio('pythagorean', 17).toFixed(3)],
    ['[0; 1, 1, 2, 2, 3, 1, 5, 2, 23', '[0; ' + CF.pythagorean.slice(1).join(', ')],
    ['1.173', q[1].toFixed(3)],
    ['1.015', t[1].toFixed(3)],
    ['685.714', (1200 * 4 / 7).toFixed(3)],
    ['3.63', jf.toFixed(2)],
    ['0.049', d19.toFixed(3)],
    ['0.196', d31.toFixed(3)],
    ['(2, 5, 12, 41, 53, 306)', '(' + E.fractions(CF.pythagorean).conv.map((f) => f.q).filter((x) => x >= 2 && x <= NMAX).join(', ') + ')'],
    ['1/2, 3/5, 7/12, 24/41, 31/53, 179/306', E.fractions(CF.pythagorean).conv.slice(2, 8).map((f) => `${f.p}/${f.q}`).join(', ')],
    ['(3, 7, 17, 29, 94, 147, 200, 253, 359)', '(' + E.fractions(CF.pythagorean).semi.map((f) => f.q).filter((x) => x >= 2 && x <= NMAX).sort((a, b) => a - b).join(', ') + ')'],
  ];
  for (const [shown, computed] of FIG) {
    ok(`page prints ${shown} and the arithmetic gives ${computed}`, shown === computed && text.includes(shown), `page has it: ${text.includes(shown)}`);
  }

  if (!quiet) {
    for (const f of failures) console.log('  ✗ ' + f);
    console.log(`${pass} passed, ${fail} failed`);
  }
  return { pass, fail, failures };
}

// ---------------------------------------------------------------------------------------------

const result = run(REAL, HTML_REAL, false);

if (process.argv.includes('--mutate')) {
  const mutants = [
    ['a gap tolerance wide enough to merge two lengths', () => {
      const E = { ...REAL };
      E.chain = (g, N) => { const c = REAL.chain(g, N); const m = []; for (const k of c.classes) { const f = m.find((x) => Math.abs(x.len - k.len) < 0.004); if (f) f.count += k.count; else m.push({ ...k }); } return { ...c, classes: m }; };
      E.twoGapMoments = (g, Nmax) => { const o = []; for (let N = 2; N <= Nmax; N++) { const c = E.chain(g, N); if (c.closedAt !== null) break; if (c.classes.length === 2) o.push(N); } return o; };
      return [E, HTML_REAL];
    }],
    ['the fifth off by a hundredth of a cent', () => {
      const E = { ...REAL, PRESETS: REAL.PRESETS.map((p) => p.id === 'pythagorean' ? { ...p, cents: p.cents + 0.01 } : p) };
      return [E, HTML_REAL];
    }],
    ['a sort that forgets the wrap-around arc', () => {
      const E = { ...REAL };
      E.chain = (g, N) => { const c = REAL.chain(g, N); const gaps = c.gaps.slice(0, -1); const classes = []; for (const gp of gaps) { let k = classes.find((x) => Math.abs(x.len - gp.len) < 1e-7); if (!k) { k = { len: gp.len, count: 0, ds: new Set() }; classes.push(k); } k.count++; } classes.sort((a, b) => b.len - a.len); return { ...c, gaps, classes }; };
      E.twoGapMoments = (g, Nmax) => { const o = []; for (let N = 2; N <= Nmax; N++) { const c = E.chain(g, N); if (c.closedAt !== null) break; if (c.classes.length === 2) o.push(N); } return o; };
      return [E, HTML_REAL];
    }],
    ['an evenness test that only checks adjacent steps', () => {
      const E = { ...REAL };
      E.maximallyEven = (set, q) => { const s = [...new Set(set.map((x) => ((x % q) + q) % q))].sort((a, b) => a - b); const st = s.map((x, i) => (s[(i + 1) % s.length] - x + q) % q); return Math.max(...st) - Math.min(...st) <= 1; };
      return [E, HTML_REAL];
    }],
    ['a figure changed in the prose (3.615 printed as 3.616)', () => [REAL, HTML_REAL.split('3.615').join('3.616')]],
    ['a moment dropped from the prose list (17 removed)', () => [REAL, HTML_REAL.split('2, 3, 5, 7, 12, 17, 29, 41, 53').join('2, 3, 5, 7, 12, 29, 41, 53')]],
  ];
  let caught = 0;
  for (const [name, make] of mutants) {
    const [E, H] = make();
    let r;
    try { r = run(E, H, true); } catch (e) { caught++; console.log(`  mutant: ${name} -> RED (the suite threw: ${e.message})`); continue; }
    const red = r.fail > result.fail;
    if (red) caught++;
    console.log(`  mutant: ${name} -> ${red ? `RED (${r.fail - result.fail} new failures, e.g. ${r.failures.find((f) => !result.failures.includes(f))})` : 'still green: THIS CHECK CANNOT FAIL'}`);
  }
  console.log(`${caught} of ${mutants.length} planted faults caught`);
  if (caught !== mutants.length) process.exit(1);
}

process.exit(result.fail ? 1 : 0);
