#!/usr/bin/env node
// verify-how-much-deadlier-30-than-20.mjs
//
// Offline gate for /strata/how-much-deadlier-30-than-20/. It recomputes EVERY number the
// page shows, from the same closed-form equations and five sourced anchor points the page
// uses, and exits 0 only if all checks pass. Where possible each fact is verified two
// independent ways. No dataset download is required.
//
//   Tefft logistic fit   P = 1/(1+e^-(a+bv))   a=-4.857, b=0.115643/mph
//                         forced through 10% @ 23 mph and 50% @ 42 mph
//   age-specific model   logit += kA*(age-40) + kB*(age-40)*v  (shifts AND steepens the curve;
//                         calibrated so a 70-year-old reads ~13% @20 mph and ~70% @40 mph, per ProPublica)
//   Rosen & Sander 2009  aR=-6.9, bR=0.090*1.609344/mph  (published equation (2))
//   outdated 1970s       aT=-10.749, bT=0.31209/mph  (20% @30, 85% @40 mph) ILLUSTRATIVE GHOST ONLY
//   stopping coupling    d = v*t_r + v^2/(2a);  v_res = sqrt(max(0, v^2 - 2a*(d - v*t_r)))
//   kinetic energy       KE proportional to v^2, so (30/20)^2 = 2.25
//
// Run:  node research/how-much-deadlier-30-than-20/verify-how-much-deadlier-30-than-20.mjs

'use strict';

// ---- model constants (identical to the page's inline JS) --------------------------
const A = -4.857, B = 0.115643;      // Tefft fit, per mph
const C_AGE_A = 0.006926154, C_AGE_B = 0.000725661, AGE0 = 40;  // age: shift + steepen the logit
const AR = -6.9, BR = 0.090 * 1.609344; // Rosen & Sander 2009, equation (2), converted to per mph
const AT = -10.749, BT = 0.31209;    // outdated 1970s THINK! illustration, per mph
const MPH2MS = 0.44704, G = 9.81;

const logistic = (v, a, b) => 1 / (1 + Math.exp(-(a + b * v)));
const logit = (p) => Math.log(p / (1 - p));
const pTefft = (v, age = AGE0) => { const g = age - AGE0; return 1 / (1 + Math.exp(-((A + C_AGE_A * g) + (B + C_AGE_B * g) * v))); };
const pRosen = (v) => logistic(v, AR, BR);
const pThink = (v) => logistic(v, AT, BT);
const impactRisk = (v, curve = pTefft) => v <= 0 ? 0 : curve(v);
const stopDist = (vmph, tr, a) => { const v = vmph * MPH2MS; return v * tr + v * v / (2 * a); };
function residMph(vmph, tr, a, d) {
  const v = vmph * MPH2MS, react = v * tr, braked = d - react;
  if (braked <= 0) return vmph;
  const v2 = v * v - 2 * a * braked;
  return v2 <= 0 ? 0 : Math.sqrt(v2) / MPH2MS;
}

// Tefft's five published anchor cells (AAA Foundation 2011): speed mph -> risk of death
const ANCHORS = [[23, 0.10], [32, 0.25], [42, 0.50], [50, 0.75], [58, 0.90]];

