#!/usr/bin/env node
// verify.mjs — recompute every number the shipped page states, from the source
// grid, and refuse to pass if any of them has drifted by a digit.
//
//   node research/nobody-died-at-forty/verify.mjs
//   node research/nobody-died-at-forty/verify.mjs --list    # print key -> value
//
// The page marks each of its stated numbers with data-check="<key>". This file
// owns the other end of every key: an independent re-derivation and the exact
// string the page is allowed to print. Both directions are enforced, so a number
// cannot be added to the page without a check, and a check cannot rot in here
// after the sentence around it is deleted.
//
// It then runs negative controls: deliberately broken inputs that the machinery
// must reject. A check that cannot fail is not a check.

import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  loadQx, hazard, lifeTable, gompertz, modalAge, medianAge,
  equivalentAge, safestAge, exactMatches,
} from './lib.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '..', '..', 'public', 'strata', 'nobody-died-at-forty', 'index.html');

const data = loadQx();
const { years } = data;
const Y0 = years[0], Y1 = years[years.length - 1];
const TOP = 100;
const FIT = [35, 85];

/* ------------------------------------------------------------- derivations */
const tab = {};
const T = (sex, year) => (tab[sex + year] ||= lifeTable(data, sex, year));
const G = {};
const fitOf = (sex, year, a0 = FIT[0], a1 = FIT[1]) => (G[[sex, year, a0, a1]] ||= gompertz(data, sex, year, a0, a1));
const share = (sex, year, a0, a1) => T(sex, year).d.slice(a0, a1 + 1).reduce((s, v) => s + v, 0);
const ratio = (sex, age) => hazard(data.q(sex, age, Y0)) / hazard(data.q(sex, age, Y1));
const pct = (v, n = 1) => (v * 100).toFixed(n) + '%';
const comma = (n) => n.toLocaleString('en-US');

function extremes(sex) {
  let min = null, max = null;
  for (const y of years) {
    const v = fitOf(sex, y).mrdt;
    if (!min || v < min.v) min = { y, v };
    if (!max || v > max.v) max = { y, v };
  }
  return { min, max };
}
function peakRatio(sex) {
  let best = { a: 1, r: 0 };
  for (let a = 1; a <= 95; a++) { const r = ratio(sex, a); if (r > best.r) best = { a, r }; }
  return best;
}
function safestModern(sex) {
  const s = safestAge(data, sex, Y0, TOP);
  for (let a = 0; a <= TOP; a++) {
    const m = hazard(data.q(sex, a, Y1));
    if (m !== null && m > s.mu) return { safest: s.age, lastSafer: a - 1 };
  }
  return { safest: s.age, lastSafer: TOP };
}
function hybridE0(sex, cut, below, above, maxAge = 110) {
  let alive = 1, total = 0;
  for (let a = 0; a <= maxAge; a++) {
    const qq = a === maxAge ? 1 : data.q(sex, a, a < cut ? below : above);
    const de = alive * qq;
    total += alive - 0.5 * de;
    alive -= de;
  }
  return total;
}
function decomp(sex, cut) {
  const e0 = T(sex, Y0).e[0], e1 = T(sex, Y1).e[0];
  const childOnly = hybridE0(sex, cut, Y1, Y0);
  const adultOnly = hybridE0(sex, cut, Y0, Y1);
  return { childOnly, adultOnly, childShare: (childOnly - e0) / (e1 - e0), adultShare: (adultOnly - e0) / (e1 - e0), gain: e1 - e0 };
}
// The fit-free steepness measure: one cell of the table over another, no regression.
const PAIRS = [[40, 80], [50, 80], [35, 85], [60, 90], [45, 75], [30, 70]];
const steep = (sex, year, a, b) => hazard(data.q(sex, b, year)) / hazard(data.q(sex, a, year));
function steepPeak(sex, a, b) {
  let peak = { year: Y0, v: steep(sex, Y0, a, b) };
  for (const y of years) { const v = steep(sex, y, a, b); if (v > peak.v) peak = { year: y, v }; }
  return peak;
}
function steepCount() {
  let n = 0, total = 0;
  for (const sex of ['m', 'f']) for (const [a, b] of PAIRS) {
    total++;
    if (steep(sex, Y1, a, b) > steep(sex, Y0, a, b)) n++;
  }
  return `${n} of ${total}`;
}

