// verify-more-data-wrong-tree.mjs
// Recomputes, offline and from scratch, every number shown on
// /strata/more-data-wrong-tree/ ("More Data, More Certain, Still Wrong").
//
// The claim under test is Felsenstein's (1978): maximum parsimony is
// STATISTICALLY INCONSISTENT. There is a region of branch-length space (two
// long external branches separated by a short internal branch) in which the
// probability that parsimony recovers the true four-taxon topology goes to
// ZERO as the amount of data goes to infinity. More sequence, more confidence,
// wrong tree.
//
// The page's second layer answers the standard dismissal ("use maximum
// likelihood, it's consistent") by breaking it: when the generating process is
// heterotachous and the inference model is not, likelihood fails too. It then
// stages the live 2004-2005 exchange (Kolaczkowski & Thornton vs their critics)
// as a dial rather than a verdict.
//
//   run:  node research/more-data-wrong-tree/verify-more-data-wrong-tree.mjs
//
// No npm dependencies. core.mjs is the same engine the page runs inline.

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import * as C from './core.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '..', '..', 'public', 'strata', 'more-data-wrong-tree', 'index.html');

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;
const eqArr = (a, b, eps) => a.length === b.length && a.every((v, i) => Math.abs(v - b[i]) <= eps);
const f4 = (x) => x.toFixed(4);

// ── the page's pinned defaults (these must match the HTML, checked below) ────
const DEF = {
  long: 0.45, short: 0.05, internal: 0.05,   // layer 1, inside the zone
  safeLong: 0.25,                             // layer 1, outside the zone
  NS: [50, 100, 200, 500, 1000, 2000, 5000, 10000],
  SEED1: 20260720, REPS1: 120,
  // layer 2, the heterotachy bench
  hLong: 0.75, hShort: 0.10, hInternal: 0.20,
  N2: 1000, SEED2: 7314159, REPS2: 60,
  ML_SWEEPS: 3, ML_GITERS: 14, MIX_SWEEPS: 3, MIX_GITERS: 12,
};

// ═══ 1. Jukes-Cantor is a proper substitution model ═════════════════════════
console.log('\n· Jukes-Cantor transition probabilities ·');
{
  ok('t=0: no change with probability 1', approx(C.jcSame(0), 1, 1e-12) && approx(C.jcDiff(0), 0, 1e-12));
  ok('rows sum to 1 at every branch length',
    [0.01, 0.05, 0.2, 0.45, 0.75, 3].every((t) => approx(C.jcSame(t) + 3 * C.jcDiff(t), 1, 1e-12)));
  ok('t→∞: every base equally likely (1/4)', approx(C.jcSame(50), 0.25, 1e-9) && approx(C.jcDiff(50), 0.25, 1e-9));
  // expected substitutions per site equals the branch length, by construction:
  // P(different) = 3/4(1 - e^(-4t/3)) is the standard JC p-distance
  ok('p-distance formula: P(differ) = 3/4·(1 − e^(−4t/3))',
    [0.1, 0.45, 1.2].every((t) => approx(3 * C.jcDiff(t), 0.75 * (1 - Math.exp(-4 * t / 3)), 1e-12)));
}

// ═══ 2. Exact site-pattern distribution on the true tree ════════════════════
console.log('\n· exact site-pattern probabilities (256 patterns, summed over both internal states) ·');
{
  for (const r of [C.zoneRegime(0.45, 0.05, 0.05), C.zoneRegime(0.25, 0.05, 0.05),
                   C.swapRegime(0.75, 0.10, 0.20)]) {
    const P = C.patternProbs(r);
    const s = P.reduce((a, b) => a + b, 0);
    ok(`pattern distribution sums to 1 (long=${r.a === r.c ? r.a : r.b})`, approx(s, 1, 1e-12), `Σ=${s.toFixed(12)}`);
  }
  // zero internal branch AND equal external branches: a perfectly symmetric star,
  // which carries no topological signal at all. All three masses must coincide.
  const star = C.informativeMass(C.patternProbs({ a: 0.4, b: 0.4, c: 0.4, d: 0.4, e: 0 }));
  ok('symmetric star tree (internal = 0, all externals equal): the three masses coincide',
    approx(star[0], star[1], 1e-14) && approx(star[1], star[2], 1e-14), `${star.map((x) => x.toFixed(10)).join(' ')}`);
  // with UNEQUAL externals a zero internal branch still favours a topology: pairing
  // the two long branches. That is long-branch attraction with the signal removed
  // entirely, which is the cleanest statement of what the artefact is.
  const starLBA = C.informativeMass(C.patternProbs(C.zoneRegime(0.45, 0.05, 0)));
  ok('zero internal branch, unequal externals: AC|BD still wins outright (pure artefact, zero signal)',
    C.argmaxUnique(starLBA) === 1, `${starLBA.map((x) => x.toFixed(6)).join(' / ')}`);
  // equal external branches ⇒ AC|BD and AD|BC masses are equal by symmetry
  const sym = C.informativeMass(C.patternProbs({ a: 0.3, b: 0.3, c: 0.3, d: 0.3, e: 0.05 }));
  ok('equal external branches ⇒ the two wrong topologies are symmetric',
    approx(sym[1], sym[2], 1e-12) && sym[0] > sym[1], `AB=${sym[0].toFixed(6)} AC=AD=${sym[1].toFixed(6)}`);
}

