#!/usr/bin/env node
/**
 * verify-the-draw-the-code-won.mjs: the check for /strata/the-draw-the-code-won/.
 *
 *   node verify-the-draw-the-code-won.mjs
 *
 * The page's whole claim is that a number everybody samples can be computed
 * exactly, so the check has to be about arithmetic that could be wrong in silence.
 * Eight families, in an order where each sees something the one before cannot:
 *
 *   1. the codon table, parsed from NCBI's pinned file rather than remembered, and
 *      the mutation graph built on it, against the counts the papers publish
 *   2. the cost function, against six numbers published by other people: 5.194,
 *      5.501, 3.489, 9.41, the Freeland-Hurst optimum, and 114 better codes per
 *      million. If any of those is out, nothing downstream is worth reading
 *   3. THE CENTRAL CLAIM, made falsifiable: the closed-form moments against
 *      complete enumeration of every permutation, at sizes where every
 *      permutation can be walked. Plus the control, where the two paths are
 *      deliberately pointed at different data and MUST disagree
 *   4. the closed form against Monte Carlo at the real n = 20, which is the only
 *      place the actual instance is exercised
 *   5. the AAindex parse, positive-controlled against a record read by hand out of
 *      the raw file, because a parser that silently mis-columns 553 scales returns
 *      a full table of plausible wrong numbers
 *   6. the committed artifacts, re-derived rather than trusted, including the
 *      published plus-or-minus resolution the page prints
 *   7. every tail figure carries an interval and a seed, and no exact rank is
 *      claimed anywhere on the page
 *   8. the rendered page in a real browser: the numbers a reader sees, the
 *      instrument they operate, and the 558-scale census run to completion
 */

import fs from 'node:fs';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { pathToFileURL } from 'node:url';
import { loadChromium } from './research/verifier-independence/lib/playwright-resolve.mjs';

const ROOT = path.dirname(new URL(import.meta.url).pathname);
const SLUG = 'the-draw-the-code-won';
const DIR = path.join(ROOT, 'public', 'strata', SLUG);
const RESEARCH = path.join(ROOT, 'research', 'genetic-code-draw');
const OUT = path.join(RESEARCH, 'out');

let pass = 0, fail = 0;
const log = [];
function ok(cond, what, detail) {
  if (cond) { pass++; log.push(`  ok    ${what}`); return true; }
  fail++; log.push(`  FAIL  ${what}${detail ? `\n          ${detail}` : ''}`);
  return false;
}
const near = (a, b, tol) => Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol;
const rel = (a, b) => Math.abs(a - b) / Math.max(Math.abs(a), Math.abs(b), 1e-300);

const C = await import(pathToFileURL(path.join(RESEARCH, 'lib', 'code.mjs')).href);
const M = await import(pathToFileURL(path.join(RESEARCH, 'lib', 'moments.mjs')).href);
const S = await import(pathToFileURL(path.join(RESEARCH, 'lib', 'sample.mjs')).href);
const R = await import(pathToFileURL(path.join(RESEARCH, 'lib', 'rng.mjs')).href);

const read = (f) => JSON.parse(fs.readFileSync(path.join(OUT, f), 'utf8'));
const exactArt = read('exact.json');
const tailArt = read('tail.json');
const censusArt = read('census.json');
const optArt = read('optimum.json');
const enumArt = read('enumerate.json');
const payload = JSON.parse(fs.readFileSync(path.join(DIR, 'payload.json'), 'utf8'));

/* ── 1. the codon table and the mutation graph ────────────────────────────── */

