#!/usr/bin/env node
// verify-does-an-epidemic-stop-at-herd-immunity.mjs: checks /strata/does-an-epidemic-stop-at-herd-immunity/ ("Twice the Excess").
//
//   node verify-does-an-epidemic-stop-at-herd-immunity.mjs            # the model, the 1907 table, the inversion, the page's prose
//   node verify-does-an-epidemic-stop-at-herd-immunity.mjs --mutate   # also break the engine on purpose; the checks must go red
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it downloads
// the page's engine.mjs and index.html from https://artwaste.land into ./does-an-epidemic-stop-at-herd-immunity-files/
// (the bytes your browser runs), and fetches the Internet Archive's OCR of the 1907 volume to compare the table
// with. Exit 0 = every check passed. It takes about fifteen seconds (the damping searches are most of it).

import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'does-an-epidemic-stop-at-herd-immunity';
const MUTATE = process.argv.includes('--mutate');
let dir = join(here, 'public/strata', slug);
if (!existsSync(join(dir, 'engine.mjs'))) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  for (const f of ['engine.mjs', 'index.html']) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const engineSrc = readFileSync(join(dir, 'engine.mjs'), 'utf8');
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const text = html.replace(/<script[\s\S]*?<\/script>/g, ' ').replace(/<style[\s\S]*?<\/style>/g, ' ')
  .replace(/<sup>/g, '^').replace(/<\/?sub>/g, '').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&middot;/g, '·')
  .replace(/&minus;/g, '−').replace(/&amp;/g, '&').replace(/\s+/g, ' ');