// ═══ 3. Fitch parsimony, and why only "two-and-two" sites decide ════════════
console.log('\n· Fitch parsimony on the three unrooted four-taxon topologies ·');
{
  const sc = (p, t) => C.fitchSite(p, t);
  ok('constant site AAAA costs 0 on every topology', [0, 1, 2].every((t) => sc([0, 0, 0, 0], t) === 0));
  ok('singleton site AAAG costs 1 on every topology (uninformative)',
    [0, 1, 2].every((t) => sc([0, 0, 0, 2], t) === 1));
  ok('site AABB costs 1 on AB|CD but 2 on the other two',
    sc([0, 0, 1, 1], 0) === 1 && sc([0, 0, 1, 1], 1) === 2 && sc([0, 0, 1, 1], 2) === 2);
  ok('site ABAB costs 1 on AC|BD but 2 on the other two',
    sc([0, 1, 0, 1], 1) === 1 && sc([0, 1, 0, 1], 0) === 2 && sc([0, 1, 0, 1], 2) === 2);
  // The decisive structural fact: across ALL 256 patterns, the score VECTOR is
  // flat except on the three "two-and-two" classes. So the parsimony winner is
  // decided entirely by which of the three informative counts is largest.
  let flat = 0, informative = 0, bad = 0;
  for (let k = 0; k < 256; k++) {
    const p = [(k >> 6) & 3, (k >> 4) & 3, (k >> 2) & 3, k & 3];
    const v = [sc(p, 0), sc(p, 1), sc(p, 2)];
    const isTwoTwo = (p[0] === p[1] && p[2] === p[3] && p[0] !== p[2]) ||
                     (p[0] === p[2] && p[1] === p[3] && p[0] !== p[1]) ||
                     (p[0] === p[3] && p[1] === p[2] && p[0] !== p[1]);
    if (v[0] === v[1] && v[1] === v[2]) { flat++; if (isTwoTwo) bad++; }
    else { informative++; if (!isTwoTwo) bad++; }
  }
  ok('exactly the 36 two-and-two patterns separate the topologies; the other 220 are flat',
    flat === 220 && informative === 36 && bad === 0, `flat=${flat} informative=${informative}`);
}

// ═══ 4. The Felsenstein zone, located exactly ═══════════════════════════════
console.log('\n· the zone boundary, by bisection on the exact pattern masses ·');
{
  const boundary = (short, internal) => {
    let lo = 0.001, hi = 6;
    for (let i = 0; i < 200; i++) {
      const m = (lo + hi) / 2;
      const f = C.informativeMass(C.patternProbs(C.zoneRegime(m, short, internal)));
      if (f[1] > f[0]) hi = m; else lo = m;
    }
    return (lo + hi) / 2;
  };
  const Lstar = boundary(DEF.short, DEF.internal);
  ok('boundary long-branch length L* = 0.394048 (short = internal = 0.05)',
    approx(Lstar, 0.394048, 5e-6), `L*=${Lstar.toFixed(6)}`);
  const below = C.informativeMass(C.patternProbs(C.zoneRegime(Lstar - 0.02, DEF.short, DEF.internal)));
  const above = C.informativeMass(C.patternProbs(C.zoneRegime(Lstar + 0.02, DEF.short, DEF.internal)));
  ok('just below L*: the true topology has the most informative mass', below[0] > below[1]);
  ok('just above L*: the WRONG topology AC|BD does', above[1] > above[0]);
  // a longer internal branch pushes the boundary out · the zone shrinks
  ok('a longer internal branch enlarges the safe region (L* grows)',
    boundary(0.05, 0.20) > boundary(0.05, 0.05), `${boundary(0.05, 0.20).toFixed(4)} > ${boundary(0.05, 0.05).toFixed(4)}`);
  ok('longer short-branches also enlarge the safe region',
    boundary(0.20, 0.05) > boundary(0.05, 0.05), `${boundary(0.20, 0.05).toFixed(4)} > ${boundary(0.05, 0.05).toFixed(4)}`);
}