log.push('[1] the codon table, parsed from NCBI, and the graph built on it:');
const blockOf = C.standardBlocks();
const suppressed = C.applySuppression(blockOf);
{
  const table = C.readNcbiTable(1);
  ok(table.size === 64, 'NCBI table 1 parses to 64 codons', `got ${table.size}`);
  ok(table.get('AUG') === 'M' && table.get('UGG') === 'W' && table.get('UGA') === '*'
     && table.get('UAA') === '*' && table.get('UAG') === '*' && table.get('AUA') === 'I',
    'six landmark codons read as they should (AUG Met, UGG Trp, UGA/UAA/UAG stop, AUA Ile)');

  // block sizes, against the degeneracy every textbook prints
  const sizes = new Array(21).fill(0);
  for (const b of blockOf) sizes[b]++;
  const expect = { Leu: 6, Ser: 6, Arg: 6, Val: 4, Pro: 4, Thr: 4, Ala: 4, Gly: 4, Ile: 3, Met: 1, Trp: 1 };
  let sizesOk = true, bad = [];
  for (const [aa, n] of Object.entries(expect)) {
    const i = C.AMINOS.indexOf(aa);
    if (sizes[i] !== n) { sizesOk = false; bad.push(`${aa}=${sizes[i]} want ${n}`); }
  }
  ok(sizesOk, 'the six-fold, four-fold, three-fold and one-fold blocks are exactly where they should be', bad.join(', '));
  ok(sizes[C.STOP] === 3, 'three stop codons', `got ${sizes[C.STOP]}`);
  ok(sizes.reduce((a, b) => a + b, 0) === 64, 'the blocks partition all 64 codons');
  ok(new Set(blockOf).size === 21, 'all 21 blocks are non-empty');

  ok(C.edgeCount({ includeStop: false, blockOf }) === 263,
    'the sense-codon mutation graph has 263 edges (Buhrman et al. 2010, section I)');
  ok(C.edgeCount({ includeStop: true, blockOf }) === 288,
    'the full 64-codon graph has 288 edges');
  ok(C.edgeCount({ includeStop: false, blockOf: suppressed }) === 288,
    'under the suppression rule every codon is a sense codon, so all 288 edges count');

  // the suppression rule sends exactly UAA, UAG to Tyr and UGA to Trp
  const moved = [];
  for (let i = 0; i < 64; i++) if (blockOf[i] !== suppressed[i]) moved.push(`${C.codonName(i)}->${C.AMINOS[suppressed[i]]}`);
  ok(moved.join(',') === 'UAA->Tyr,UAG->Tyr,UGA->Trp',
    'suppression moves exactly UAA and UAG to Tyr and UGA to Trp', moved.join(','));

  // the transition/transversion split
  const edges = C.mutationEdges('fh');
  ok(edges.length === 576, 'every codon has nine one-step neighbours (64 x 9 = 576 ordered)', `got ${edges.length}`);
  const tr = edges.filter((e) => e.transition).length;
  ok(tr === 192, 'exactly a third of one-step changes are transitions (192 of 576)', `got ${tr}`);
  const w2v = edges.filter((e) => e.pos === 1 && !e.transition);
  ok(w2v.every((e) => e.w === 0.1) && w2v.length === 128,
    'the Freeland-Hurst weight 0.1 lands on exactly the 128 second-position transversions', `${w2v.length}`);
}

/* ── 2. the cost, against numbers published by other people ───────────────── */

log.push('[2] the cost function, against six published values:');
const A_woese = C.costMatrix(C.POLAR_WOESE, 2);
const gFlat = C.blockMatrix({ weight: 'flat', includeStop: false, blockOf });
const gFH = C.blockMatrix({ weight: 'fh', includeStop: false, blockOf });
const gSup = C.blockMatrix({ weight: 'flat', includeStop: false, blockOf: suppressed });
{
  const ms0 = C.msCost(gFlat.B, A_woese, gFlat.N);
  ok(near(Number(ms0.toFixed(3)), 5.194, 1e-9), 'MS0 of the standard code rounds to the published 5.194', ms0.toFixed(6));
  const ms0s = C.msCost(gSup.B, A_woese, gSup.N);
  ok(near(Number(ms0s.toFixed(3)), 5.501, 1e-9), 'MS0S of the standard code rounds to the published 5.501', ms0s.toFixed(6));

  const invert = (p) => { const q = new Array(p.length); p.forEach((v, i) => { q[v] = i; }); return q; };
  const goldman = invert([11, 15, 12, 14, 9, 6, 7, 8, 20, 10, 5, 2, 1, 17, 18, 4, 16, 13, 3, 19].map((v) => v - 1));
  const gv = C.msCost(gFlat.B, A_woese, gFlat.N, goldman);
  ok(near(Number(gv.toFixed(3)), 3.489, 1e-9), 'the published globally optimal code re-scores to 3.489', gv.toFixed(6));
  ok(gv < ms0, 'the optimal code really is better than the natural one');

  const fhOpt = invert([15, 11, 12, 13, 18, 6, 17, 20, 19, 14, 9, 8, 2, 5, 4, 3, 10, 16, 1, 7].map((v) => v - 1));
  const fv = C.msCost(gFH.B, A_woese, gFH.N, fhOpt);
  const rowFH = optArt.rows.find((r) => r.key === 'polar-woese/fh');
  ok(near(fv, rowFH.publishedOptimum.value, 1e-12), 'the published Freeland-Hurst optimum re-scores to the committed value', `${fv} vs ${rowFH.publishedOptimum.value}`);
  ok(!rowFH.search.wentBelowPublishedOptimum && !optArt.rows.some((r) => r.search.wentBelowPublishedOptimum),
    'no random-restart search in any of the four models ever beat the published optimum');

  const ex = M.exactMoments(gFlat.B, A_woese, gFlat.N);
  ok(near(Number(ex.mean.toFixed(2)), 9.41, 1e-9), 'the exact mean of all 20! codes rounds to the published 9.41', ex.mean.toFixed(6));

  // 114 better per million, the figure Buhrman et al. Table III reports for MS0
  const c = S.compile(gFlat.B, A_woese);
  const r = S.sampleTail(c, ms0 * 2 * gFlat.N, 1_000_000, R.makeRng(7), { keepMin: false });
  const ci = R.clopperPearson(r.better, 1_000_000);
  ok(ci.lo <= 114e-6 && 114e-6 <= ci.hi,
    'a fresh million draws gives an interval containing the published 114 per million',
    `${r.better}/1e6, interval [${(ci.lo * 1e6).toFixed(1)}, ${(ci.hi * 1e6).toFixed(1)}] per million`);
}

