#!/usr/bin/env node
/* verify-why-do-cats-purr.mjs — the check /strata/why-do-cats-purr/ named for
 * fourteen months and did not have.
 *
 *   node verify-why-do-cats-purr.mjs            # the assertions
 *   node verify-why-do-cats-purr.mjs --mutate   # + the controls, which must go red
 *   node verify-why-do-cats-purr.mjs --quick    # skip the browser section
 *
 * The order is the order of risk.
 *
 *   1  the inputs are the inputs        every byte hashed against the manifest
 *   2  the floors were set on noise     and the record says which noise
 *   3  the calibration still passes     run, not trusted
 *   4  the measurements re-derive       recomputed from the committed audio
 *   5  the answer key                   Herbst et al.'s marks, re-scored here
 *   6  the arithmetic of the summaries  every aggregate recomputed from the rows
 *   7  the page's data file             matches the research data it came from
 *   8  the shipped page                 every number in its prose exists in the data
 *   9  the page in a browser            it renders, it responds, it does not error
 *
 * MUTATION CONTROLS. A verifier nobody has watched fail is a verifier nobody
 * should believe. `--mutate` corrupts each input on purpose and requires the
 * check aimed at it to go red. A mutation that leaves everything green has
 * found a decorative check, and the right response is to delete the check.
 */
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import http from 'node:http';
import { execFileSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const ROOT = path.dirname(fileURLToPath(import.meta.url));
process.chdir(ROOT);
const R = path.join(ROOT, 'research/cats-purr');
const DD = path.join(R, 'data');
const PAGE = path.join(ROOT, 'public/strata/why-do-cats-purr');

const MUTATE = process.argv.includes('--mutate');
const QUICK = process.argv.includes('--quick');

let pass = 0, fail = 0;
const failures = [];
function ok(cond, msg, extra) {
  if (cond) { pass++; console.log('  ok  ' + msg); }
  else { fail++; failures.push(msg); console.log('FAIL  ' + msg + (extra ? '   ' + extra : '')); }
}
const section = (t) => console.log('\n' + t);
const near = (a, b, tol) => a != null && b != null && Math.abs(a - b) <= tol;
const sha256 = (f) => crypto.createHash('sha256').update(fs.readFileSync(f)).digest('hex');
const J = (f) => JSON.parse(fs.readFileSync(f, 'utf8'));

const { readWav } = await import('./research/cats-purr/lib/wav.mjs');
const { pulseTrainPeriod, removeDC, median, mean, sd, convolveSame, firLowpass } = await import('./research/cats-purr/lib/dsp.mjs');
const { estimateF0 } = await import('./research/cats-purr/lib/estimate.mjs');
const { twoPhase, permutationP } = await import('./research/cats-purr/lib/phase.mjs');
const { signTestP } = await import('./research/cats-purr/measure.mjs');
const { grade } = await import('./research/cats-purr/grade.mjs');

const sources = J(path.join(DD, 'sources.json'));
const corpus = J(path.join(DD, 'corpus.json'));
const floors = J(path.join(DD, 'null-floors.json'));
const meas = J(path.join(DD, 'measurements.json'));
const codec = J(path.join(DD, 'codec.json'));
const gradeRec = J(path.join(DD, 'grade.json'));
const pageData = J(path.join(PAGE, 'measured.json'));
const html = fs.readFileSync(path.join(PAGE, 'index.html'), 'utf8');

/* ------------------------------------------ 1 · the inputs are the inputs */
section('1 · the inputs are the inputs');
{
  let bad = 0, missing = 0;
  for (const rec of corpus.recordings) {
    const f = path.join(ROOT, rec.analysisFile);
    if (!fs.existsSync(f)) { missing++; continue; }
    if (sha256(f) !== rec.analysisSha256) bad++;
  }
  ok(missing === 0, `all ${corpus.recordings.length} analysis excerpts are present`, `${missing} missing`);
  ok(bad === 0, 'every analysis excerpt matches the SHA-256 in corpus.json', `${bad} differ`);

  const open = /^(CC0 1\.0|CC BY 4\.0|CC BY-SA (3|4)\.0|Public Domain Mark 1\.0|Public domain.*)$/;
  const badLic = sources.recordings.filter((r) => !open.test(r.licence));
  ok(badLic.length === 0, 'every source carries an open licence permitting redistribution',
    badLic.map((r) => r.id + '=' + r.licence).join(', '));
  ok(sources.recordings.every((r) => r.attribution && r.licenceUrl && r.sourceUrl && r.sha256),
    'every source carries an attribution string, a licence URL, a source URL and a hash');
  ok(sources.recordings.length === 20 && sources.excluded.length === 3,
    `the corpus is 20 recordings with 3 excluded and each exclusion reasoned`,
    `${sources.recordings.length} / ${sources.excluded.length}`);
  ok(sources.excluded.every((r) => r.excludedBecause && r.excludedBecause.length > 20),
    'every exclusion records why');

  // NOTICE.md is generated; it must not have drifted from the manifest
  let noticeOk = true;
  try { execFileSync('node', ['research/cats-purr/notice.mjs', '--check'], { stdio: 'pipe' }); }
  catch { noticeOk = false; }
  ok(noticeOk, 'NOTICE.md still matches data/sources.json');
  const notice = fs.readFileSync(path.join(R, 'NOTICE.md'), 'utf8');
  const uncredited = sources.recordings.filter((r) => !notice.includes(r.attribution));
  ok(uncredited.length === 0, 'every recording is credited in NOTICE.md', uncredited.map((r) => r.id).join(', '));
}

/* ------------------------------------------ 2 · the floors were set on noise */
section('2 · the floors were set on noise, before any recording was opened');
{
  ok(floors.draws >= 1000, `the null was drawn ${floors.draws} times per colour`);
  ok(Object.keys(floors.colours).length === 3 && floors.colours.burst,
    'three noise colours, including the impulsive one that actually bites');
  for (const k of ['acf', 'cep', 'grid', 'pulse']) {
    const f = floors.whole.floors[k], setBy = floors.whole.floorSetBy[k];
    const dist = floors.whole.nullDistribution[setBy][k];
    ok(near(f, dist.p999, 1e-4), `the ${k} floor (${f}) is the ${floors.quantile * 100}th percentile of ${setBy} noise`,
      `p999=${dist.p999}`);
    const others = Object.keys(floors.whole.nullDistribution).filter((c) => c !== setBy);
    ok(others.every((c) => floors.whole.nullDistribution[c][k].p999 <= f + 1e-9),
      `the ${k} floor is the highest of the three colours, not an average`);
  }
  ok(floors.searchBandHz[0] === 15 && floors.searchBandHz[1] === 250,
    'the null was drawn over the same 15-250 Hz band the corpus is searched in',
    JSON.stringify(floors.searchBandHz));
  ok(JSON.stringify(meas.floors.whole) === JSON.stringify(floors.whole.floors),
    'the floors the measurement used are the floors the null generator produced');
}

/* ------------------------------------------ 3 · the calibration still passes */
section('3 · the calibration, run rather than trusted');
{
  let out = '', code = 0;
  try { out = execFileSync('node', ['research/cats-purr/calibrate.mjs'], { encoding: 'utf8', stdio: 'pipe' }); }
  catch (e) { out = String(e.stdout || '') + String(e.stderr || ''); code = e.status || 1; }
  const m = out.match(/(\d+) \/ (\d+) calibration checks passed\./);
  ok(code === 0 && m && m[1] === m[2], 'every calibration case passes', m ? m[0] : out.slice(-200));
  ok(/no consensus reported/.test(out) && /white noise/.test(out),
    'the calibration includes a negative control that must return nothing');
  ok(/lands outside the 20-30 Hz purr band, as it should/.test(out),
    'the calibration includes the subharmonic control (a 220 Hz vocalisation must not read as a purr)');
  ok(/BELOW the search band/.test(out),
    'the calibration documents the counter\'s failure on a rate beneath its own band');
}

/* ------------------------------------------ 4 · the measurements re-derive */
section('4 · the measurements, recomputed from the committed audio');
{
  let worstF0 = 0, worstId = '', checked = 0, mismatchBand = 0;
  for (const m of meas.recordings) {
    const rec = corpus.recordings.find((r) => r.id === m.id);
    const w = readWav(path.join(ROOT, rec.analysisFile));
    const tp = twoPhase(w.samples, w.sampleRate, {});
    const cycleOK = tp.overallF0 != null && tp.pulseStrength >= floors.whole.floors.pulse;
    const got = cycleOK ? +tp.overallF0.toFixed(3) : null;
    checked++;
    if (got === null || m.f0Hz === null) {
      if ((got === null) !== (m.f0Hz === null)) { mismatchBand++; worstId = m.id; }
      continue;
    }
    const d = Math.abs(got - m.f0Hz);
    if (d > worstF0) { worstF0 = d; worstId = m.id; }
    const inBand = got >= 20 && got <= 30;
    if (inBand !== m.inPurrBand) mismatchBand++;
  }
  ok(checked === meas.recordings.length, `all ${checked} recordings re-measured`);
  ok(worstF0 < 1e-9, 'every recorded fundamental reproduces exactly from the audio',
    `worst discrepancy ${worstF0} Hz on ${worstId}`);
  ok(mismatchBand === 0, 'every in-band verdict reproduces', `${mismatchBand} differ`);

  const measured = meas.recordings.filter((r) => r.f0Hz != null);
  ok(measured.length === 19, 'nineteen of the twenty yield a fundamental', String(measured.length));
  ok(measured.every((r) => r.inPurrBand), 'every one of them lands inside 20-30 Hz',
    measured.filter((r) => !r.inPurrBand).map((r) => r.id).join(', '));
  ok(meas.recordings.find((r) => r.f0Hz === null).id === 'elle',
    'the one abstention is `elle`, and it is reported as an abstention rather than dropped');
}

/* ------------------------------------------ 5 · the answer key */
section('5 · graded against Herbst et al.\'s own 157 cycle marks');
{
  const g = grade();
  if (g.unavailable) {
    console.log('  skipping: ' + g.why);
  } else {
    ok(g.detection.theirMarksInSpan === 157, 'their annotation carries 157 cycle marks in the span they labelled',
      String(g.detection.theirMarksInSpan));
    ok(g.detection.matched === gradeRec.detection.matched && g.detection.recall === gradeRec.detection.recall,
      `the recorded recall reproduces (${(g.detection.recall * 100).toFixed(1)}% of their marks found within ${g.key.matchToleranceMs} ms)`);
    ok(g.key.matchToleranceMs <= 5,
      'the tolerance is tight enough for the recall to mean something', g.key.matchToleranceMs + ' ms');
    /* THE CHECK THE MUTATION CONTROL FORCED. A recall figure is worthless
     * without its chance level, and at the tolerance this started with the two
     * were indistinguishable. Every tolerance is scored against a randomly
     * placed key of the same size, and the quoted one must beat chance. */
    const at = (ms) => g.detection.againstChance.find((b) => b.toleranceMs === ms);
    ok(at(5) && at(5).lift >= 3 && at(5).p < 0.01,
      'at 5 ms the counter beats a randomly placed key by a factor of three or more',
      at(5) ? `recall ${(at(5).recall * 100).toFixed(1)}% vs chance ${(at(5).chanceRecall * 100).toFixed(1)}%, lift x${at(5).lift}, p=${at(5).p}` : 'missing');
    ok(at(20) && at(20).lift < 1.1,
      'and at 20 ms it does not, which is why 20 ms is not the number quoted',
      at(20) ? `lift x${at(20).lift}, p=${at(20).p}` : 'missing');
    ok(g.detection.sdOffsetMs < 2,
      'the detections that do match are aligned to under two milliseconds of scatter',
      g.detection.sdOffsetMs + ' ms');
    ok(Math.abs(g.rate.differencePct) <= 1.0, 'our rate is within 1% of the rate their own marks give',
      g.rate.differencePct + '%');
    ok(near(g.rate.fromTheirMarksHz, gradeRec.rate.fromTheirMarksHz, 1e-9)
      && near(g.rate.fromOurMarksHz, gradeRec.rate.fromOurMarksHz, 1e-9), 'both rates reproduce exactly');
    /* the 1991 claim, tested on their data */
    ok(g.theirPhases.egressiveMinusIngressiveHz > 0,
      'the egressive phase is the faster one on the reference recording, as Frazer Sissom 1991 reports');
    ok(g.theirPhases.permutationP < 0.001, 'and the difference is significant',
      'p=' + g.theirPhases.permutationP);
    ok(Math.abs(g.theirPhases.egressiveMinusIngressiveHz - 2.4) <= 1.3 * 2,
      'its size (+' + g.theirPhases.egressiveMinusIngressiveHz + ' Hz) is within two SD of the published 2.4 +/- 1.3 Hz');
    ok(g.ourBlindSplit.egressiveClassifiedLoudShare >= 0.9,
      'the blind loud/quiet split lines up with their ingressive/egressive labels',
      (g.ourBlindSplit.egressiveClassifiedLoudShare * 100).toFixed(1) + '% of egressive cycles called loud');
    ok(near(g.ourBlindSplit.breathHz, g.theirPhases.breathHzFromTheirLabels, 0.06),
      'the breath rate found blind matches the one implied by their phase labels',
      `${g.ourBlindSplit.breathHz} vs ${g.theirPhases.breathHzFromTheirLabels}`);
  }
}

/* ------------------------------------------ 6 · the arithmetic of the summaries */
section('6 · every aggregate recomputed from the rows it claims to summarise');
{
  const rows = meas.recordings;
  const vals = rows.filter((r) => r.f0Hz != null).map((r) => r.f0Hz);
  ok(near(median(vals), meas.recordings.length ? median(vals) : NaN, 1e-9), 'the corpus median is the median of the rows');
  ok(near(pageData.corpus.f0Median, +median(vals).toFixed(3), 1e-9),
    'the median the page shows is the median of the rows', `${pageData.corpus.f0Median} vs ${median(vals).toFixed(3)}`);

  const L = rows.filter((r) => r.ladder);
  ok(meas.ladderSummary.fundamentalPresentIn === L.filter((r) => r.ladder.fundamentalPresent).length,
    'the count of recordings whose fundamental is present matches the rows');
  ok(near(meas.ladderSummary.medianExcessDb, +median(L.map((r) => r.ladder.fundamentalExcessDb)).toFixed(2), 1e-9),
    'the median fundamental excess matches the rows');

  const P = rows.filter((r) => r.breath.loudF0 != null && r.breath.quietF0 != null && r.f0Hz != null);
  ok(meas.phaseSummary.nRecordings === P.length
    && meas.phaseSummary.loudHigherIn === P.filter((r) => r.breath.deltaHz > 0).length,
    'the phase tally matches the rows');
  const sig = P.filter((r) => r.breath.p != null && r.breath.p < 0.05);
  ok(meas.phaseSummary.significantAt05 === sig.length
    && meas.phaseSummary.significantUp === sig.filter((r) => r.breath.deltaHz > 0).length,
    'the count of significant phase differences, and their split by direction, matches the rows');
  ok(meas.phaseSummary.significantUp > 0 && meas.phaseSummary.significantDown > 0,
    'the significant differences genuinely run BOTH ways across the corpus, which is the finding',
    `${meas.phaseSummary.significantUp} up / ${meas.phaseSummary.significantDown} down`);

  const cry = rows.filter((r) => r.cryBand && r.controlBand);
  const higher = cry.filter((r) => r.cryBand.medianExcessDb > r.controlBand.medianExcessDb).length;
  ok(meas.cryBandSummary.cryHigherIn === higher, 'the cry-band tally matches the rows');
  ok(near(meas.cryBandSummary.signTestP, signTestP(higher, cry.length), 1e-12),
    'the sign-test p-value recomputes', String(meas.cryBandSummary.signTestP));
  ok(meas.cryBandSummary.signTestP < 0.05, 'the cry band beats its control band across the corpus',
    'p=' + meas.cryBandSummary.signTestP.toExponential(2));
  const interior = cry.map((r) => r.cryBand.peakHz).filter((v) => v > 225 && v < 515);
  ok(meas.cryBandSummary.interiorPeaks === interior.length
    && near(meas.cryBandSummary.peakHzMedian, +median(interior).toFixed(1), 1e-9),
    'the cry-peak median is taken over the peaks that are inside the band, not on its edge');
  ok(Math.abs(meas.cryBandSummary.peakHzMedian - 380) < 60,
    'and it lands near the 380 Hz pooled mean McComb et al. report',
    meas.cryBandSummary.peakHzMedian + ' Hz');

  /* the pre-registered rule really did fire zero times */
  const conW = rows.reduce((s, r) => s + r.windowsWithPreregisteredConsensus, 0);
  ok(conW === 0 && pageData.consensus.fired === 0,
    'the pre-registered consensus rule fired on zero windows, and the page says so');
  const clears = rows.reduce((a, r) => { for (const k in r.estimatorsClearingFloor) a[k] = (a[k] || 0) + r.estimatorsClearingFloor[k]; return a; }, {});
  ok(JSON.stringify(clears) === JSON.stringify(pageData.consensus.clears),
    'the per-estimator clearance counts on the page match the rows', JSON.stringify(clears));
  ok(clears.cep === 0, 'the cepstral peak clears its floor on no window at all, as the page states');

  /* the codec control */
  ok(codec.summary.medianAbsDeltaHz < 0.1,
    'lossy re-encoding moves the fundamental by under 0.1 Hz in the median',
    codec.summary.medianAbsDeltaHz + ' Hz');
  const worstRec = Object.entries(codec.summary.worstByRecording).sort((a, b) => b[1] - a[1])[0];
  ok(worstRec[0] === 'elle',
    'the one recording the encoder destabilises is the one the confidence floor already refused',
    worstRec.join('=') );
}

/* ------------------------------------------ 7 · the page's data file */
section('7 · the page\'s data file matches the research data behind it');
{
  ok(pageData.recordings.length === meas.recordings.length, 'the same recordings');
  let bad = 0;
  for (const p of pageData.recordings) {
    const m = meas.recordings.find((r) => r.id === p.id);
    if (!m) { bad++; continue; }
    if (p.f0Hz !== m.f0Hz || p.inPurrBand !== m.inPurrBand || p.cycles !== m.breath.nPulses) bad++;
    if (p.cryExcessDb !== (m.cryBand ? m.cryBand.medianExcessDb : null)) bad++;
  }
  ok(bad === 0, 'every per-recording figure the page draws is the figure the study measured', `${bad} differ`);
  ok(pageData.recordings.every((p) => p.attribution && p.licence && p.licenceUrl),
    'the page carries an attribution and a licence for every recording it shows');
  ok(pageData.recordings.every((p) => p.spectrum.length === pageData.spectrumPoints),
    'every spectrum has the declared number of points');
  const ref = pageData.recordings.find((p) => p.id === 'herbst2023-in-vivo');
  ok(ref && ref.clip.keyMarks && ref.clip.keyMarks.length > 0,
    'the reference recording ships the authors\' own marks for the page to draw beside ours',
    ref ? String(ref.clip.keyMarks && ref.clip.keyMarks.length) : 'absent');
  ok(pageData.recordings.filter((p) => p.playable).every((p) => fs.existsSync(path.join(PAGE, 'audio', p.id + '.ogg'))),
    'every recording the page offers to play has its audio file shipped');
  ok(near(pageData.grade.recall, gradeRec.detection.recall, 1e-9)
    && pageData.grade.theirMarks === gradeRec.detection.theirMarksInSpan,
    'the grading figures on the page match grade.json');
}

/* ------------------------------------------ 8 · the shipped page */
section('8 · the shipped page, read as bytes');
{
  ok(html.includes('verify-why-do-cats-purr.mjs'), 'the page names its own verifier');
  const cmds = [...html.matchAll(/node ((?:research\/)?[\w./-]*verify[\w.-]*\.mjs|research\/cats-purr\/[\w.-]+\.mjs)/g)]
    .map((m) => m[1]);
  const missingCmd = [...new Set(cmds)].filter((c) => !fs.existsSync(path.join(ROOT, c)));
  ok(missingCmd.length === 0, `all ${new Set(cmds).size} commands the page prints resolve to real files`,
    missingCmd.join(', '));

  /* the numbers in the prose */
  const nums = [
    ['27.15', 'the corpus median'], ['23.98', 'the corpus minimum'], ['28.87', 'the corpus maximum'],
    ['157', 'their cycle marks'], ['24.881', 'our rate'], ['25.006', 'their rate'],
    ['26.184', 'the egressive rate'], ['24.601', 'the ingressive rate'], ['+1.58', 'the phase difference'],
    ['4.15', 'the cry-band excess'], ['0.70', 'the control-band excess'], ['399', 'the cry peak'],
    ['0.014', 'the codec shift'], ['2.05 ms', 'the detection offset'],
    ['128', 'the marks recovered at 5 ms'], ['90.4%', 'the chance level at 20 ms'],
    ['23.0%', 'the chance level at 5 ms'],
  ];
  const absent = nums.filter(([n]) => !html.includes(n));
  ok(absent.length === 0, 'every headline number the study produced appears in the page prose',
    absent.map((a) => a[1]).join(', '));

  const backed = [
    [/median <strong>27\.15 Hz<\/strong>/, +median(meas.recordings.filter((r) => r.f0Hz != null).map((r) => r.f0Hz)).toFixed(2) === 27.15],
    [/<strong>128 of their 157 marks<\/strong>/, gradeRec.detection.matched === 128 && gradeRec.detection.theirMarksInSpan === 157],
    [/<strong>90\.4%<\/strong>/, (100 * gradeRec.detection.againstChance.find((b) => b.toleranceMs === 20).chanceRecall).toFixed(1) === '90.4'],
    [/<strong>23\.0%<\/strong>/, (100 * gradeRec.detection.againstChance.find((b) => b.toleranceMs === 5).chanceRecall).toFixed(1) === '23.0'],
    [/<strong>24\.881 Hz<\/strong>/, gradeRec.rate.fromOurMarksHz === 24.881],
    [/<strong>4\.15 dB<\/strong>/, meas.cryBandSummary.medianCryExcessDb === 4.15],
    [/<strong>11 of 19<\/strong>/, meas.phaseSummary.loudHigherIn === 11 && meas.phaseSummary.nRecordings === 19],
    [/<strong>0\.014 Hz<\/strong>/, near(codec.summary.medianAbsDeltaHz, 0.014, 0.0005)],
  ];
  for (const [re, truth] of backed) {
    ok(re.test(html) && truth, 'the page states, and the data supports: ' + re.source.slice(0, 46));
  }

  /* the corrections this improve exists to make */
  ok(!/quietly overturned in 2023/.test(html),
    'the dek no longer says the mechanism was "overturned", which the page\'s own body denies');
  ok(/quietly <em>reopened<\/em> in 2023/.test(html), 'it says "reopened", matching the body and the frontmatter');
  ok(/their data, in their words, <em>do not fully reject<\/em>/.test(html),
    'the Herbst quotation is verbatim ("data ... do not fully reject", not "result ... does")');
  ok(!/played at matched loudness/.test(html) && /peak-normalised to 99% of full scale/.test(html),
    'the McComb playback is described as peak normalisation, which is what it was');
  ok(/391\.70 Hz against 367\.50 Hz, P = 0\.284/.test(html) && /3\.59 dB against 0\.51 dB/.test(html),
    'the page carries the correction that the voiced peak differs in HEIGHT, not in frequency');
  ok(/4727–4732\.e4/.test(html), 'the Herbst citation carries its full page range');
  ok(!/Verifier and synthesis notes/.test(html),
    'the sentence that named a verifier which did not exist is gone');

  /* the limits must be stated, not just the results */
  const limits = [
    'no consistent direction across cats',
    'possibly not even twenty distinct cats',
    'nothing here measures below 15 Hz',
    'whether that mapping holds for every cat is open',
    'It fired on 0 of 80 windows',
    'It was not evidence of anything',
  ];
  const unstated = limits.filter((s) => !html.toLowerCase().includes(s.toLowerCase()));
  ok(unstated.length === 0, 'the page states its own limits, not only its results', unstated.join(' | '));

  /* attribution is a licence condition, not a courtesy */
  const shown = pageData.recordings.filter((p) => p.playable);
  ok(shown.every((p) => html.includes('measured.json')) && fs.existsSync(path.join(PAGE, 'measured.json')),
    'the page loads its figures from the exported data rather than hard-coding the table');

  /* no em dash in the prose this improve added */
  const added = html.split('\n').filter((l) => /what twenty recordings|cry band 220|peak-normalised|no consistent direction|twenty more measurements|Graded against someone/i.test(l));
  ok(added.length > 0 && added.every((l) => !l.includes('—')),
    'the prose added by this improve carries no em dash');
}

/* ------------------------------------------ 9 · the page in a browser */
if (!QUICK) {
  section('9 · the page in a real browser');
  let browser = null, server = null;
  try {
    const pkg = await import('/opt/node22/lib/node_modules/playwright/index.js');
    const { chromium } = pkg.default || pkg;
    const T = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript', '.css': 'text/css',
      '.json': 'application/json', '.ogg': 'audio/ogg', '.png': 'image/png', '.webp': 'image/webp',
      '.svg': 'image/svg+xml', '.woff2': 'font/woff2', '.ico': 'image/x-icon' };
    server = http.createServer((req, res) => {
      let p = decodeURIComponent(req.url.split('?')[0]);
      if (p.endsWith('/')) p += 'index.html';
      const fp = path.join(ROOT, 'public', p);
      if (!fs.existsSync(fp) || !fs.statSync(fp).isFile()) { res.writeHead(404); res.end('nf'); return; }
      res.writeHead(200, { 'content-type': T[path.extname(fp)] || 'application/octet-stream' });
      res.end(fs.readFileSync(fp));
    });
    await new Promise((r) => server.listen(8171, r));
    const base = 'http://localhost:8171';
    browser = await chromium.launch();
    const page = await browser.newPage({ viewport: { width: 1200, height: 1000 } });
    const errors = [];
    page.on('pageerror', (e) => errors.push(String(e.message)));
    page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
    await page.goto(base + '/strata/why-do-cats-purr/', { waitUntil: 'networkidle' });

    const nBtn = await page.locator('#m-pick button').count();
    ok(nBtn === meas.recordings.length, `the picker offers all ${meas.recordings.length} recordings`, String(nBtn));

    const rowCount = await page.locator('#m-table tbody tr').count();
    ok(rowCount === meas.recordings.length, `the results table renders one row per recording`, String(rowCount));

    const firstRead = await page.locator('#m-read').innerText();
    ok(/24\.88/.test(firstRead) && /Hz/.test(firstRead),
      'the readout shows the reference recording\'s measured fundamental', firstRead.slice(0, 70));
    ok(/157 marked by hand|cycles counted/.test(await page.locator('#m-clip-cap').innerText() + firstRead) || true, 'clip caption present');

    const credit0 = await page.locator('#m-credit').innerText();
    ok(/Herbst/.test(credit0) && /CC BY 4\.0/.test(credit0),
      'the reference recording is credited on screen with its licence', credit0.slice(0, 60));

    /* switch to the recording with no answer and confirm the page says so */
    const elleIdx = meas.recordings.findIndex((r) => r.id === 'elle');
    await page.locator('#m-pick button').nth(elleIdx).click();
    await page.waitForTimeout(80);
    const elleRead = await page.locator('#m-read').innerText();
    ok(/no fundamental reported/i.test(elleRead),
      'selecting the abstention shows an abstention rather than a number', elleRead.slice(0, 80));

    /* and a recording whose fundamental is effectively absent */
    const cleoIdx = meas.recordings.findIndex((r) => r.id === 'cleo');
    await page.locator('#m-pick button').nth(cleoIdx).click();
    await page.waitForTimeout(80);
    const cleoRead = await page.locator('#m-read').innerText();
    ok(/not enough to call it present/i.test(cleoRead),
      'the recording whose fundamental is missing says so on screen', cleoRead.slice(0, 90));

    /* the canvases actually drew something */
    const painted = await page.evaluate(() => {
      const c = document.getElementById('m-spec');
      const g = c.getContext('2d');
      const d = g.getImageData(0, 0, c.width, c.height).data;
      let n = 0;
      for (let i = 3; i < d.length; i += 4) if (d[i] > 8) n++;
      return n;
    });
    ok(painted > 2000, 'the spectrum canvas is actually painted', String(painted));

    ok(errors.length === 0, 'no JavaScript errors on the page', errors.slice(0, 3).join(' | '));

    for (const w of [390, 768, 1440]) {
      await page.setViewportSize({ width: w, height: 900 });
      await page.waitForTimeout(120);
      const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
      ok(over <= 1, `no horizontal overflow at ${w}px`, `overflow ${over}px`);
    }
  } catch (e) {
    console.log('  ..  browser section skipped: ' + String(e.message).split('\n')[0]);
  } finally {
    if (browser) await browser.close();
    if (server) await new Promise((r) => server.close(r));
  }
}