console.log('\n· the page defaults: infinite-data verdict, computed exactly ·');
const ZONE = C.zoneRegime(DEF.long, DEF.short, DEF.internal);
const SAFE = C.zoneRegime(DEF.safeLong, DEF.short, DEF.internal);
{
  const fz = C.informativeMass(C.patternProbs(ZONE));
  ok('zone default (long 0.45): informative masses 0.025953 / 0.033391 / 0.007161',
    eqArr([...fz], [0.025953, 0.033391, 0.007161], 5e-7), fz.map((x) => x.toFixed(6)).join(' / '));
  ok('zone default: parsimony converges on AC|BD · the tree that never existed',
    C.argmaxUnique(fz) === 1, `wrong mass exceeds true by ${(100 * (fz[1] / fz[0] - 1)).toFixed(1)}%`);
  const Ez = C.expectedParsimony(C.patternProbs(ZONE));
  ok('zone default: expected tree length per site 0.789916 / 0.782479 / 0.808708',
    eqArr([...Ez], [0.789916, 0.782479, 0.808708], 5e-7), Ez.map((x) => x.toFixed(6)).join(' / '));
  ok('the wrong topology is genuinely SHORTER in expectation (parsimony is not confused, it is misled)',
    Ez[1] < Ez[0] && Ez[1] < Ez[2]);
  // the expected-length gap and the informative-mass gap are the same quantity
  ok('E[length AB|CD] − E[length AC|BD] equals f(AC|BD) − f(AB|CD) exactly',
    approx(Ez[0] - Ez[1], fz[1] - fz[0], 1e-12), `${(Ez[0] - Ez[1]).toExponential(6)}`);

  const fs = C.informativeMass(C.patternProbs(SAFE));
  ok('safe default (long 0.25): informative masses 0.032220 / 0.013552 / 0.005142',
    eqArr([...fs], [0.032220, 0.013552, 0.005142], 5e-7), fs.map((x) => x.toFixed(6)).join(' / '));
  ok('safe default: parsimony converges on the TRUE topology', C.argmaxUnique(fs) === 0);
  // the page uses the 576-multiplication shortcut on every slider drag; it must
  // give the same answer as the full 256-pattern sum
  let worst = 0;
  for (const r of [ZONE, SAFE, C.zoneRegime(1.1, 0.3, 0.4), C.swapRegime(0.75, 0.1, 0.2)]) {
    const a = C.informativeFast(r), b = C.informativeMass(C.patternProbs(r));
    for (let i = 0; i < 3; i++) worst = Math.max(worst, Math.abs(a[i] - b[i]));
  }
  ok('the fast informative-mass shortcut equals the full 256-pattern sum',
    worst < 1e-15, `max absolute difference ${worst.toExponential(2)}`);
}

// ═══ 5. Simulation reproduces the exact distribution ════════════════════════
console.log('\n· the seeded simulator agrees with the exact pattern distribution ·');
{
  const n = 400000;
  const rnd = C.mulberry32(31337);
  const seq = C.simulate(n, [ZONE], [1], rnd);
  const cnt = C.patternCounts(seq, n);
  const P = C.patternProbs(ZONE);
  let maxZ = 0;
  for (let k = 0; k < 256; k++) {
    const e = n * P[k];
    const z = Math.abs(cnt[k] - e) / Math.sqrt(e * (1 - P[k]));
    if (z > maxZ) maxZ = z;
  }
  ok('every one of 256 pattern counts within 4.5 binomial sd of its exact expectation',
    maxZ < 4.5, `max |z| = ${maxZ.toFixed(2)} over ${n.toLocaleString('en-US')} sites`);
  // and the empirical informative counts order the topologies the same way
  const fEmp = [0, 0, 0];
  for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) {
    if (i === j) continue;
    fEmp[0] += cnt[((i * 4 + i) * 4 + j) * 4 + j];
    fEmp[1] += cnt[((i * 4 + j) * 4 + i) * 4 + j];
    fEmp[2] += cnt[((i * 4 + j) * 4 + j) * 4 + i];
  }
  ok('at 400 000 sites the wrong topology wins the informative count outright',
    C.argmaxUnique(fEmp) === 1, `${fEmp.map((x) => (x / n).toFixed(5)).join(' / ')}`);
}