const WINDOWS = [[30, 80], [35, 85], [40, 90], [50, 90], [60, 90], [65, 85], [70, 90], [45, 75]];
function sweepShorter() {
  let n = 0, total = 0;
  for (const sex of ['m', 'f']) for (const [a0, a1] of WINDOWS) {
    total++;
    if (fitOf(sex, Y1, a0, a1).mrdt < fitOf(sex, Y0, a0, a1).mrdt) n++;
  }
  return `${n} of ${total}`;
}
function closureAge(sex = 'm') {
  for (let a = 100; a <= 125; a++) {
    let all = true;
    for (const y of years) if (data.per100k(sex, a, y) < 1e5) { all = false; break; }
    if (all) return a;
  }
  return null;
}
const forensicCache = {};
function forensic(sex) {
  if (forensicCache[sex]) return forensicCache[sex];
  const pre = exactMatches(data, sex, Y0, 1910, TOP);
  const post = exactMatches(data, sex, 1911, Y1, TOP);
  const runs = (list) => list.filter((p) => p.runs.some((r) => r[1] - r[0] >= 3)).length;
  return (forensicCache[sex] = { prePairs: pre.length, preRuns: runs(pre), postPairs: post.length, postRuns: runs(post), pre });
}
function crossing(sex) {
  const a = fitOf(sex, Y0), b = fitOf(sex, Y1);
  return (b.lnA - a.lnA) / (a.B - b.B);
}
const equiv = (sex, age) => equivalentAge(data, sex, age, Y1, Y0, TOP);