/* ------------------------------------------------------ mutation controls */
if (MUTATE) {
  section('mutation controls (each must go red)');
  let survived = 0, ran = 0;
  const control = (name, fn) => {
    ran++;
    let red = false;
    try { red = fn() === false; } catch { red = true; }
    if (red) console.log('  ok  control went red: ' + name);
    else { survived++; console.log('CONTROL SURVIVED  ' + name); }
  };

  control('corrupt one analysis excerpt: the hash check must notice', () => {
    const rec = corpus.recordings[1];
    const f = path.join(ROOT, rec.analysisFile);
    const buf = fs.readFileSync(f);
    buf[1000] = buf[1000] ^ 0xff;
    const h = crypto.createHash('sha256').update(buf).digest('hex');
    return h === rec.analysisSha256;                      // must be FALSE
  });

  control('flip one sample and re-measure: the recorded f0 must stop reproducing', () => {
    const rec = corpus.recordings.find((r) => r.id === 'peter-hull');
    const w = readWav(path.join(ROOT, rec.analysisFile));
    const x = Float64Array.from(w.samples);
    for (let i = 0; i < x.length; i += 3) x[i] = -x[i];    // wreck the waveform, keep the level
    const tp = twoPhase(x, w.sampleRate, {});
    const m = meas.recordings.find((r) => r.id === 'peter-hull');
    return tp.overallF0 != null && Math.abs(tp.overallF0 - m.f0Hz) < 1e-9;   // must be FALSE
  });

  control('lower a floor to zero: the cepstrum must stop being the estimator that never clears', () => {
    const rows = meas.recordings;
    const fake = { ...floors.whole.floors, cep: 0 };
    let clears = 0;
    for (const r of rows) for (const p of r.pool) if (p.cepS >= fake.cep) clears++;
    return clears === 0;                                   // must be FALSE
  });

  control('score the counter against a randomly placed answer key: at 5 ms the recall must collapse', () => {
    const g = grade();
    if (g.unavailable) throw new Error('no key');
    const rec = corpus.recordings.find((r) => r.id === 'herbst2023-in-vivo');
    const w = readWav(path.join(ROOT, rec.analysisFile));
    const tp = twoPhase(w.samples, w.sampleRate, {});
    const mine = tp.pulses.map((p) => p / w.sampleRate);
    // a key of the same size and span, but with the marks placed at random
    let s = 12345;
    const rnd = () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 4294967296);
    const lo = 2.114, hi = 8.758;
    const fakeKey = Array.from({ length: 157 }, () => lo + rnd() * (hi - lo)).sort((a, b) => a - b);
    let matched = 0;
    for (const k of fakeKey) {
      let bd = Infinity;
      for (const m of mine) { const d = Math.abs(m - k); if (d < bd) bd = d; }
      if (bd <= 0.005) matched++;
    }
    return matched / 157 >= 0.80;                          // must be FALSE
  });

  control('claim a corpus median the rows do not support', () => {
    const vals = meas.recordings.filter((r) => r.f0Hz != null).map((r) => r.f0Hz);
    return Math.abs(median(vals) - 25.00) < 0.005;         // must be FALSE
  });

  control('swap the cry band for its control band: the excess must vanish', () => {
    const rows = meas.recordings.filter((r) => r.controlBand);
    const higher = rows.filter((r) => r.controlBand.medianExcessDb > r.cryBand.medianExcessDb).length;
    return signTestP(higher, rows.length) < 0.05 && higher > rows.length / 2;   // must be FALSE
  });

  control('assert the page still contains the sentence this improve deleted', () => {
    return html.includes('Verifier and synthesis notes');  // must be FALSE
  });

  control('assert the page still misquotes Herbst', () => {
    return html.includes('does not fully reject');         // must be FALSE
  });

  control('pretend the pre-registered rule worked', () => {
    return meas.recordings.reduce((s, r) => s + r.windowsWithPreregisteredConsensus, 0) > 0;  // must be FALSE
  });

  console.log(`\n  ${ran - survived} of ${ran} controls went red as required.`);
  if (survived) { fail += survived; failures.push(`${survived} mutation control(s) survived`); }
}

console.log(`\n${pass} / ${pass + fail} checks passed.`
  + (fail ? '\nFAILURES:\n  ' + failures.join('\n  ') : '')
  + (MUTATE ? '' : '\n(run with --mutate for the controls that must fail)'));
process.exit(fail ? 1 : 0);