// ═══ 6. LAYER 1 · the accuracy curves the page draws ════════════════════════
console.log('\n· maximum parsimony: accuracy vs sequence length (seeded, reproducible) ·');
function mpCurve(regime, reps) {
  return DEF.NS.map((n) => {
    const rnd = C.mulberry32(DEF.SEED1 ^ n);
    let wins = 0;
    for (let i = 0; i < reps; i++) {
      const seq = C.simulate(n, [regime], [1], rnd);
      if (C.argminUnique(C.fitchAll(seq, n)) === 0) wins++;
    }
    return wins / reps;
  });
}
const CURVE_ZONE = [0.2583, 0.2833, 0.3667, 0.1667, 0.2167, 0.0250, 0.0250, 0.0000];
const CURVE_SAFE = [0.5417, 0.8000, 0.8083, 0.9917, 0.9917, 1.0000, 1.0000, 1.0000];
{
  const cz = mpCurve(ZONE, DEF.REPS1);
  console.log(`   zone  n=${DEF.NS.join('/')}  →  ${cz.map(f4).join(' ')}`);
  ok('zone curve reproduces the page exactly (120 replicates per point)',
    eqArr(cz, CURVE_ZONE, 5e-5));
  ok('inside the zone: 10 000 sites recovers the true tree 0 times out of 120',
    cz[cz.length - 1] === 0);
  ok('inside the zone: accuracy at 10 000 sites is BELOW accuracy at 100 sites',
    cz[cz.length - 1] < cz[1], `${f4(cz[1])} → ${f4(cz[cz.length - 1])}`);
  ok('inside the zone: accuracy also falls below 1/3, the blind-guess rate',
    cz[cz.length - 1] < 1 / 3 && cz[5] < 1 / 3);

  const cs = mpCurve(SAFE, DEF.REPS1);
  console.log(`   safe  n=${DEF.NS.join('/')}  →  ${cs.map(f4).join(' ')}`);
  ok('safe curve reproduces the page exactly', eqArr(cs, CURVE_SAFE, 5e-5));
  ok('outside the zone: accuracy climbs to 1.0000 and stays there',
    cs[cs.length - 1] === 1 && cs[cs.length - 2] === 1 && cs[0] < 0.7);
  // The page computes each point in batches of 10 replicates so the browser
  // stays responsive. Batching must not change the answer: one seeded stream,
  // consumed in order, gives the same total either way.
  const batched = (n, reps, regime) => {
    const rnd = C.mulberry32(DEF.SEED1 ^ n);
    let wins = 0, done = 0;
    while (done < reps) {
      const take = Math.min(10, reps - done);
      for (let i = 0; i < take; i++) {
        const seq = C.simulate(n, [regime], [1], rnd);
        if (C.argminUnique(C.fitchAll(seq, n)) === 0) wins++;
      }
      done += take;
    }
    return wins / reps;
  };
  ok('batched evaluation (10 replicates at a time) equals the single-loop result',
    [1, 4, 7].every((idx) => batched(DEF.NS[idx], DEF.REPS1, ZONE) === cz[idx]),
    `${[1, 4, 7].map((i) => batched(DEF.NS[i], DEF.REPS1, ZONE).toFixed(6)).join(' ')}`);
  ok('the ONLY difference between the two curves is one branch length (0.45 vs 0.25)',
    ZONE.b === SAFE.b && ZONE.d === SAFE.d && ZONE.e === SAFE.e && ZONE.a !== SAFE.a);
}

// ═══ 7. Wilson 95% intervals (the error bars the page draws) ════════════════
console.log('\n· Wilson score intervals on the plotted rates ·');
function wilson(k, n, z = 1.959963985) {
  const p = k / n, z2 = z * z;
  const c = (p + z2 / (2 * n)) / (1 + z2 / n);
  const h = (z * Math.sqrt(p * (1 - p) / n + z2 / (4 * n * n))) / (1 + z2 / n);
  return [Math.max(0, c - h), Math.min(1, c + h)];
}
{
  const [lo, hi] = wilson(0, 120);
  ok('0/120 gives a one-sided Wilson interval [0.0000, 0.0310]',
    approx(lo, 0, 1e-12) && approx(hi, 0.0310, 5e-5), `[${lo.toFixed(4)}, ${hi.toFixed(4)}]`);
  const [lo2, hi2] = wilson(31, 120);
  ok('31/120 = 0.2583 gives [0.1884, 0.3433]',
    approx(lo2, 0.1884, 5e-5) && approx(hi2, 0.3433, 5e-5), `[${lo2.toFixed(4)}, ${hi2.toFixed(4)}]`);
  ok('the zone endpoint interval [0.0000, 0.0310] excludes 1/3 · the collapse is not noise',
    hi < 1 / 3);
}