// Sentences of the page: a figure is only "stated" if it sits in the same sentence as what it is a figure of.
const sentences = text.split(/(?<=[.!?:;])\s+(?=[A-Z0-9“(])/);
const stated = (needles) => sentences.some((s) => needles.every((n) => s.includes(n)));

// The OCR of the same page, an independent reading of the scan by the Internet Archive.
async function ocrTokens() {
  const local = join(here, 'research', slug, 'sources', 'ia-ocr-journalofhygiene07nutt-table-ix.txt');
  let raw;
  if (existsSync(local)) raw = readFileSync(local, 'utf8').split('\n').filter((l) => !l.startsWith('#')).join('\n');
  else {
    const r = await fetch('https://archive.org/download/journalofhygiene07nutt/journalofhygiene07nutt_djvu.txt');
    if (!r.ok) throw new Error(`could not download the OCR: ${r.status}`);
    const all = (await r.text()).split('\n');
    const a = all.findIndex((l) => /^TABLE {2}IX\./.test(l));
    const b = all.findIndex((l, k) => k > a && /^323-9/.test(l));
    raw = all.slice(a, b + 1).join('\n');
  }
  // numbers in reading order: "5-9" is the OCR's "5·9", "42  0" is "42·0"
  const toks = [];
  for (const line of raw.split('\n')) {
    const m = line.trim().match(/^(\d+)(?:[-·.]\s*|\s{2})(\d)$/) || line.trim().match(/^(\d+)$/);
    if (m) toks.push(m[2] !== undefined ? Number(`${m[1]}.${m[2]}`) : Number(m[1]));
  }
  return toks;
}
const OCR = await ocrTokens();

async function suite(E, { quiet = false } = {}) {
  let pass = 0, fail = 0;
  const check = (name, ok, detail = '') => {
    if (ok) pass++; else fail++;
    if (!quiet) console.log(`${ok ? 'ok  ' : 'FAIL'} ${name}${detail ? '  (' + detail + ')' : ''}`);
    return ok;
  };
  const near = (a, b, tol) => Math.abs(a - b) <= tol;
  const p1 = (x) => (100 * x).toFixed(1) + '%';

  // ---------------------------------------------------------------- 1. the model
  // An independent final size, by bisection, not the engine's Newton.
  const fsBisect = (R) => { let lo = 1e-12, hi = 1; for (let k = 0; k < 200; k++) { const m = (lo + hi) / 2; (m - 1 + Math.exp(-R * m) < 0) ? (lo = m) : (hi = m); } return (lo + hi) / 2; };
  let worstFs = 0, worstSim = 0, worstPeak = 0;
  for (const R of [1.2, 1.5, 2, 2.5, 4, 8]) {
    worstFs = Math.max(worstFs, Math.abs(E.finalSize(R) - fsBisect(R)));
    const run = E.sir(R, { i0: 1e-7, tMax: 60 + 30 / (R - 1), dt: 0.01, every: 50 });
    worstSim = Math.max(worstSim, Math.abs(run.everInfected - fsBisect(R)));
    worstPeak = Math.max(worstPeak, Math.abs(run.sAtPeak - 1 / R));
  }
  check('final size: engine (Newton) and an independent bisection agree for R0 = 1.2 to 8', worstFs < 1e-12, worstFs.toExponential(1));
  check('final size: the simulated epidemic ends where z = 1 - exp(-R0 z) says', worstSim < 2e-6, worstSim.toExponential(1));
  check('the peak comes when the susceptible share is 1/R0 (the threshold reached), every R0 tried', worstPeak < 2e-3, worstPeak.toExponential(1));

  // The table on the page, row by row.
  const rows = [...html.matchAll(/<tr><td>([\d.]+)<\/td><td>([\d.]+)%<\/td><td>([\d.]+)%<\/td><td>([\d.]+) pts<\/td><td>(\d+)%<\/td><td>([\d.]+)%<\/td><\/tr>/g)];
  let rowsOk = rows.length === 7;
  for (const r of rows) {
    const L = E.ledger(Number(r[1]));
    rowsOk &&= (100 * L.hit).toFixed(1) === r[2] && (100 * fsBisect(L.R0)).toFixed(1) === r[3] && (100 * L.overshoot).toFixed(1) === r[4]
      && (100 * L.pastPeakShare).toFixed(0) === r[5] && (100 * 2 * (1 - 1 / L.R0)).toFixed(1) === r[6];
  }
  check('the table of thresholds, final sizes, overshoots and twice the excess: all 7 rows recomputed', rowsOk, `${rows.length} rows read`);
  const L25 = E.ledger(2.5), L11 = E.ledger(1.1);
  check('dek: at R0 = 2.5 the threshold is 60% and the epidemic ends at 89.3%', stated(['R0 = 2.5', '60%', p1(L25.final)]) && p1(L25.final) === '89.3%');
  check('at 1.1 twice the excess says 18.2% against an exact 17.6%', stated(['1.1', '18.2%', '17.6%']) && p1(L11.km) === '18.2%' && p1(L11.final) === '17.6%');
  const maxOver = Math.max(...Array.from({ length: 300 }, (_, k) => E.ledger(1.01 + k * 0.03).overshoot));
  const argOver = 1.01 + 0.03 * Array.from({ length: 300 }, (_, k) => E.ledger(1.01 + k * 0.03).overshoot).indexOf(maxOver);
  check('the overshoot in points is largest between R0 = 2 and 2.5, about 30 points', argOver > 2 && argOver < 2.5 && near(maxOver, 0.30, 0.01) && stated(['about 30 points', 'R0 = 2 and 2.5']), `max ${p1(maxOver)} at R0 ${argOver.toFixed(2)}`);
  let falls = true; for (let R = 1.02; R < 12; R += 0.05) falls &&= E.ledger(R + 0.05).pastPeakShare < E.ledger(R).pastPeakShare;
  check('measured as a share of all infections the overshoot falls steadily from one half', falls && near(E.ledger(1.0001).pastPeakShare, 0.5, 1e-3));

  // Second-order expansions of the three size rules, estimated numerically at small epsilon.
  const eps = 1e-3, R = 1 + eps, h = 1 - 1 / R;
  const cExact = (fsBisect(R) - 2 * eps) / eps ** 2, cPlain = (2 * h - 2 * eps) / eps ** 2, cRef = (2 * h * (1 - h) - 2 * eps) / eps ** 2;
  check('second order: exact -8/3, twice the excess -2, the refined 2n - 2n^2/N -4', near(cExact, -8 / 3, 0.01) && near(cPlain, -2, 0.01) && near(cRef, -4, 0.01)
    && stated(['2ε − (8/3)ε²', '2ε − 2ε²', '2ε − 4ε²']), `${cExact.toFixed(3)}, ${cPlain.toFixed(3)}, ${cRef.toFixed(3)}`);
  check('at R0 = 1.1: exact 17.6%, plain 18.2%, refined 16.5%', p1(2 * L11.hit * (1 - L11.hit)) === '16.5%' && stated(['exact 17.6%', 'plain 18.2%', 'refined 16.5%']));

  // ---------------------------------------------------------------- 2. the damping floor
  let floorOk = true, floorDetail = [];
  for (const f of [0, 0.25, 0.5, 0.6, 0.9]) {
    const b = E.bestSingleDamp(2.5, f);
    floorOk &&= b.everInfected > 0.6;
    floorDetail.push(`${f}: ${(100 * b.everInfected).toFixed(2)}%`);
  }
  check('no temporary damping at R0 = 2.5 ends below the 60% threshold (1,600 timings at each of 5 strengths)', floorOk, floorDetail.join(', '));
  const b60 = E.bestSingleDamp(2.5, 0.6);
  check('at 60% strength the best timing found ends at 60.01%', (100 * b60.everInfected).toFixed(2) === '60.01' && stated(['60% strength', '60.01%']), `${(100 * b60.everInfected).toFixed(3)}%`);
  const exact = E.withDamping(2.5, { start: 4, len: 6, factor: 0.5 });
  const long = E.sir(2.5, { tMax: 400, dt: 0.01, every: 1e9, damp: { start: 4, end: 10, factor: 0.5 } });
  check('the exact end state after a damping matches a long simulation', near(exact.everInfected, long.everInfected, 1e-5), `${exact.everInfected.toFixed(6)} vs ${long.everInfected.toFixed(6)}`);
  check('the page says 1,600 timings, and the search tries 40 x 40', stated(['1,600 timings']) && /bestSingleDamp\(R0, factor, \{ starts = 40, lens = 40/.test(engineSrc));

  // ---------------------------------------------------------------- 3. the table
  const T = E.TABLE_IX;
  check('Table IX: 52 weeks in each of the three columns', T.deaths.length === 52 && T.rattus.length === 52 && T.decumanus.length === 52);
  const interleaved = []; for (let k = 0; k < 52; k++) interleaved.push(T.deaths[k], T.rattus[k], T.decumanus[k]);
  interleaved.push(177, 102.0, 323.9);
  const same = interleaved.length === OCR.length && interleaved.every((v, k) => Math.abs(v - OCR[k]) < 1e-9);
  const firstDiff = interleaved.findIndex((v, k) => Math.abs(v - OCR[k]) > 1e-9);
  check('Table IX as transcribed = the Internet Archive OCR of p. 753, all 156 values and the 3 printed means', same, same ? `${OCR.length} numbers` : `first difference at ${firstDiff}: ${interleaved[firstDiff]} vs ${OCR[firstDiff]}`);
  const m = (a) => E.mean(a);
  check('printed means: deaths 177 (column 177.3), black rats 102.0 (column 102.1)', m(T.deaths).toFixed(1) === '177.3' && m(T.rattus).toFixed(1) === '102.1' && stated(['177.3', '102.1']));
  check('printed mean for the brown rats 323.9, column 322.9, a difference of exactly one', m(T.decumanus).toFixed(1) === '322.9' && near(T.printedMeans.decumanus - m(T.decumanus), 1, 0.05) && stated(['323.9', '322.9']));
  check('the 52 weeks of deaths add up to 9,219; the report gives 11,010 for the island', E.sum(T.deaths) === 9219 && E.REPORT.deathsYear === 11010 && stated(['9,219', '11,010']));
  check('census density: 977,822 over 14,385.89 acres is 67.97 per acre, as printed', (E.REPORT.census1906 / E.REPORT.acres).toFixed(2) === '67.97');
  check('the table itself: fewest deaths 5 in 19 to 25 November, most 925 in 22 to 28 April',
    Math.min(...T.deaths) === 5 && E.weekStart(T.deaths.indexOf(5)) === '1905-11-19' && E.weekStart(T.deaths.indexOf(925)) === '1906-04-22');
  const rt = T.rattus;
  const localPeaks = rt.map((v, k) => (k > 0 && k < 51 && v > rt[k - 1] && v > rt[k + 1] && v > 400 ? E.weekStart(k) : null)).filter(Boolean);
  check('the black-rat column has two peaks, in the weeks of 11 March and 15 April', JSON.stringify(localPeaks) === '["1906-03-11","1906-04-15"]' && stated(['11 March', '15 April']), localPeaks.join(', '));

  // ---------------------------------------------------------------- 4. the 1927 curve
  const win = E.kmWindow();
  check('their window: 31 weeks, 17 December 1905 to 21 July 1906', win.length === 31 && win[0].start === '1905-12-17' && win.at(-1).end === '1906-07-21');
  check('the 31 weeks hold 8,859 deaths; the curve over all time holds 8,900', E.sum(win.map((w) => w.deaths)) === 8859 && 2 * E.KM.A / E.KM.B === 8900 && stated(['8,859', '8,900']));
  const at = (t) => win.find((w) => w.t === t)?.deaths;
  check('registered as their figure is: 17 December at t = 1, 925 at t = 19, 702 and 695 at 16 and 17, 779 at 15, 870 at 18',
    win[0].t === 1 && at(19) === 925 && at(16) === 702 && at(17) === 695 && at(15) === 779 && at(18) === 870 && stated(['sits at t = 1', '925 at about t = 19', '16 and 17']));
  check('the curve peaks at t = 17, two weeks before the table', E.KM.phi / E.KM.B === 17 && at(19) === Math.max(...win.map((w) => w.deaths)) && stated(['peaks at t = 17, two weeks before']));
  check('the deaths rise to 779, dip to 702 and 695, then climb to 925', win[14].deaths === 779 && stated(['779', '702 and 695', '925']));
  const B = E.bestFit(win), ratio = B.sse / E.sse(win, 890, 0.2, 3.4);
  // an independent least-squares search: coarse grid then the engine's answer must be no worse than the grid's best
  let grid = Infinity; for (let A = 800; A <= 950; A += 5) for (let b = 0.15; b <= 0.25; b += 0.0025) for (let ph = 2.6; ph <= 4.2; ph += 0.02) grid = Math.min(grid, E.sse(win, A, b, ph));
  check('least squares cuts the squared error by about a quarter (ratio 0.7 to 0.8), and beats a brute-force grid', ratio > 0.7 && ratio < 0.8 && B.sse <= grid + 1e-6 && stated(['by about a quarter']), `ratio ${ratio.toFixed(3)}, grid ${grid.toFixed(0)} vs ${B.sse.toFixed(0)}`);

  // ---------------------------------------------------------------- 5. the inversion
  const bac = [[1, 57368, 1.6, 1.09], [2, 35439, 3.0, 1.17], [3, 28202, 4.3, 1.24]]; // Bacaer 2012, Table 1
  let tabOk = true;
  const got = [];
  for (const [y0, x0, d, r0] of bac) { const v = E.invertFromY0(y0); got.push(Math.round(v.x0)); tabOk &&= Math.abs(Math.round(v.x0) - x0) <= 1 && v.infectiousDays.toFixed(1) === d.toFixed(1) && v.R0.toFixed(2) === r0.toFixed(2); }
  tabOk &&= got[0] === 57368 && got[1] === 35439 && got[2] === 28203 && stated(['28,203', '28,202']);
  check("Bacaer's Table 1 reproduced (x0 57,368 / 35,439 / 28,203 against his 28,202; 1.6 / 3.0 / 4.3 days; R0 1.09 / 1.17 / 1.24)", tabOk
    && stated(['57,368', '1.6 days', '1.09']) && stated(['35,439', '3.0 days', '1.17']) && stated(['28,202', '4.3 days', '1.24']));
  const w890 = E.invertFromX0(1e6), w989 = E.invertFromX0(1e6, 890 / 0.9);
  check('whole island with A = 890: R0 about 224 with about 496,000 first cases, or 1.0045 with 0.045',
    Math.round(w890[0].R) === 224 && Math.round(w890[0].y0 / 1000) === 496 && w890[1].R.toFixed(4) === '1.0045' && w890[1].y0.toFixed(3) === '0.045' && stated(['224', '496,000', '1.0045', '0.045']));
  check("with A = 890/0.9 the roots are Bacaer's: 202 and 446,000, or 1.005 and 0.06", Math.round(w989[0].R) === 202 && Math.round(w989[0].y0 / 1000) === 446
    && w989[1].R.toFixed(3) === '1.005' && w989[1].y0.toFixed(2) === '0.06' && stated(['202 and 446,000', '1.005 and 0.06']));
  const y989 = E.invertFromY0(1, 989);
  check("and his rescaled y0 = 1 case (x0 about 69,183, 1.5 days, R0 1.08) comes out with A = 989", Math.abs(y989.x0 - 69183) < 20 && y989.infectiousDays.toFixed(1) === '1.5' && y989.R0.toFixed(2) === '1.08', `${y989.x0.toFixed(0)}`);
  const wi = E.wholeIsland();
  check('whole island: R0 = 1.0063 from 12,245 attacks among 977,822', wi.R0.toFixed(4) === '1.0063' && stated(['R0 comes out at 1.0063'])
    && stated(['12,245 plague attacks']) && stated(['counted 977,822 people']) && E.REPORT.attacksYear === 12245);
  check('the deaths doubled about every 13.5 days from 17 December to 24 March', wi.doublingDays.toFixed(1) === '13.5' && E.weekStart(24) === '1906-03-18' && stated(['13.5 days', '17 December to 24 March']));
  check('each case infectious for about three hours (SIR: T = (R0 - 1)/r)', wi.Thours > 2.5 && wi.Thours < 3.5 && stated(['about three hours']), `${wi.Thours.toFixed(2)} h`);
  // fixed-duration infection: R0 = rT / (1 - exp(-rT)); solve for T
  let lo = 1e-9, hi = 1; for (let k = 0; k < 200; k++) { const mT = (lo + hi) / 2, x = wi.rate * mT; (x / (1 - Math.exp(-x)) < wi.R0) ? (lo = mT) : (hi = mT); }
  const fixedHours = (lo + hi) / 2 * 7 * 24;
  check('with a fixed infectious period instead, about six hours', fixedHours > 5.5 && fixedHours < 6.5 && stated(['about six hours']), `${fixedHours.toFixed(2)} h`);
  const mx = Number((html.match(/id="pop"[^>]*max="([\d.]+)"/) || [])[1]);
  check('the population slider tops out at the census, 977,822', Math.abs(10 ** mx - 977822) < 1 && E.REPORT.census1906 === 977822, `${(10 ** mx).toFixed(1)}`);

  // ---------------------------------------------------------------- 6. dates and names in the prose
  check('Kermack and McKendrick quoted from pp. 715 to 716 and p. 715', text.includes('(1927), pp. 715 to 716') && text.includes('McKendrick (1927), p. 715'));
  check('Table IX is on page 753 of J. Hyg. 7 (1907)', stated(['page 753']) && T.source.includes('p. 753'));
  return { pass, fail };
}

const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const { pass, fail } = await suite(E);
console.log(`\n${pass} passed, ${fail} failed`);
let bad = fail > 0;

if (MUTATE) {
  const mutants = [
    ['final size replaced by twice the excess', [/export function finalSize\(R0\) \{/, 'export function finalSize(R0) { return Math.min(1, 2 * (1 - 1 / R0));']],
    ['one table entry changed (644 -> 664)', [/,442,644,779,/, ',442,664,779,']],
    ["the inversion's R off by a sign", [/const R = \(1 \+ Math\.sqrt/, 'const R = (1 - 1e-3 + Math.sqrt']],
    ['the damping end computed from the lift state as if nobody were infectious', [/if \(i1 <= 0\) return s1;/, 'return s1;']],
    ['the curve peaks a week late', [/phi: 3\.4, firstWeek/, 'phi: 3.6, firstWeek']],
    ['the growth window starts a week late', [/growthRate\(11, 24\)/, 'growthRate(12, 24)']],
  ];
  console.log('\n--mutate: each planted fault must turn at least one check red');
  const mdir = join(dir, '.mutants'); mkdirSync(mdir, { recursive: true });
  let k = 0;
  for (const [name, [re, rep]] of mutants) {
    if (!re.test(engineSrc)) { console.log(`FAIL mutant "${name}": pattern not found in engine`); bad = true; continue; }
    const f = join(mdir, `engine-${k++}.mjs`);
    writeFileSync(f, engineSrc.replace(re, rep));
    const M = await import(pathToFileURL(f).href);
    const r = await suite(M, { quiet: true });
    const caught = r.fail > 0;
    console.log(`${caught ? 'ok  ' : 'FAIL'} mutant caught: ${name}  (${r.fail} checks red)`);
    if (!caught) bad = true;
  }
}
process.exit(bad ? 1 : 0);