// ---- harness ----------------------------------------------------------------------
let pass = 0, fail = 0;
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  PASS  ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${detail ? '  ' + detail : ''}`); }
}
const pc = (p) => (p * 100).toFixed(1) + '%';

console.log('how-much-deadlier-30-than-20 :: offline verifier');
console.log(`Tefft fit  a=${A}  b=${B}/mph  (P = 1/(1+e^-(a+bv)))`);
console.log('');

// [0] the fit constants really are forced through the two named anchors (independent re-derivation)
console.log('[0] fit is forced through 10% @23 mph and 50% @42 mph');
{
  const bDer = (logit(0.50) - logit(0.10)) / (42 - 23);
  const aDer = logit(0.50) - bDer * 42;
  check('re-derived b from anchors = 0.115643', approx(bDer, B, 5e-6), `b=${bDer.toFixed(6)}`);
  check('re-derived a from anchors = -4.857', approx(aDer, A, 5e-4), `a=${aDer.toFixed(4)}`);
  check('fit passes exactly through 10% @23 mph', approx(pTefft(23), 0.10, 1e-3), pc(pTefft(23)));
  check('fit passes exactly through 50% @42 mph', approx(pTefft(42), 0.50, 1e-3), pc(pTefft(42)));
}

// [1] the fit reproduces Tefft's OTHER three published anchors within tolerance
console.log('\n[1] fit reproduces the other published anchors (24-25 @32, 71-72 @50, 86-90 @58)');
{
  check('32 mph -> ~24% (published 25%)', approx(pTefft(32), 0.24, 0.015), pc(pTefft(32)));
  check('50 mph -> ~72% (published 75%)', approx(pTefft(50), 0.716, 0.02), pc(pTefft(50)));
  check('58 mph -> ~86% (published 90%; 2-param fit under-reads the tail)', pTefft(58) >= 0.855 && pTefft(58) <= 0.90, pc(pTefft(58)));
  // every anchor within 4.5 points (the page's audit tolerance)
  let worst = 0;
  for (const [v, pub] of ANCHORS) worst = Math.max(worst, Math.abs(pTefft(v) - pub) * 100);
  check('every published anchor reproduced within 4.5 points', worst <= 4.5, `worst gap = ${worst.toFixed(2)} pts`);
}

// [2] the headline: 20 vs 30 mph is ~2.7x (about 3x), NOT 4x, on the US average adult curve
console.log('\n[2] headline ratio 30 vs 20 mph on the US average adult curve');
{
  const p20 = pTefft(20), p30 = pTefft(30), ratio = p30 / p20;
  check('20 mph -> ~7% (1 in 14)', approx(p20, 0.073, 0.005), pc(p20) + '  1 in ' + Math.round(1 / p20));
  check('30 mph -> ~20% (1 in 5)', approx(p30, 0.20, 0.006), pc(p30) + '  1 in ' + Math.round(1 / p30));
  check('ratio is ~2.7x (in [2.6, 2.9], "about 3x")', ratio >= 2.6 && ratio <= 2.9, `ratio=${ratio.toFixed(3)}x`);
  check('ratio is NOT 4x on the US average adult curve', ratio < 3.5 && Math.abs(ratio - 4) > 0.5, `ratio=${ratio.toFixed(2)}x`);
  // independent: the gap 20->30 exceeds the gap 10->20 (convexity through the band)
  check('gap(20->30) > gap(10->20): the curve steepens', (p30 - p20) > (p20 - pTefft(10)), `dP=${((p30 - p20) * 100).toFixed(1)} vs ${((p20 - pTefft(10)) * 100).toFixed(1)} pts`);
}

// [3] AGE model (shift + steepen): ProPublica's reads, and the 20-vs-30 ratio EDGES UP with age
console.log('\n[3] age model reproduces ProPublica reads and steepens the curve with age');
{
  check('30-year-old at 40 mph -> ~36%', approx(pTefft(40, 30), 0.36, 0.01), pc(pTefft(40, 30)));
  check('70-year-old at 20 mph -> ~13% (ProPublica: 87% survive)', approx(pTefft(20, 70), 0.13, 0.01), pc(pTefft(20, 70)));
  check('70-year-old at 40 mph -> ~70%', approx(pTefft(40, 70), 0.70, 0.015), pc(pTefft(40, 70)));
  check('age 40 reproduces the population-average curve', approx(pTefft(20, 40), pTefft(20), 1e-9) && approx(pTefft(30, 40), pTefft(30), 1e-9), 'shift = 0 at age 40');
  const r30 = pTefft(30, 30) / pTefft(20, 30), r40 = pTefft(30) / pTefft(20), r70 = pTefft(30, 70) / pTefft(20, 70);
  check('the 20-vs-30 ratio EDGES UP with age (older = steeper curve, matches the prose)', r70 > r40 && r40 > r30, `30yr ${r30.toFixed(2)}x < 40yr ${r40.toFixed(2)}x < 70yr ${r70.toFixed(2)}x`);
  check('older ratio stays "about 3x" (nearer 2.9x, NOT 4x)', r70 >= 2.6 && r70 < 3.0, `age70 ratio=${r70.toFixed(3)}x`);
  check('older pedestrian absolute risk far exceeds a 30-year-old at 30 mph', pTefft(30, 70) > pTefft(30, 30) + 0.15, `70yr=${pc(pTefft(30, 70))} vs 30yr=${pc(pTefft(30, 30))}`);
}

// [4] studies disagree on the ABSOLUTE number by ~2-3x, agree on the shape
console.log('\n[4] Tefft vs Rosen & Sander: absolute risk disagrees by ~2-3x at 30 mph');
{
  // Equation (2) uses km/h; these independently evaluated probabilities check its mph conversion.
  for (const [mph, expected] of [[20, 0.017930114478468182], [30, 0.07210660507615552], [40, 0.24854982085484273], [50, 0.584687920684721]]) {
    check(`Rosen equation (2) at ${mph} mph`, approx(pRosen(mph), expected, 1e-12), pc(pRosen(mph)));
  }
  check('Rosen ~7-10% at 50 km/h (31 mph)', pRosen(31.07) >= 0.07 && pRosen(31.07) <= 0.10, pc(pRosen(31.07)));
  const disagree = pTefft(30) / pRosen(30);
  check('US vs German absolute risk at 30 mph differs by ~2-3x', disagree >= 2 && disagree <= 3.2, `Tefft ${pc(pTefft(30))} / Rosen ${pc(pRosen(30))} = ${disagree.toFixed(2)}x`);
  // agree on the shape: both convex and steep in the band
  check('both curves are convex through 20-40 mph (steepen)', (pTefft(40) - pTefft(30)) > (pTefft(30) - pTefft(20)) && (pRosen(40) - pRosen(30)) > (pRosen(30) - pRosen(20)), 'shape agrees');
}

// [5] KE ratio is exactly 2.25
console.log('\n[5] kinetic energy (30/20)^2 = 2.25 exactly');
{
  check('(30/20)^2 = 2.25 exactly', (30 * 30) / (20 * 20) === 2.25, '= 2.25');
}

// [6] stopping-distance coupling (dry a = 6.6 m/s^2 ~ 0.67 g)
console.log('\n[6] coupling: from a shared sight line the faster car is still moving');
{
  const a = 6.6;
  const sA10 = stopDist(20, 1.0, a);
  check('20 mph stops in ~15 m (t_r=1.0, a=6.6)', approx(sA10, 15, 0.2), `${sA10.toFixed(2)} m`);
  const rB10 = residMph(30, 1.0, a, 15);
  check('30 mph residual speed at 15 m is ~28 mph', approx(rB10, 28.2, 0.6), `${rB10.toFixed(1)} mph`);
  // independent residual via the page's v_res formula
  const vB = 30 * MPH2MS, rB10b = Math.sqrt(Math.max(0, vB * vB - 2 * a * (15 - vB * 1.0))) / MPH2MS;
  check('residual matches v_res = sqrt(v^2 - 2a(d - v*t_r)) (two ways)', approx(rB10, rB10b, 1e-9), `${rB10b.toFixed(1)} mph`);
  // distracted 1.5 s: 30 mph reaction distance alone exceeds the 20 mph total stop
  const react30 = 30 * MPH2MS * 1.5, stop20 = stopDist(20, 1.5, a);
  check('t_r=1.5: 30 mph reaction dist exceeds 20 mph total stop', react30 > stop20, `react=${react30.toFixed(1)} m vs stop=${stop20.toFixed(1)} m`);
  check('=> 30 mph impact at t_r=1.5 is the full 30 mph', approx(residMph(30, 1.5, a, stop20), 30, 1e-6), `${residMph(30, 1.5, a, stop20).toFixed(1)} mph`);
}

// [7] feed the residual/impact speeds back through the fatality curve
console.log('\n[7] impact speed feeds the risk: clean stop -> 0%, ~28 mph -> ~17%');
{
  const rA = residMph(20, 1.0, 6.6, 15);
  check('a clean stop without contact yields exactly 0% collision fatality risk', rA === 0 && impactRisk(rA) === 0, pc(impactRisk(rA)));
  check('a positive residual speed still uses the impact-conditioned curve', impactRisk(0.25) === pTefft(0.25) && impactRisk(0.25) > 0, pc(impactRisk(0.25)));
  const rB = residMph(30, 1.0, 6.6, 15);
  const riskB = pTefft(rB);
  check('~28 mph strike yields ~17% risk (spec "~18%")', approx(riskB, 0.17, 0.03), `${rB.toFixed(1)} mph -> ${pc(riskB)}`);
  check('the residual-speed risk is far below the full-30-mph risk of ~20%', riskB < pTefft(30), `${pc(riskB)} < ${pc(pTefft(30))}`);
}

// [8] ASSERT ABSENCE: the outdated 1970s figures are only a ghost, never a current estimate
console.log('\n[8] absence: the outdated 1970s figures are an illustrative ghost');
{
  check('THINK! ghost reproduces its illustrative 85% @40 mph', approx(pThink(40), 0.85, 0.01), pc(pThink(40)));
  check('the page never USES 85% at 40 mph: Tefft@40 is ~44%, not ~85%', approx(pTefft(40), 0.442, 0.01) && pTefft(40) < 0.55, 'Tefft@40 ' + pc(pTefft(40)));
  check('the page never USES 20% at 30 mph FROM THINK: Tefft@30 (~20%) is coincidental, THINK is steeper', pThink(20) < pTefft(20), `THINK@20 ${pc(pThink(20))} < Tefft@20 ${pc(pTefft(20))}`);
  // Scan the shipped HTML for the dated acknowledgment label.
  try {
    const fs = await import('node:fs');
    const url = new URL('../../public/strata/how-much-deadlier-30-than-20/index.html', import.meta.url);
    const html = fs.readFileSync(url, 'utf8');
    const hasGhostLabel = /var txt = 'DfT: overstated \(2010\)'/.test(html) && /THINK/.test(html);
    check('shipped page dates the DfT acknowledgment to 2010', hasGhostLabel);
    // The 85% figure appears only as the outdated/1970s figure in prose.
    const claims85 = /85%[^<]{0,40}(risk|chance|probability) of death/i.test(html);
    check('no prose claims 85% as the page\'s own risk of death', !claims85);
  } catch (e) {
    check('shipped HTML must be readable', false, String(e && e.message));
  }
}

// [9] Execute the served inline script with DOM and canvas-text stand-ins; no browser rendering.
console.log('\n[9] served-page German values and collision/no-collision outputs');
{
  const { readFileSync } = await import('node:fs');
  const { runInNewContext } = await import('node:vm');
  function loadPage(html) {
    const elements = new Map();
    function element(id = '') {
      const labels = [];
      const canvas = new Proxy({
        clearRect() { labels.length = 0; },
        fillText(text) { labels.push(text); },
        measureText(text) { return { width: text.length * 6 }; }
      }, { get(target, key) { return target[key] ?? (() => {}); } });
      return {
        id, value: '', style: {}, textContent: '', children: [], handlers: {}, labels,
        clientWidth: 720, classList: { toggle() {} },
        set innerHTML(value) { this.markup = value; this.children = []; },
        get innerHTML() { return this.markup ?? ''; },
        appendChild(child) { this.children.push(child); },
        getElementsByTagName() { return [this.tbody ??= element()]; },
        getContext() { return canvas; },
        setAttribute() {},
        addEventListener(type, fn) { (this.handlers[type] ??= []).push(fn); },
        fire(type, value) {
          if (value !== undefined) this.value = String(value);
          for (const fn of this.handlers[type] ?? []) fn.call(this, { target: this });
        }
      };
    }
    for (const [, id] of html.matchAll(/\bid="([^"]+)"/g)) elements.set(id, element(id));
    const document = {
      readyState: 'complete', body: {},
      getElementById(id) {
        if (!elements.has(id)) throw new Error('Missing element: ' + id);
        return elements.get(id);
      },
      createElement() { return element(); }
    };
    // The served page also carries the site's own injected scripts (worker.js adds a page-count pulse before
    // this one), so take the layer's script by what it drives, not by being the first inline script.
    const script = [...html.matchAll(/<script>\s*([\s\S]*?)\s*<\/script>/g)].map((m) => m[1])
      .find((s) => /^\(function\s*\(\)\s*\{/.test(s) && s.includes('runcheck'));
    if (!script) throw new Error('Layer script missing');
    runInNewContext(script, {
      document,
      window: { matchMedia: () => ({ matches: true }), devicePixelRatio: 1, addEventListener() {} }
    }, { timeout: 1000 });
    return id => document.getElementById(id);
  }
  try {
    const html = readFileSync(new URL('../../public/strata/how-much-deadlier-30-than-20/index.html', import.meta.url), 'utf8');
    const $ = loadPage(html);
    const cells = $('cmp-body').children.map(row => row.innerHTML.match(/class="r">(.*?)</)?.[1]);
    check('served German table uses equation (2) at 20/30/40/50 mph and for its ratio',
      JSON.stringify(cells) === JSON.stringify(['1.8%', '7.2%', '24.9%', '58.5%', '4.0x']), cells.join(', '));
    check('default accessible summary reports a clean stop without contact and 0% risk',
      $('street-alt').textContent.includes('20 mph car stops without contact (0% collision fatality risk)') &&
      !$('street-alt').textContent.includes('strikes at 0 mph'), $('street-alt').textContent);
    check('default visible readout agrees on the clean stop', $('impAsub').textContent === 'stopped without contact: 0% risk');
    check('default impact annotation reports A stopped at 0%', $('curve').labels.includes('A stopped: 0%'));
    check('positive default impact still reports 28 mph and 17% risk',
      $('impB').textContent === '28 mph' && $('impBsub').textContent === 'about 17% risk');
    $('runcheck').fire('click');
    check('served self-check requires and reports exactly zero for the clean stop',
      $('checkout').innerHTML.includes('clean stop => exactly 0% collision fatality risk  0.0%') &&
      $('checkout').innerHTML.includes('ALL CHECKS PASS') && !$('checkout').innerHTML.includes('FAIL'));
    for (const study of ['rosen', 'think', 'tefft']) {
      $('study-' + study).fire('click');
      check(`clean stop remains zero with ${study} selected`,
        $('street-alt').textContent.includes('20 mph car stops without contact (0% collision fatality risk)') &&
        $('curve').labels.includes('A stopped: 0%'));
    }
    $('age').fire('input', 70);
    check('clean stop remains zero for an older pedestrian', $('impAsub').textContent === 'stopped without contact: 0% risk');
    $('age').fire('input', 40);
    $('dist').fire('input', 40);
    check('both stopped cars have no contact in the accessible summary',
      ($('street-alt').textContent.match(/stops without contact/g) || []).length === 2);
    check('both stopped cars have zero-risk calculation annotations',
      ($('check-calc').textContent.match(/stops without impact: 0% risk/g) || []).length === 2);
    // An available slider setting gives a positive residual below 0.5 mph. It must not be called a stop.
    $('spdA').fire('input', 10);
    $('dist').fire('input', 5);
    $('react').fire('input', 0.78);
    check('small positive impact is not mislabeled a clean stop',
      $('impA').textContent === 'under 1 mph' && $('impAsub').textContent === 'about 1% risk' &&
      $('street-alt').textContent.includes('10 mph car strikes at under 1 mph (about 1% risk)'));
  } catch (error) {
    check('served inline script must execute for the regression checks', false, error.message);
  }
}

// ---- summary ----------------------------------------------------------------------
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