// ═══ 8. The fast likelihood equals the slow likelihood ══════════════════════
console.log('\n· class-collapsed likelihood == full 256-pattern likelihood ·');
{
  const rnd = C.mulberry32(2468);
  const seq = C.simulate(3000, [ZONE], [1], rnd);
  const cnt = C.patternCounts(seq, 3000);
  ok('Jukes-Cantor collapses 256 site patterns to 15 equivalence classes',
    C.CLASSES.reps.length === 15);
  let worst = 0;
  for (const r of [{ a: 0.4, b: 0.06, c: 0.5, d: 0.07, e: 0.04 },
                   { a: 1.2, b: 0.3, c: 0.02, d: 0.9, e: 0.5 }]) {
    for (const t of [0, 1, 2]) {
      const rel = Math.abs(C.llSlow(cnt, t, r) - C.llFast(cnt, t, r)) / Math.abs(C.llSlow(cnt, t, r));
      if (rel > worst) worst = rel;
    }
  }
  ok('the two log-likelihoods agree to floating-point precision',
    worst < 1e-12, `max relative difference ${worst.toExponential(2)}`);
}

// ═══ 9. LAYER 2a · likelihood IS consistent, when the model is right ════════
console.log('\n· the standard answer: ML under the TRUE model, in the same zone ·');
const ML_CONSISTENT = [0.9250, 1.0000, 1.0000];
{
  const got = [200, 1000, 5000].map((n) => {
    const rnd = C.mulberry32(DEF.SEED1 ^ n);
    let wins = 0, reps = 40;
    for (let i = 0; i < reps; i++) {
      const seq = C.simulate(n, [ZONE], [1], rnd);
      const cnt = C.patternCounts(seq, n);
      if (C.mlWinner(cnt, (c, t) => C.mlFit(c, t, DEF.ML_SWEEPS, DEF.ML_GITERS)).winner === 0) wins++;
    }
    return wins / reps;
  });
  console.log(`   n=200/1000/5000  →  ${got.map(f4).join(' ')}   (parsimony there: ${f4(CURVE_ZONE[2])} ${f4(CURVE_ZONE[4])} ${f4(CURVE_ZONE[6])})`);
  ok('ML accuracy in the zone reproduces the page: 0.9250 / 1.0000 / 1.0000',
    eqArr(got, ML_CONSISTENT, 5e-5));
  ok('ML rises with data where parsimony falls · consistency, demonstrated not asserted',
    got[2] >= got[0] && got[2] === 1);
}