/* ── 3. the central claim: closed form against complete enumeration ───────── */

log.push('[3] the closed-form moments against complete enumeration:');
{
  const sub = (Mx, n) => Array.from({ length: n }, (_, i) => Float64Array.from(Mx[i].slice(0, n)));
  let worst = 0, walked = 0, cases = 0;
  for (let n = 4; n <= 8; n++) {
    const B = sub(gFlat.B, n), A = sub(A_woese, n);
    const ex = M.exactMoments(B, A, 17), en = M.enumeratedMoments(B, A, 17);
    worst = Math.max(worst, rel(ex.mean, en.mean), rel(ex.variance, en.variance), rel(ex.skewness, en.skewness));
    walked += en.count; cases++;
  }
  // and on instances that are not corners of the real code
  const rng = R.makeRng(99);
  for (let n = 5; n <= 7; n++) {
    const B = Array.from({ length: n }, () => new Float64Array(n));
    for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) if (i !== j) B[i][j] = rng.float() < 0.3 ? 0 : Math.round(rng.float() * 40) / 10;
    const p = Array.from({ length: n }, () => Math.round(rng.float() * 150) / 10);
    const A = C.costMatrix(p, 2);
    const ex = M.exactMoments(B, A, 9), en = M.enumeratedMoments(B, A, 9);
    worst = Math.max(worst, rel(ex.mean, en.mean), rel(ex.variance, en.variance), rel(ex.skewness, en.skewness));
    walked += en.count; cases++;
  }
  ok(worst < 1e-9,
    `THE CENTRAL CLAIM: over ${cases} instances and ${walked.toLocaleString('en-US')} permutations walked one at a time, the closed form and complete enumeration agree`,
    `worst relative error ${worst.toExponential(3)}`);

  // the control: a comparison that cannot fail is not a comparison
  const n = 6;
  const B = sub(gFlat.B, n);
  const exW = M.exactMoments(B, sub(C.costMatrix(C.POLAR_WOESE, 2), n), 17).mean;
  const enU = M.enumeratedMoments(B, sub(C.costMatrix(C.POLAR_UPDATED, 2), n), 17).mean;
  ok(rel(exW, enU) > 1e-6,
    'CONTROL: pointed at two different property scales, the same comparison goes red',
    `relative difference ${rel(exW, enU).toExponential(2)}`);

  // and the committed enumerate.json says the same
  ok(enumArt.allAgree && enumArt.control.disagrees,
    'the committed enumerate.json agrees and its own control disagrees',
    `worst ${enumArt.worstRelativeError}`);
}

/* ── 4. the closed form at the real n = 20 ────────────────────────────────── */