/* -------------------------------------------------------------- the checks */
const CHECKS = {
  'cells': () => comma(data.ages.length * years.length * 2),

  'm.1841.e0': () => T('m', Y0).e[0].toFixed(1),
  'm.1841.dUnder1': () => pct(share('m', Y0, 0, 0)),
  'm.1841.dUnder5': () => pct(share('m', Y0, 0, 4)),
  'm.1841.d35to44': () => pct(share('m', Y0, 35, 44)),
  'm.1841.mode': () => String(modalAge(T('m', Y0))),

  'm.1841.e5plus': () => (5 + T('m', Y0).e[5]).toFixed(1),
  'm.2016.e5plus': () => (5 + T('m', Y1).e[5]).toFixed(1),
  'm.gain.e5': () => (T('m', Y1).e[5] - T('m', Y0).e[5]).toFixed(1),
  'm.1841.die20to40': () => pct((T('m', Y0).l[20] - T('m', Y0).l[40]) / T('m', Y0).l[20]),
  'm.2016.die20to40': () => pct((T('m', Y1).l[20] - T('m', Y1).l[40]) / T('m', Y1).l[20]),
  'm.1841.reach65from20': () => pct(T('m', Y0).l[65] / T('m', Y0).l[20]),
  'm.2016.reach65from20': () => pct(T('m', Y1).l[65] / T('m', Y1).l[20]),
  'f.ratio.20': () => ratio('f', 20).toFixed(1),
  'm.ratio.20': () => ratio('m', 20).toFixed(1),

  'm.gain.e0': () => (T('m', Y1).e[0] - T('m', Y0).e[0]).toFixed(1),
  'm.decomp.5.childOnly': () => decomp('m', 5).childOnly.toFixed(1),
  'm.decomp.5.adultOnly': () => decomp('m', 5).adultOnly.toFixed(1),
  'm.decomp.5.childShare': () => Math.round(decomp('m', 5).childShare * 100) + '%',
  'm.decomp.5.adultShare': () => Math.round(decomp('m', 5).adultShare * 100) + '%',

  'm.1841.mrdt': () => fitOf('m', Y0).mrdt.toFixed(2),
  'm.2016.mrdt': () => fitOf('m', Y1).mrdt.toFixed(2),
  'm.mrdt.min': () => extremes('m').min.v.toFixed(2),
  'm.mrdt.min.year': () => String(extremes('m').min.y),
  'm.mrdt.max': () => extremes('m').max.v.toFixed(2),
  'm.mrdt.max.year': () => String(extremes('m').max.y),
  'sweep.shorter': () => sweepShorter(),

  'm.peak.ratio': () => String(Math.round(peakRatio('m').r)),
  'm.peak.age': () => String(peakRatio('m').a),
  'm.ratio.90b': () => ratio('m', 90).toFixed(1),
  'm.ratio.95b': () => ratio('m', 95).toFixed(1),

  'm.equiv.60': () => equiv('m', 60).toFixed(0),
  'm.equiv.70': () => equiv('m', 70).toFixed(1),
  'm.equiv.80': () => equiv('m', 80).toFixed(1),
  'm.equiv.90': () => equiv('m', 90).toFixed(1),
  'm.safest.age': () => String(safestModern('m').safest),
  'm.safest.mod': () => String(safestModern('m').lastSafer),

  'closure': () => String(closureAge('m')),
  'm.crossing': () => crossing('m').toFixed(0),

  'm.steep.first': () => steep('m', Y0, 40, 80).toFixed(1),
  'm.steep.last': () => steep('m', Y1, 40, 80).toFixed(1),
  'm.steep.peak': () => steepPeak('m', 40, 80).v.toFixed(1),
  'm.steep.peak.year': () => String(steepPeak('m', 40, 80).year),
  'steep.count': () => steepCount(),

  'pairs.pre': () => comma(((1910 - Y0 + 1) * (1910 - Y0)) / 2),
  'pairs.pre2': () => comma(((1910 - Y0 + 1) * (1910 - Y0)) / 2),
  'pairs.post': () => comma(((Y1 - 1911 + 1) * (Y1 - 1911)) / 2),
  'pairs.post2': () => comma(((Y1 - 1911 + 1) * (Y1 - 1911)) / 2),
  'pairs.post3': () => comma(((Y1 - 1911 + 1) * (Y1 - 1911)) / 2),
};
for (const sex of ['m', 'f']) {
  for (const a of [1, 5, 10, 30, 40, 50, 60, 70, 80, 90, 95]) {
    CHECKS[`${sex}.ratio.${a}`] = () => (a <= 10 ? String(Math.round(ratio(sex, a))) : ratio(sex, a).toFixed(1));
  }
  CHECKS[`${sex}.ratio.20b`] = () => ratio(sex, 20).toFixed(1);
  for (const k of ['prePairs', 'preRuns', 'postPairs', 'postRuns']) {
    CHECKS[`${sex}.forensic.${k}`] = () => String(forensic(sex)[k]);
  }
}

/* ------------------------------------------------------------- the compare */
function pageValues(html) {
  const out = new Map();
  const re = /data-check="([^"]+)"[^>]*>([^<]*)</g;
  let m;
  while ((m = re.exec(html))) out.set(m[1], m[2].replace(/&nbsp;/g, ' ').trim());
  return out;
}

function run(html, { quiet = false } = {}) {
  const page = pageValues(html);
  const fails = [];
  for (const [key, got] of page) {
    if (!(key in CHECKS)) { fails.push(`page states data-check="${key}" but verify.mjs owns no such key`); continue; }
    const want = String(CHECKS[key]());
    if (want !== got) fails.push(`${key}: page says "${got}", recomputation says "${want}"`);
  }
  for (const key of Object.keys(CHECKS)) {
    if (!page.has(key)) fails.push(`verify.mjs owns "${key}" but no sentence on the page uses it`);
  }
  if (!quiet) {
    console.log(`${page.size} marked numbers on the page, ${Object.keys(CHECKS).length} owned here`);
    for (const f of fails) console.log('  FAIL  ' + f);
  }
  return fails;
}