// ═══ 10. LAYER 2b · break the fix: heterotachy the model does not contain ═══
console.log('\n· the heterotachy bench: two branch-length regimes, one homogeneous model ·');
const B1 = { a: DEF.hLong, b: DEF.hShort, c: DEF.hLong, d: DEF.hShort, e: DEF.hInternal }; // A,C long
const B2 = { a: DEF.hShort, b: DEF.hLong, c: DEF.hShort, d: DEF.hLong, e: DEF.hInternal }; // B,D long
function bench(rho, reps = DEF.REPS2, mult = 1) {
  const rnd = C.mulberry32(DEF.SEED2 ^ Math.round(rho * 1000));
  let mp = 0, ml = 0, mx = 0;
  for (let i = 0; i < reps; i++) {
    const seq = C.simulate(DEF.N2, [B1, B2], [rho, 1 - rho], rnd);
    const cnt = C.patternCounts(seq, DEF.N2);
    if (C.argminUnique(C.fitchAll(seq, DEF.N2)) === 0) mp++;
    if (C.mlWinner(cnt, (c, t) => C.mlFit(c, t, DEF.ML_SWEEPS * mult, DEF.ML_GITERS * mult)).winner === 0) ml++;
    if (C.mlWinner(cnt, (c, t) => C.mlFitMixture(c, t, DEF.MIX_SWEEPS * mult, DEF.MIX_GITERS * mult)).winner === 0) mx++;
  }
  return [mp / reps, ml / reps, mx / reps];
}
const BENCH = {
  0:    [0.4500, 1.0000, 0.9167],
  0.25: [0.5500, 0.7000, 0.9833],
  0.5:  [0.5000, 0.1000, 0.9833],
  0.75: [0.5167, 0.7333, 0.9500],
  1:    [0.4333, 1.0000, 0.9667],
};
{
  const got = {};
  for (const rho of [0, 0.25, 0.5, 0.75, 1]) {
    got[rho] = bench(rho);
    console.log(`   ρ=${rho.toFixed(2)}   MP ${f4(got[rho][0])}   ML(JC) ${f4(got[rho][1])}   ML(2-class mixture) ${f4(got[rho][2])}`);
  }
  for (const rho of [0, 0.25, 0.5, 0.75, 1]) {
    ok(`bench at ρ=${rho} reproduces the page exactly`, eqArr(got[rho], BENCH[rho], 5e-5));
  }
  // ── the published exchange, both sides, on the same bench ────────────────
  ok('KOLACZKOWSKI & THORNTON regime: at ρ=0.50, parsimony (0.5000) beats homogeneous ML (0.1000)',
    got[0.5][0] > got[0.5][1], `MP − ML = +${f4(got[0.5][0] - got[0.5][1])}`);
  ok('THE CRITICS\' regime: at ρ=0 and ρ=1 (no heterotachy) ML (1.0000) crushes parsimony',
    got[0][1] > got[0][0] && got[1][1] > got[1][0], `+${f4(got[0][1] - got[0][0])} and +${f4(got[1][1] - got[1][0])}`);
  ok('the sign of the MP−ML difference flips with ρ alone · the exchange was an argument about ρ',
    (got[0.5][0] - got[0.5][1]) > 0 && (got[0][0] - got[0][1]) < 0 && (got[1][0] - got[1][1]) < 0);
  ok('parsimony\'s accuracy is nearly FLAT in ρ (0.4333–0.5500): it is not good here, only unbothered',
    Math.max(...[0, 0.25, 0.5, 0.75, 1].map((r) => got[r][0])) -
    Math.min(...[0, 0.25, 0.5, 0.75, 1].map((r) => got[r][0])) < 0.15);
  ok('SPENCER/SUSKO/ROGER answer, part 1: where heterotachy is REAL (ρ=0.25/0.50/0.75) the '
   + '2-class mixture strictly beats both rivals',
    [0.25, 0.5, 0.75].every((r) => got[r][2] > Math.max(got[r][0], got[r][1])));
  ok('SPENCER/SUSKO/ROGER answer, part 2: where there is NO heterotachy (ρ=0 and ρ=1) the mixture '
   + 'LOSES to plain JC by ≤0.10, the ordinary cost of extra parameters',
    [0, 1].every((r) => got[r][2] < got[r][1] && got[r][1] - got[r][2] <= 0.10),
    `deficits ${f4(got[0][1] - got[0][2])} and ${f4(got[1][1] - got[1][2])}`);
  ok('the page\'s stated endpoint deficits (0.0833 at ρ=0, 0.0333 at ρ=1) are exact',
    Math.abs((got[0][1] - got[0][2]) - 0.0833) < 5e-5 && Math.abs((got[1][1] - got[1][2]) - 0.0333) < 5e-5);
  ok('the page\'s stated cost of being WRONG at ρ=0.50 (0.8833) dwarfs both endpoint costs',
    Math.abs((got[0.5][2] - got[0.5][1]) - 0.8833) < 5e-5);
  ok('at the contested point ρ=0.50 the mixture model reaches 0.9833 where plain JC reaches 0.1000',
    got[0.5][2] > 0.9 && got[0.5][1] < 0.2);
  // the misspecification is what does the damage, not the method name
  ok('homogeneous ML is worst exactly where the single-tree assumption is most wrong (ρ=0.50)',
    got[0.5][1] < got[0.25][1] && got[0.5][1] < got[0.75][1]);

  // ── the optimiser-effort control the page claims in its check panel ──────
  // "Doubling the effort was tested and moved no accuracy figure by more than
  // one replicate." That test ships here, so the claim is part of the record.
  console.log('\n· optimiser-effort control: same seeds, 2× sweeps and 2× golden iterations ·');
  const TOL1 = 1 / DEF.REPS2 + 1e-9;               // one replicate out of sixty
  let worst = 0;
  for (const rho of [0, 0.25, 0.5, 0.75, 1]) {
    const dbl = bench(rho, DEF.REPS2, 2);
    const d = [0, 1, 2].map((k) => dbl[k] - got[rho][k]);
    worst = Math.max(worst, ...d.map(Math.abs));
    console.log(`   ρ=${rho.toFixed(2)}   Δ MP ${f4(d[0])}   Δ ML ${f4(d[1])}   Δ mixture ${f4(d[2])}`);
    ok(`doubling optimiser effort at ρ=${rho} moves no figure by more than one replicate`,
      d.every((x) => Math.abs(x) <= TOL1));
  }
  ok('the check panel\'s "no accuracy figure moved by more than one replicate" is reproduced here',
    worst <= TOL1, `largest movement ${f4(worst)} = ${Math.round(worst * DEF.REPS2)} replicate(s)`);
  ok('parsimony is untouched by optimiser effort (it uses no optimiser) · a sanity control',
    [0, 0.25, 0.5, 0.75, 1].every((r) => bench(r, 6, 2)[0] === bench(r, 6, 1)[0]));
}