log.push('[4] the closed form against Monte Carlo at n = 20:');
{
  const ex = M.exactMoments(gFlat.B, A_woese, gFlat.N);
  const c = S.compile(gFlat.B, A_woese);
  const draws = 2_000_000;
  const r = S.sampleTail(c, 0, draws, R.makeRng(20260814), { keepMin: false });
  const k = 2 * gFlat.N;
  const sMean = r.mean / k, sSd = r.sd / k;
  // the standard error of the sample mean, from the exact sd
  const se = ex.sd / Math.sqrt(draws);
  ok(Math.abs(sMean - ex.mean) < 5 * se,
    'the sample mean of 2,000,000 draws lands within five standard errors of the exact mean',
    `sample ${sMean.toFixed(6)}, exact ${ex.mean.toFixed(6)}, s.e. ${se.toExponential(2)}`);
  ok(rel(sSd, ex.sd) < 5e-3, 'the sample standard deviation matches the exact one to better than 0.5%',
    `sample ${sSd.toFixed(6)}, exact ${ex.sd.toFixed(6)}`);
  ok(Math.abs(r.skewness - ex.skewness) < 0.02, 'the sample skewness matches the exact one',
    `sample ${r.skewness.toFixed(4)}, exact ${ex.skewness.toFixed(4)}`);
  ok(ex.skewness > 0, 'the background leans right, which is why its left tail is thinner than a normal curve');

  // a control on the sampler itself: a deliberately wrong target must change the count
  const ms0 = C.msCost(gFlat.B, A_woese, gFlat.N);
  const hit = S.sampleTail(c, ms0 * k, 200_000, R.makeRng(5), { keepMin: false });
  const atMean = S.sampleTail(c, ex.mean * k, 200_000, R.makeRng(5), { keepMin: false });
  ok(hit.better < atMean.better / 10,
    'CONTROL: the same sampler asked about the mean instead of the natural code returns a wholly different count',
    `${hit.better} vs ${atMean.better} in 200,000`);
}

/* ── 5. the AAindex parse ─────────────────────────────────────────────────── */

log.push('[5] the AAindex parse, positive-controlled against the raw file:');
{
  const raw = fs.readFileSync(path.join(RESEARCH, 'data', 'aaindex1'), 'utf8');
  const entries = C.readAaindex();
  ok(entries.length === (raw.match(/^\/\/$/gm) || []).length,
    'one parsed entry per record terminator in the file', `${entries.length}`);
  const complete = entries.filter((e) => e.values);
  ok(complete.length === censusArt.summary.scalesScored,
    'the parse yields the number of complete scales the committed census used',
    `${complete.length} vs ${censusArt.summary.scalesScored}`);

  // POSITIVE CONTROL: one record, read out of the raw text by hand here, must come
  // back from the parser in the right amino-acid slots. A parser that mis-columns
  // returns 553 plausible wrong scales and no error.
  const rec = raw.split(/^\/\/$/m).find((r) => /^H KYTJ820101/m.test(r));
  const lines = rec.split('\n');
  const li = lines.findIndex((l) => /^I\s+A\/L/.test(l));
  const r1 = lines[li + 1].trim().split(/\s+/).map(Number);
  const r2 = lines[li + 2].trim().split(/\s+/).map(Number);
  const byHand = { Ala: r1[0], Arg: r1[1], Asn: r1[2], Asp: r1[3], Cys: r1[4], Gln: r1[5], Glu: r1[6], Gly: r1[7], His: r1[8], Ile: r1[9],
    Leu: r2[0], Lys: r2[1], Met: r2[2], Phe: r2[3], Pro: r2[4], Ser: r2[5], Thr: r2[6], Trp: r2[7], Tyr: r2[8], Val: r2[9] };
  const parsed = entries.find((e) => e.id === 'KYTJ820101');
  const mismatch = C.AMINOS.filter((a, i) => Math.abs(parsed.values[i] - byHand[a]) > 1e-9);
  ok(mismatch.length === 0, 'Kyte-Doolittle hydropathy comes back in the right twenty slots', mismatch.join(','));
  // ...and it is the same scale the papers' MATLAB carries, which is a second, independent source
  const same = C.AMINOS.every((a, i) => Math.abs(parsed.values[i] - C.HYDROPATHY[i]) < 1e-9);
  ok(same, "AAindex's Kyte-Doolittle equals the vector transcribed from the papers' own MATLAB");

  // NEGATIVE CONTROL: a shuffled scale must NOT match, or the comparison above is empty
  const shuffled = [...C.HYDROPATHY]; shuffled.push(shuffled.shift());
  ok(!C.AMINOS.every((a, i) => Math.abs(parsed.values[i] - shuffled[i]) < 1e-9),
    'CONTROL: rotating that vector by one position breaks the match');

  // the pinned files are the ones the numbers were computed from
  const sha = (f) => crypto.createHash('sha256').update(fs.readFileSync(path.join(RESEARCH, 'data', f))).digest('hex');
  ok(sha('aaindex1') === censusArt.aaindexSha256, 'the AAindex file on disk is the one the census read');
  ok(sha('aaindex1') === payload.sources.aaindex.sha256 && sha('ncbi-gc.prt') === payload.sources.ncbi.sha256,
    'the page payload names the same two pinned files by hash');
}