/* ----------------------------------------------------------- the structure */
function structural() {
  const fails = [];
  const say = (ok, msg) => { if (!ok) fails.push(msg); };

  say(years.length === 176 && Y0 === 1841 && Y1 === 2016, 'the grid is not 1841 to 2016');
  say(data.ages.length === 126, 'the grid does not carry ages 0 to 125');

  // Gompertz is a claim about the whole file, not about two years of it.
  let worst = 1, worstYear = null;
  for (const sex of ['m', 'f']) for (const y of years) {
    const r = fitOf(sex, y).r2;
    if (r < worst) { worst = r; worstYear = `${sex} ${y}`; }
  }
  say(worst > 0.95, `the straight line fails somewhere: worst R^2 ${worst.toFixed(4)} at ${worstYear}`);

  // The improvement falls with age: not monotonically, but by a wide margin end to end.
  for (const sex of ['m', 'f']) {
    say(ratio(sex, 5) > 10 * ratio(sex, 90), `${sex}: the age-5 improvement is not an order of magnitude above the age-90 one`);
  }

  // The forensic split is the whole claim in section three.
  for (const sex of ['m', 'f']) {
    const f = forensic(sex);
    say(f.postRuns === 0, `${sex}: a post-1911 year-pair shares a run of four ages`);
    say(f.preRuns > 20, `${sex}: too few pre-1911 shared runs for the claim to hold`);
    const ends = new Set();
    for (const p of f.pre) for (const r of p.runs) if (r[1] - r[0] >= 3) { ends.add(r[0] % 10); ends.add(r[1] % 10); }
    const stray = [...ends].filter((d) => d !== 2 && d !== 7);
    say(stray.length === 0, `${sex}: a shared run begins or ends on age digit ${stray.join(',')}, not on a five-year band midpoint`);
  }

  // The two decomposition halves must overshoot 100% neither way.
  for (const sex of ['m', 'f']) {
    const d = decomp(sex, 5);
    say(d.childShare > 0.2 && d.childShare < 0.5, `${sex}: the child share is outside the range the page describes`);
    say(d.childShare + d.adultShare < 1, `${sex}: the two halves sum to more than the whole, which cannot be right`);
  }

  console.log(`${fails.length ? 'FAIL' : 'ok  '}  ${8 + 2 * 6} structural assertions`);
  for (const f of fails) console.log('  FAIL  ' + f);
  return fails;
}

/* --------------------------------------------------------- negative control */
function negatives(html) {
  const fails = [];
  const cases = [
    ['a changed digit in a stated number', html.replace('data-check="m.1841.mode">75<', 'data-check="m.1841.mode">76<')],
    ['a number marked with a key nobody owns', html.replace('data-check="closure"', 'data-check="closure.typo"')],
    ['a stated percentage silently rounded differently', html.replace('data-check="m.1841.dUnder5">27.3%<', 'data-check="m.1841.dUnder5">27%<')],
    ['a whole sentence deleted', html.replace(/data-check="m\.safest\.age">\d+</, 'x><')],
  ];
  for (const [name, mutated] of cases) {
    if (mutated === html) { fails.push(`negative control "${name}" did not actually mutate the page`); continue; }
    if (run(mutated, { quiet: true }).length === 0) fails.push(`negative control "${name}" was NOT caught`);
  }
  // and one against the data itself
  const saved = data.grids.m[data.ai.get(60)][data.yi.get(Y1)];
  data.grids.m[data.ai.get(60)][data.yi.get(Y1)] = saved * 2;
  for (const k of Object.keys(tab)) delete tab[k];
  for (const k of Object.keys(G)) delete G[k];
  const caught = run(html, { quiet: true }).length > 0;
  data.grids.m[data.ai.get(60)][data.yi.get(Y1)] = saved;
  for (const k of Object.keys(tab)) delete tab[k];
  for (const k of Object.keys(G)) delete G[k];
  if (!caught) fails.push('doubling the 2016 male death rate at age 60 did not break a single stated number');

  console.log(`${fails.length ? 'FAIL' : 'ok  '}  ${cases.length + 1} negative controls`);
  for (const f of fails) console.log('  FAIL  ' + f);
  return fails;
}

/* --------------------------------------------------------------------- run */
const html = readFileSync(PAGE, 'utf8');
if (process.argv.includes('--list')) {
  for (const k of Object.keys(CHECKS).sort()) console.log(k.padEnd(26), CHECKS[k]());
  process.exit(0);
}
const all = [...run(html), ...structural(), ...negatives(html)];
console.log(all.length ? `\nFAIL: ${all.length} problem(s)` : `\nPASS: every stated number recomputes, the structure holds, and the controls fire.`);
process.exit(all.length ? 1 : 0);