// ═══ 11. The page and this script must not drift ════════════════════════════
console.log('\n· the page HTML carries the same constants ·');
{
  let html = '';
  try { html = readFileSync(PAGE, 'utf8'); } catch (e) { html = ''; }
  ok('page file found', html.length > 4000, `${html.length} bytes`);
  const has = (needle) => html.indexOf(needle) !== -1;
  const checks = [
    ['SEED1 = 20260720', 'SEED1: 20260720'],
    ['SEED2 = 7314159', 'SEED2: 7314159'],
    ['REPS1 = 120', 'REPS1: 120'],
    ['REPS2 = 60', 'REPS2: 60'],
    ['zone default long = 0.45', 'DEF_LONG: 0.45'],
    ['safe default long = 0.25', 'DEF_SAFE: 0.25'],
    ['heterotachy long = 0.75', 'H_LONG: 0.75'],
    ['heterotachy internal = 0.20', 'H_INT: 0.20'],
    ['bench sites = 1000', 'N2: 1000'],
    ['ML optimiser 3 sweeps / 14 golden iterations', 'ML_SWEEPS: 3, ML_GITERS: 14'],
    ['mixture optimiser 3 sweeps / 12 golden iterations', 'MIX_SWEEPS: 3, MIX_GITERS: 12'],
    ['site lengths 50…10000', 'NS: [50, 100, 200, 500, 1000, 2000, 5000, 10000]'],
  ];
  for (const [label, needle] of checks) ok(`HTML declares ${label}`, has(needle));
  ok('page ships the closing tags (inline script would be dead without them)',
    /<\/script>\s*<\/body>\s*<\/html>/.test(html));
  ok('page makes no third-party request',
    !/(src|href)\s*=\s*["']https?:\/\//i.test(html.replace(/<link rel="canonical"[^>]*>/g, '')
      .replace(/<meta property="og:[^"]*" content="https?:\/\/[^"]*"\s*\/?>/g, '')
      .replace(/<meta name="twitter:[^"]*" content="https?:\/\/[^"]*"\s*\/?>/g, '')
      .replace(/<script type="application\/ld\+json">[\s\S]*?<\/script>/g, '')
      .replace(/<footer>[\s\S]*?<\/footer>/g, '')));
}