/* ── 6. the committed artifacts, re-derived ───────────────────────────────── */

log.push('[6] the committed artifacts, recomputed rather than trusted:');
{
  let worst = 0, n = 0;
  for (const row of exactArt.rows) {
    const bo = row.stops === 'suppression' ? suppressed : blockOf;
    const { B, N } = C.blockMatrix({ weight: row.weight, includeStop: false, blockOf: bo });
    const A = C.costMatrix(C.NAMED_SCALES[row.scale].values, row.power);
    const sgc = C.msCost(B, A, N);
    const ex = M.exactMoments(B, A, N, { third: false });
    worst = Math.max(worst, rel(sgc, row.sgc), rel(ex.mean, row.mean), rel(ex.sd, row.sd));
    n++;
  }
  ok(worst < 1e-12, `all ${n} rows of exact.json recompute from source`, `worst relative error ${worst.toExponential(2)}`);

  // the z-scores in census.json, recomputed for a sample of scales
  const entries = C.readAaindex().filter((e) => e.values);
  const byId = new Map(entries.map((e) => [e.id, e.values]));
  let cworst = 0, checked = 0;
  for (const row of censusArt.rows) {
    if (row.source !== 'aaindex1') continue;
    if (checked >= 40 && !/^(WERD|KYTJ|GRAR|MIYS)/.test(row.id)) continue;
    const v = byId.get(row.id);
    for (const [wk, g] of [['flat', gFlat], ['fh', gFH]]) {
      const A = C.costMatrix(v, 2);
      const ex = M.exactMoments(g.B, A, g.N, { third: false });
      const z = (C.msCost(g.B, A, g.N) - ex.mean) / ex.sd;
      cworst = Math.max(cworst, Math.abs(z - row[wk].z));
    }
    checked++;
  }
  ok(cworst < 1e-9, `${checked} census rows recompute to the committed z-scores`, `worst absolute error ${cworst.toExponential(2)}`);

  // the census summary counts, recounted
  const aa = censusArt.rows.filter((r) => r.source === 'aaindex1');
  ok(aa.filter((r) => r.flat.z < 0).length === censusArt.summary.flat.betterThanAverage
     && aa.filter((r) => r.flat.z < -2).length === censusArt.summary.flat.zBelow2
     && aa.filter((r) => r.flat.z < -3).length === censusArt.summary.flat.zBelow3
     && aa.filter((r) => r.flat.z > 0).length === censusArt.summary.flat.worseThanAverage,
    'the census summary counts match a recount of its own rows');
  ok(censusArt.summary.flat.betterThanAverage + censusArt.summary.flat.worseThanAverage === censusArt.summary.scalesScored,
    'better-than-average and worse-than-average partition the scored scales');

  // THE PUBLISHED PLUS-OR-MINUS, decided by arithmetic rather than by assertion
  const t0 = tailArt.rows.find((r) => r.key === 'polar-woese/flat');
  const t1 = tailArt.rows.find((r) => r.key === 'polar-woese/flat/suppression');
  ok(near(t0.exact.sd, 1.51, 5e-3) && !near(t0.exact.variance, 1.51, 5e-3),
    'the published 9.41 +/- 1.51 is a standard deviation: the exact s.d. is 1.51 and the exact variance is not',
    `sd ${t0.exact.sd.toFixed(6)}, variance ${t0.exact.variance.toFixed(6)}`);
  ok(near(t1.exact.variance, 1.89, 5e-3) && !near(t1.exact.sd, 1.89, 5e-3),
    'the published 9.43 +/- 1.89 is a variance: the exact variance is 1.89 and the exact s.d. is not',
    `sd ${t1.exact.sd.toFixed(6)}, variance ${t1.exact.variance.toFixed(6)}`);
  ok(near(t0.exact.mean, 9.41, 5e-3) && near(t1.exact.mean, 9.43, 5e-3),
    'both published means are right to the digits printed');
}

/* ── 7. every tail figure is an estimate, and says so ─────────────────────── */

log.push('[7] the tail figures carry intervals, seeds and no exact claim:');
{
  const rows = tailArt.rows.filter((r) => r.sampled && r.sampled.draws && r.exact);
  ok(rows.length >= 6, 'the committed tail run covers at least six cost models', `${rows.length}`);
  ok(rows.every((r) => Array.isArray(r.sampled.ci95) && r.sampled.ci95[0] <= r.sampled.proportion && r.sampled.proportion <= r.sampled.ci95[1]),
    'every sampled proportion lies inside its own Clopper-Pearson interval');
  ok(rows.every((r) => r.sampled.seed === tailArt.seed && r.sampled.draws === tailArt.draws),
    'every row records the same declared seed and draw count');
  const ctl = tailArt.rows.find((r) => String(r.key).startsWith('CONTROL'));
  ok(ctl && ctl.intervalsOverlap,
    'CONTROL: the headline cell redrawn from the operating system generator agrees with the seeded one',
    ctl ? JSON.stringify(ctl.sampled) : 'missing');

  const head = rows.find((r) => r.key === 'polar-woese/flat');
  ok(head.approximations.normalOverstatesBy > 5,
    'the normal reading of the exact z overstates the share of better codes by more than fivefold',
    `factor ${head.approximations.normalOverstatesBy.toFixed(1)}`);
  ok(rows.some((r) => r.approximations.edgeworthTail < 0),
    'at least one model has the first Edgeworth correction return a negative probability, which the page reports rather than clips');

  // the page must say plainly that the rank is not exact, and must never call one exact
  const html = fs.readFileSync(path.join(DIR, 'index.html'), 'utf8');
  ok(/There is no exact rank here/.test(html), 'the page states in its own words that it has no exact rank');
  const forbidden = [/the exact tail/i, /exact(ly)? one in/i, /the exact rank of/i, /exact proportion/i];
  const hits = forbidden.filter((re) => re.test(html)).map(String);
  ok(hits.length === 0, 'and never calls a tail, a rank or a proportion exact anywhere in its prose', hits.join(' '));
  ok(/Clopper-Pearson/.test(html) && /seed \$\{|seed/.test(html), 'the page names its interval method and prints its seed');
}

/* ── 8. the rendered page ─────────────────────────────────────────────────── */

log.push('[8] the page in a real browser:');
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.mjs': 'text/javascript',
  '.css': 'text/css', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png',
  '.ico': 'image/x-icon', '.woff2': 'font/woff2', '.woff': 'font/woff', '.txt': 'text/plain' };
const PUBLIC = path.join(ROOT, 'public');
const server = http.createServer((req, res) => {
  let p;
  try { p = decodeURIComponent(new URL(req.url, 'http://localhost').pathname); }
  catch { res.writeHead(400); res.end(); return; }
  if (p.endsWith('/')) p += 'index.html';
  const f = path.join(PUBLIC, p);
  if (!f.startsWith(PUBLIC + path.sep) || !fs.existsSync(f) || !fs.statSync(f).isFile()) { res.writeHead(404); res.end('no'); return; }
  res.writeHead(200, { 'content-type': MIME[path.extname(f)] || 'application/octet-stream' });
  res.end(fs.readFileSync(f));
});
await new Promise((r) => server.listen(0, '127.0.0.1', r));
const BASE = `http://127.0.0.1:${server.address().port}`;