// ═══ 12. The page's OWN engine, executed, against core.mjs ══════════════════
// Section 11 only greps constants out of the HTML. That leaves a hole: the page
// could compute the right numbers with the wrong code, or drift silently from
// core.mjs on a later edit. So here the page's inline engine is sliced out at
// the ENGINE-END-SENTINEL marker, executed standalone (it touches no DOM above
// that marker), and run head to head with core.mjs on the same inputs and the
// same seeds.
console.log('\n· the page\'s inline engine, extracted and executed against core.mjs ·');
{
  const html = readFileSync(PAGE, 'utf8');
  const start = html.indexOf("'use strict';");
  const end = html.indexOf('// ENGINE-END-SENTINEL');
  ok('page carries the ENGINE-END-SENTINEL marker the extraction depends on', start > 0 && end > start);
  const NAMES = ['jcSame', 'jcDiff', 'mulberry32', 'step', 'zoneRegime', 'swapRegime', 'simulate',
    'fitchSite', 'fitchAll', 'argminUnique', 'argmaxUnique', 'patternProbs', 'informativeFast',
    'expectedParsimony', 'zoneBoundary', 'patternCounts', 'classCounts', 'classProbs',
    'mlFit', 'mlFitMixture', 'mlWinner'];
  let P = null, err = '';
  try {
    const src = html.slice(start + 13, end) + '\n;return {' + NAMES.join(',') + '};';
    P = new Function(src)();                                    // eslint-disable-line no-new-func
  } catch (e) { err = String(e && e.message); }
  ok('the extracted engine parses and runs with no DOM present', P !== null, err);

  if (P) {
    for (const n of NAMES) ok(`page engine exports ${n}()`, typeof P[n] === 'function');

    // 12a. pointwise arithmetic
    let mx = 0;
    for (let i = 0; i <= 300; i++) {
      const t = i / 200;
      mx = Math.max(mx, Math.abs(P.jcSame(t) - C.jcSame(t)), Math.abs(P.jcDiff(t) - C.jcDiff(t)));
    }
    ok('jcSame/jcDiff agree over t ∈ [0, 1.5]', mx === 0, `max |Δ| = ${mx}`);

    // 12b. the RNG stream, value for value: this is what makes seeds portable
    {
      const a = P.mulberry32(DEF.SEED2), b = C.mulberry32(DEF.SEED2);
      let d = 0;
      for (let i = 0; i < 20000; i++) d = Math.max(d, Math.abs(a() - b()));
      ok('mulberry32 emits an identical 20 000-draw stream from the same seed', d === 0);
    }

    // 12c. exact pattern probabilities and the derived masses
    {
      const r = { a: 0.45, b: 0.05, c: 0.45, d: 0.05, e: 0.05 };
      const pp = P.patternProbs(r), cp = C.patternProbs(r);
      let d = 0; for (let i = 0; i < 256; i++) d = Math.max(d, Math.abs(pp[i] - cp[i]));
      ok('the full 256-pattern distribution agrees to floating point', d < 1e-15, `max |Δ| = ${d.toExponential(2)}`);
      const pf = P.informativeFast(r), cf = C.informativeFast(r);
      ok('informative masses agree', [0, 1, 2].every((k) => Math.abs(pf[k] - cf[k]) < 1e-15));
      const pe = P.expectedParsimony(pp), ce = C.expectedParsimony(cp);
      ok('expected tree lengths agree', [0, 1, 2].every((k) => Math.abs(pe[k] - ce[k]) < 1e-15));
    }

    // 12d. the whole simulate → parsimony → likelihood path, on one seed
    {
      const rnd1 = P.mulberry32(1234567), rnd2 = C.mulberry32(1234567);
      const s1 = P.simulate(400, [P.zoneRegime(0.45, 0.05, 0.05)], [1], rnd1);
      const s2 = C.simulate(400, [C.zoneRegime(0.45, 0.05, 0.05)], [1], rnd2);
      let same = s1.length === s2.length;
      for (let i = 0; same && i < s1.length; i++) same = s1[i] === s2[i];
      ok('simulate() consumes the stream in the same order and emits the same alignment', same);
      ok('Fitch scores on that alignment agree',
        JSON.stringify(Array.from(P.fitchAll(s1, 400))) === JSON.stringify(Array.from(C.fitchAll(s2, 400))));
      const c1 = P.patternCounts(s1, 400), c2 = C.patternCounts(s2, 400);
      // NOTE: the page's mlWinner returns the index, core.mjs returns {winner, lls}.
      // That is the one interface difference, so the log-likelihoods are compared
      // through mlFit directly.
      const w1 = P.mlWinner(c1, (c, t) => P.mlFit(c, t, DEF.ML_SWEEPS, DEF.ML_GITERS));
      const w2 = C.mlWinner(c2, (c, t) => C.mlFit(c, t, DEF.ML_SWEEPS, DEF.ML_GITERS));
      const dML = [0, 1, 2].map((t) => Math.abs(
        P.mlFit(c1, t, DEF.ML_SWEEPS, DEF.ML_GITERS).ll - C.mlFit(c2, t, DEF.ML_SWEEPS, DEF.ML_GITERS).ll));
      ok('the ML winner and all three log-likelihoods agree',
        w1 === w2.winner && dML.every((x) => x < 1e-9),
        `winner ${w1}, max |ΔlnL| = ${Math.max(...dML).toExponential(2)}`);
      const m1 = P.mlWinner(c1, (c, t) => P.mlFitMixture(c, t, DEF.MIX_SWEEPS, DEF.MIX_GITERS));
      const m2 = C.mlWinner(c2, (c, t) => C.mlFitMixture(c, t, DEF.MIX_SWEEPS, DEF.MIX_GITERS));
      const dMX = [0, 1, 2].map((t) => Math.abs(
        P.mlFitMixture(c1, t, DEF.MIX_SWEEPS, DEF.MIX_GITERS).ll - C.mlFitMixture(c2, t, DEF.MIX_SWEEPS, DEF.MIX_GITERS).ll));
      ok('the 2-class mixture winner and all three log-likelihoods agree',
        m1 === m2.winner && dMX.every((x) => x < 1e-9),
        `winner ${m1}, max |ΔlnL| = ${Math.max(...dMX).toExponential(2)}`);
    }

    // 12e. the headline the dek quotes, computed by the PAGE's own code
    {
      const zb = P.zoneBoundary(0.05, 0.05, 200);
      ok('the page\'s own zoneBoundary(0.05, 0.05) = 0.394048, the figure in the dek',
        Math.abs(zb - 0.394048) < 5e-7, `page engine: ${zb.toFixed(6)}`);
    }
  }
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