let browser = null;
try {
  const chromium = await loadChromium();
  browser = await chromium.launch({ args: ['--no-sandbox'] });
  const page = await browser.newPage({ viewport: { width: 1280, height: 900 } });
  const errs = [];
  page.on('pageerror', (e) => errs.push(String(e.message).slice(0, 200)));
  page.on('console', (m) => { if (m.type() === 'error') errs.push(`console: ${m.text().slice(0, 160)}`); });
  await page.goto(`${BASE}/strata/${SLUG}/`, { waitUntil: 'load', timeout: 40000 });
  await page.waitForFunction(() => document.querySelector('#r-mean') && document.querySelector('#r-mean').textContent !== '–', null, { timeout: 30000 });

  ok(errs.length === 0, 'the page loads and runs without throwing', errs.join('; '));

  const shown = await page.evaluate(() => ({
    yours: document.querySelector('#r-yours').textContent,
    nat: document.querySelector('#r-nat').textContent,
    mean: document.querySelector('#r-mean').textContent,
    sd: document.querySelector('#r-sd').textContent,
    z: document.querySelector('#r-z').textContent,
    cells: document.querySelectorAll('.cell').length,
    stops: [...document.querySelectorAll('.cell')].filter((c) => c.querySelector('.aa').textContent === 'stop').length,
    facts: Object.fromEntries([...document.querySelectorAll('[data-f]')].map((e) => [e.dataset.f, e.textContent])),
    exactRows: document.querySelectorAll('#exact-tbl tbody tr').length,
    tailRows: document.querySelectorAll('#tail-tbl tbody tr').length,
    pmRows: [...document.querySelectorAll('#pm-tbl tbody tr')].map((tr) => tr.lastElementChild.textContent),
    optRows: document.querySelectorAll('#opt-tbl tbody tr').length,
    checks: document.querySelectorAll('#checklist li').length,
    enumText: document.querySelector('#enum-p').textContent,
  }));

  const exFlat = M.exactMoments(gFlat.B, A_woese, gFlat.N, { third: false });
  const ms0 = C.msCost(gFlat.B, A_woese, gFlat.N);
  ok(shown.cells === 64, 'the table renders 64 codons', String(shown.cells));
  ok(shown.stops === 3, 'three of them read as stop', String(shown.stops));
  ok(shown.nat === ms0.toFixed(4) && shown.yours === ms0.toFixed(4),
    'it opens on the natural code and prints its cost as this verifier computes it', `${shown.nat} / ${ms0.toFixed(4)}`);
  ok(shown.mean === exFlat.mean.toFixed(4), 'the exact mean the browser computed equals the one computed here', `${shown.mean} vs ${exFlat.mean.toFixed(4)}`);
  ok(shown.sd === exFlat.sd.toFixed(4), 'and the exact standard deviation', `${shown.sd} vs ${exFlat.sd.toFixed(4)}`);

  const zLive = (ms0 - exFlat.mean) / exFlat.sd;
  ok(shown.z === zLive.toFixed(3), 'and the z-score', `${shown.z} vs ${zLive.toFixed(3)}`);

  ok(Object.values(shown.facts).every((v) => v && v.trim() && !/^(–|-)$/.test(v)),
    'every figure the prose injects got filled', JSON.stringify(shown.facts).slice(0, 200));
  ok(shown.facts.edges === '263', 'the prose says 263 edges because the browser counted 263', shown.facts.edges);
  ok(shown.exactRows === 7 && shown.tailRows >= 6 && shown.optRows === 4 && shown.checks >= 6,
    'the four committed tables all filled', JSON.stringify([shown.exactRows, shown.tailRows, shown.optRows, shown.checks]));
  ok(shown.pmRows.join('|') === 'the standard deviation|the variance',
    'the plus-or-minus table decides each row from the exact numbers', shown.pmRows.join('|'));
  ok(/1e-/.test(shown.enumText) || /e-\d/.test(shown.enumText), 'the enumeration check prints its worst error');

  // operate it: swap two amino acids and confirm the numbers move the right way
  const swapped = await page.evaluate(() => {
    const cells = [...document.querySelectorAll('.cell')];
    const a = cells.find((c) => c.querySelector('.aa').textContent === 'Phe');
    const b = cells.find((c) => c.querySelector('.aa').textContent === 'Lys');
    a.click(); b.click();
    return {
      yours: document.querySelector('#r-yours').textContent,
      moved: document.querySelectorAll('.cell.moved').length,
      phe: [...document.querySelectorAll('.cell')].filter((c) => c.querySelector('.aa').textContent === 'Phe').length,
    };
  });
  const permSwap = Int32Array.from({ length: 20 }, (_, i) => i);
  const iPhe = C.AMINOS.indexOf('Phe'), iLys = C.AMINOS.indexOf('Lys');
  permSwap[iPhe] = iLys; permSwap[iLys] = iPhe;
  const expect = C.msCost(gFlat.B, A_woese, gFlat.N, permSwap);
  ok(swapped.yours === expect.toFixed(4),
    'swapping Phe and Lys in the browser gives the cost this verifier computes for that permutation',
    `${swapped.yours} vs ${expect.toFixed(4)}`);
  ok(swapped.moved === 4, 'exactly the four codons of the two swapped blocks are marked as moved', String(swapped.moved));
  ok(swapped.phe === 2, 'phenylalanine still occupies two codons, because the block structure is fixed', String(swapped.phe));
  ok(expect > ms0, 'and that swap makes the code worse, as it should');

  // the sampler
  await page.click('#reset');
  await page.click('#draw10k');
  await page.waitForFunction(() => Number(document.querySelector('#d-n').textContent.replace(/,/g, '')) >= 10000, null, { timeout: 20000 });
  const drew = await page.evaluate(() => ({
    n: Number(document.querySelector('#d-n').textContent.replace(/,/g, '')),
    mean: parseFloat(document.querySelector('#d-mean').textContent),
    better: Number(document.querySelector('#d-better').textContent.replace(/,/g, '')),
  }));
  ok(drew.n === 10000, 'ten thousand draws land', String(drew.n));
  ok(Math.abs(drew.mean - exFlat.mean) < 6 * exFlat.sd / Math.sqrt(10000),
    'their mean is within six standard errors of the exact mean', `${drew.mean} vs ${exFlat.mean.toFixed(4)}`);
  ok(drew.better <= 10, 'and at most a handful of them beat the natural code', String(drew.better));

  // the census: 558 exact z-scores, run to completion in the browser
  await page.click('#census-go');
  await page.waitForFunction(() => /Largest disagreement/.test(document.querySelector('#cen-status').textContent), null, { timeout: 90000 });
  const cen = await page.evaluate(() => ({
    status: document.querySelector('#cen-status').textContent,
    worst: Number(document.querySelector('#cen-status').dataset.worst),
    agree: document.querySelector('#cen-status').dataset.agree,
    rows: document.querySelectorAll('#cen-tbl tbody tr').length,
  }));
  ok(cen.agree === 'true' && !/DISAGREE/.test(cen.status),
    'the browser census checks its fast path against the reference and they agree', cen.status.slice(0, 160));
  const disag = cen.worst;
  ok(Number.isFinite(disag) && disag < 1e-6,
    'the browser census agrees with this repository\'s committed offline run', `largest disagreement ${disag}`);
  ok(cen.rows > 5, 'the census table fills', String(cen.rows));

  // no horizontal overflow at three widths
  for (const w of [390, 768, 1440]) {
    await page.setViewportSize({ width: w, height: 900 });
    await page.waitForTimeout(150);
    const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
    ok(over <= 1, `no horizontal overflow at ${w}px`, `overflow ${over}px`);
  }
  ok(errs.length === 0, 'still no page errors after operating everything', errs.join('; '));
} catch (e) {
  ok(false, 'the browser pass ran', String(e.message).slice(0, 220));
} finally {
  if (browser) await browser.close();
  server.close();
}

/* ── 9. the score the page states about this file ─────────────────────────── */

log.push('[9] the score the page prints about this verifier:');
{
  const html = fs.readFileSync(path.join(DIR, 'index.html'), 'utf8');
  const m = html.match(/(\d{1,4})\s*\/\s*(\d{1,4})\s+checks/);
  const total = pass + fail + 1;          // this check included
  ok(m && Number(m[1]) === total && Number(m[2]) === total,
    `the page says ${m ? `${m[1]}/${m[2]}` : 'nothing'} and this run has ${total} checks in it`,
    m ? `stated ${m[1]}/${m[2]}, actual ${pass}/${total}` : 'no score sentence found on the page');
}

/* ── report ───────────────────────────────────────────────────────────────── */

console.log(`\nverify-${SLUG}.mjs\n`);
console.log(log.join('\n'));
console.log(`\n${pass}/${pass + fail} checks pass${fail ? `, ${fail} FAILED` : ''}.\n`);
process.exit(fail ? 1 : 0);
