// verify.mjs — the statistics and physics behind the stratum
// "The Man Lightning Kept Finding" (/strata/the-man-lightning-kept-finding/).
//
// SUBJECT. Roy Cleveland Sullivan (b. 7 Feb 1912, d. 28 Sep 1983), a US park
// ranger at Shenandoah National Park, is recognised by Guinness World Records
// as the person who survived the most DOCUMENTED lightning strikes: seven,
// between April 1942 and 25 June 1977. A famous, widely-repeated figure says the
// odds of that were "4.15 in 10^32" (about 1 in 2.4x10^31). THAT number is the thing
// this page corrects — not the record.
//
// THE CATEGORY ERROR. The "4.15 in 10^32" style figure multiplies a general-
// population strike probability by itself seven times, as if the seven events
// were seven independent draws from the average American's rate. That is the
// wrong model. Strikes accumulated over a lifetime of exposure are better modelled
// as a Poisson process with a PERSON-SPECIFIC rate lambda (strikes per year) set
// by exposure-hours x local flash density x terrain — not seven copies of a
// national average.
//
// What this script proves, offline and from scratch:
//   1. The general-population base rates the page quotes are mutually consistent:
//      the NWS annual odds (~1 in 1.22 million) reproduce the NWS 80-year
//      lifetime odds (~1 in 15,300). These are POPULATION AVERAGES.
//   2. The famous "impossible" figure is a naive-independence artifact: raising
//      an average person's 35-year strike probability to the 7th power lands at
//      ~1 in 6x10^31 (order 10^32) — the same species of astronomically tiny
//      number as the quoted "4.15 in 10^32", and the same wrong model.
//   3. The Poisson model the page computes live: for expected strikes m = lambda*T,
//        P(>=1) = 1 - e^-m,  P(>=2) = 1 - e^-m(1+m),
//        P(=7)  = e^-m m^7/7!,  P(>=7) = 1 - sum_{k=0..6} e^-m m^k/k!.
//      At the rate the record itself implies (lambda = 7/35 = 0.2/yr, m = 7),
//      P(>=1) ~ 99.9%, P(>=2) ~ 99.3%, and P(>=7) ~ 55%: a coin flip, not 4.15x10^-32.
//   4. A physical collection-area estimate (IEC 62305 method) for a person on
//      open ground gives lambda of order 1e-4/yr — hundreds of times an average
//      person's rate, yet still far below the record-implied 0.2/yr. The gap is
//      named on the page: elevated exposure DISSOLVES the "4.15 in 10^32" impossibility,
//      but seven strikes remains genuinely extraordinary (which is why it is a
//      world record).
//   5. The survival side: the NWS figure that ~90% of lightning-strike victims
//      survive supplies an illustrative per-strike probability. With independent
//      survival outcomes, P(survive all 7) = 0.9^7 ~ 47.8%, slightly below even.
//      The mechanism estimates do not establish conditional survival rates;
//      all lightning injury mechanisms can be fatal.
//   6. Selected expected strings appear somewhere in the shipped index.html.
//      This does not compare every prose occurrence or certify every claim.
//   7. Small-tail values agree with independent high-precision reference values,
//      and the actual inline script produces the expected preset readouts.
//
//   run:  node research/the-man-lightning-kept-finding/verify.mjs
//
// SOURCES for the asserted numbers:
//   - Guinness World Records, "Most lightning strikes survived" (Roy Sullivan,
//     seven strikes, 1942-1977).
//   - Wikipedia, "Roy Sullivan" (dates, strike list, verification caveats).
//   - US National Weather Service, lightning-odds pages: annual ~1 in 1,222,000;
//     80-year lifetime ~1 in 15,300; ~90% of strike victims survive.
//   - Cooper & Holle, "Mechanisms of Lightning Injury..." (casualty-distribution
//     estimates), via NWS / National Lightning Safety Council.
//   - IEC 62305 equivalent-collection-area method (Ad = pi*(3h)^2 for a point).
// No dependencies; node: builtins only. Coverage is limited to the checks below.

import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;
const rel = (a, b) => Math.abs(a - b) / Math.abs(b);

// ── Poisson helpers (the model the page computes live) ──────────────────────
function factorial(n) { let f = 1; for (let i = 2; i <= n; i++) f *= i; return f; }
function poissonPmf(k, m) { return Math.exp(-m) * Math.pow(m, k) / factorial(k); }
function pAtLeast1(m) { return -Math.expm1(-m); }
function pAtLeast2(m) { return pAtLeastK(2, m); }
function pAtLeastK(k, m) {
  // Sum a small upper tail directly: 1 - CDF loses it to cancellation.
  if (m < k) {
    let term = poissonPmf(k, m), tail = term;
    for (let i = k + 1; ; i++) {
      term *= m / i;
      const next = tail + term;
      if (next === tail) return tail;
      tail = next;
    }
  }
  let cdf = 0;
  for (let i = 0; i < k; i++) cdf += poissonPmf(i, m);
  return 1 - cdf;
}

// Independent reference values from an 80-digit Python Decimal sum of
// exp(-m) * m^n / n! for n >= k, stopping when the sum no longer changes.
// These cover both presets with formerly cancelled tails and both slider ends.
const tailReferences = [
  { name: 'average preset', lambda: 8.183306e-7,
    tails: [2.8641160834121267e-5, 4.1016196281994201e-10, 3.1371582592806901e-36] },
  { name: 'illustrative preset', lambda: 1.37e-4,
    tails: [0.0047835223399547017, 1.1459329574784494e-5, 1.1515098784749950e-20] },
  { name: 'slider minimum', lambda: 1 / 1222000,
    tails: [2.8641161028878373e-5, 4.1016196839809151e-10, 3.1371584086088926e-36] },
  { name: 'slider maximum', lambda: 0.35,
    tails: [0.99999521488260787, 0.99993659719455429, 0.96016345965726327] },
];
for (const ref of tailReferences) {
  const m = ref.lambda * 35;
  const actual = [pAtLeast1(m), pAtLeast2(m), pAtLeastK(7, m)];
  for (let i = 0; i < actual.length; i++) {
    ok(`${ref.name}: P(>=${[1, 2, 7][i]}) agrees with independent reference`,
       rel(actual[i], ref.tails[i]) < 1e-13, actual[i].toExponential(8));
  }
}
ok('ten times the population rate still gives only ~1 in 24.4 million for 2+ in 35 years',
   rel(pAtLeast2(350 / 1222000), 4.1009148928007811e-8) < 1e-13);

// ── Sourced constants ───────────────────────────────────────────────────────
const NWS_ANNUAL_ODDS = 1222000;   // NWS: annual odds ~ 1 in 1,222,000
const NWS_LIFETIME_ODDS = 15300;   // NWS: 80-year lifetime odds ~ 1 in 15,300
const LIFE_YEARS = 80;             // NWS lifetime window
const SURVIVE_PER_STRIKE = 0.90;   // NWS: ~90% of strike victims survive
const WINDOW = 1977 - 1942;        // first-to-last-recorded-strike observation window

const lambdaAvg = 1 / NWS_ANNUAL_ODDS;   // average person's strikes/year

// ── 1. NWS annual and lifetime base rates are mutually consistent ───────────
console.log('\n— NWS general-population base rates (averages, not any individual) —');
{
  const lifeFromAnnual = pAtLeast1(lambdaAvg * LIFE_YEARS); // 1 - e^{-80*lambda}
  const oddsFromAnnual = 1 / lifeFromAnnual;
  ok(`observation window is 1942-1977 = 35 years`, WINDOW === 35, `${WINDOW}`);
  ok(`annual 1-in-${NWS_ANNUAL_ODDS.toLocaleString('en-US')} -> 80-yr ~1-in-${NWS_LIFETIME_ODDS.toLocaleString('en-US')}`,
     rel(oddsFromAnnual, NWS_LIFETIME_ODDS) < 0.02,
     `computed 1 in ${Math.round(oddsFromAnnual).toLocaleString('en-US')}`);
}

// ── 2. The famous "impossible" figure is a naive-independence artifact ──────
console.log('\n— the category error: an average rate raised to the 7th power —');
{
  const pWindowAvg = pAtLeast1(lambdaAvg * WINDOW);   // avg person, 35 years
  const naive = Math.pow(pWindowAvg, 7);              // seven INDEPENDENT copies
  const log10 = Math.log10(naive);
  ok(`avg person's 35-yr strike chance ~ 2.86e-5`, approx(pWindowAvg, 2.8641e-5, 1e-8),
     `${pWindowAvg.toExponential(3)}`);
  ok(`(that)^7 is astronomically tiny, order 1e-32 (the "4.15 in 10^32" species)`,
     log10 < -31 && log10 > -33, `${naive.toExponential(2)} = 1 in ${(1 / naive).toExponential(2)}`);
  // It is a category error regardless of the exact base rate: EVERY independence
  // calculation lands between ~1e-29 and ~1e-33. We do not endorse any of them.
  ok(`naive figure prints as "1 in 6x10^31" on the page`, approx(1 / naive, 6.33e31, 0.05e31),
     `1 in ${(1 / naive).toExponential(2)}`);
}

// ── 3. The Poisson model at the record-implied rate ─────────────────────────
console.log('\n— the right model: Poisson with a person-specific rate lambda —');
const lambdaRecord = 7 / WINDOW;          // MLE from the record itself: 0.2/yr
const mRecord = lambdaRecord * WINDOW;    // = 7 expected strikes
{
  ok(`record-implied lambda = 7/35 = 0.2/yr`, approx(lambdaRecord, 0.2, 1e-9), `${lambdaRecord}`);
  ok(`that is ~244,000x an average person's rate`, approx(lambdaRecord / lambdaAvg, 244400, 500),
     `${Math.round(lambdaRecord / lambdaAvg).toLocaleString('en-US')}x`);
  ok(`m = lambda*T = 7`, approx(mRecord, 7, 1e-9), `${mRecord}`);
  ok(`P(>=1 strike in window) ~ 99.91%`, approx(pAtLeast1(mRecord), 0.99909, 1e-4),
     `${(100 * pAtLeast1(mRecord)).toFixed(2)}%`);
  ok(`P(>=2 strikes in window) ~ 99.27%`, approx(pAtLeast2(mRecord), 0.99270, 1e-4),
     `${(100 * pAtLeast2(mRecord)).toFixed(2)}%`);
  ok(`P(exactly 7 strikes) ~ 14.90%`, approx(poissonPmf(7, mRecord), 0.14900, 1e-4),
     `${(100 * poissonPmf(7, mRecord)).toFixed(2)}%`);
  ok(`P(>=7 strikes) ~ 55.03% (a coin flip, not 4.15 in 10^32)`,
     approx(pAtLeastK(7, mRecord), 0.55029, 1e-4), `${(100 * pAtLeastK(7, mRecord)).toFixed(2)}%`);
}

// ── monotonicity: as exposure rises, the "impossible" dissolves ─────────────
console.log('\n— dragging exposure up: the probabilities climb (monotone in m) —');
{
  const ms = [1e-5, 1e-3, 0.1, 1, 3, 7];
  let mono1 = true, mono2 = true, prev1 = -1, prev2 = -1;
  for (const m of ms) {
    const p1 = pAtLeast1(m), p2 = pAtLeast2(m);
    if (p1 < prev1) mono1 = false;
    if (p2 < prev2) mono2 = false;
    prev1 = p1; prev2 = p2;
    console.log(`  m=${String(m).padStart(6)}  P(>=1)=${(100 * p1).toFixed(4).padStart(9)}%  ` +
                `P(>=2)=${(100 * p2).toFixed(6).padStart(11)}%  P(>=7)=${(100 * pAtLeastK(7, m)).toExponential(2)}%`);
  }
  ok(`P(>=1) is monotone increasing in exposure`, mono1);
  ok(`P(>=2) is monotone increasing in exposure`, mono2);
  ok(`at average-person exposure (m~2.9e-5) even P(>=1) is tiny`,
     pAtLeast1(lambdaAvg * WINDOW) < 1e-4, `${(100 * pAtLeast1(lambdaAvg * WINDOW)).toExponential(2)}%`);
}

// ── 4. A physical collection-area estimate (IEC 62305) ──────────────────────
console.log('\n— physics anchor: IEC 62305 equivalent collection area of a person —');
{
  const h = 1.8;                       // person height, m
  const Ap_m2 = Math.PI * (3 * h) ** 2;   // Ad = pi*(3h)^2 for a point structure
  const Ap_km2 = Ap_m2 / 1e6;
  const Ng = 6;                        // ground flash density, flashes/km^2/yr (Blue Ridge, approx)
  const lambdaFull = Ng * Ap_km2;      // continuous exposure upper bound, /yr
  ok(`collection area A = pi*(3*1.8)^2 ~ 91.6 m^2`, approx(Ap_m2, 91.6, 0.1), `${Ap_m2.toFixed(1)} m^2`);
  ok(`even 24/7 exposure gives lambda ~ 5.5e-4/yr (order 1e-4)`,
     lambdaFull > 1e-4 && lambdaFull < 1e-3, `${lambdaFull.toExponential(2)}/yr`);
  ok(`that physical estimate is >100x an average person...`, lambdaFull / lambdaAvg > 100,
     `${Math.round(lambdaFull / lambdaAvg)}x`);
  ok(`...yet still far BELOW the record-implied 0.2/yr (the honest residual gap)`,
     lambdaFull < lambdaRecord / 100, `record/physics ~ ${Math.round(lambdaRecord / lambdaFull)}x`);
}

// ── 5. Illustrative survival model ────────────────────────────────────
console.log('\nSurvival: an illustrative independent per-strike model');
{
  const surviveAll7 = Math.pow(SURVIVE_PER_STRIKE, 7);
  ok(`P(survive one strike) = 0.90 (NWS ~90% survive)`, approx(SURVIVE_PER_STRIKE, 0.9, 1e-9));
  ok(`P(survive all 7) = 0.9^7 ~ 47.8%`, approx(surviveAll7, 0.47830, 1e-4),
     `${(100 * surviveAll7).toFixed(1)}%`);
  // casualty-distribution estimates (Cooper & Holle) — ranges, not constants
  const direct = [3, 5], ground = [50, 55], side = [30, 35];
  ok(`direct strikes are the MINORITY of casualties (~3-5%)`, direct[1] < 10, `${direct[0]}-${direct[1]}%`);
  ok(`ground current + side flash dominate (~80-90% together)`,
     ground[0] + side[0] >= 80 && ground[1] + side[1] <= 90, `${ground[0]}-${ground[1]}% + ${side[0]}-${side[1]}%`);
}

// ── 6. Presence: selected expected strings occur in the shipped page ───────────────
console.log('\nPresence: selected strings in the shipped index.html');
{
  const here = dirname(fileURLToPath(import.meta.url));
  const htmlPath = join(here, '..', '..', 'public', 'strata', 'the-man-lightning-kept-finding', 'index.html');
  let html = '';
  try { html = readFileSync(htmlPath, 'utf8'); }
  catch (e) { ok(`read shipped index.html`, false, String(e)); }
  const has = (needle) => html.includes(needle);
  const wants = [
    ['Roy Cleveland Sullivan', 'the subject named'],
    ['1912', 'birth year'],
    ['1983', 'death year'],
    ['seven', 'the record count'],
    ['1942', 'first strike year'],
    ['1977', 'last strike year'],
    ['1,222,000', 'NWS annual odds'],
    ['15,300', 'NWS lifetime odds'],
    ['4.15 in 10<sup>32</sup>', 'the famous debunked figure'],
    ['55', 'P(>=7) ~ 55% at the record rate'],
    ['47.8', 'P(survive all 7) ~ 47.8%'],
    ['90%', 'per-strike survival'],
    ['Cooper', 'mechanism-distribution source'],
    ['Guinness', 'the record authority'],
    ['Hoskins', 'the verification-limit name'],
    ['988', 'the support-resource line'],
  ];
  for (const [needle, why] of wants) ok(`page shows ${why} ("${needle}")`, has(needle));

  // Execute the actual inline script with a small DOM harness and no canvas
  // rendering. Check the outputs readers see, not just the mirrored helpers.
  const script = [...html.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script>/g)]
    .map((m) => m[1]).find((s) => s.includes('function pAtLeastK'));
  ok('page contains the interactive model script', Boolean(script));
  if (script) {
    const element = (value = '') => ({
      value, innerHTML: '', textContent: '', listeners: {}, clientWidth: 700,
      addEventListener(type, fn) { this.listeners[type] = fn; },
      getContext() { return null; },
    });
    const elements = new Map();
    const buttons = [...html.matchAll(/<button[^>]+data-lam="([^"]+)"[^>]*>([^<]+)<\/button>/g)]
      .map((m) => Object.assign(element(), {
        lambda: Number(m[1]),
        getAttribute(name) { return name === 'data-lam' ? m[1] : null; },
        setAttribute() {},
      }));
    const get = (id) => {
      if (!elements.has(id)) elements.set(id, element(id === 'surv' ? '90' : ''));
      return elements.get(id);
    };
    try {
      runInNewContext(script, {
        window: { matchMedia: () => ({ matches: true }), addEventListener() {} },
        document: { getElementById: get, querySelectorAll: () => buttons, addEventListener() {} },
      }, { timeout: 1000 });
      const cases = [
        { lambda: 8.183306e-7, expected: ['2.9×10^-3%', '4.1×10^-8%', '3.1×10^-34%'],
          reciprocal: 'about 1 in 3.2×10^35' },
        { lambda: 1.37e-4, expected: ['0.48%', '1.1×10^-3%', '1.2×10^-18%'],
          reciprocal: 'about 1 in 8.7×10^19' },
        { lambda: 0.2, expected: ['99.9%', '99.3%', '55.0%'],
          reciprocal: 'not 4.15 in 10<sup>32</sup>' },
      ];
      for (const c of cases) {
        const button = buttons.find((b) => b.lambda === c.lambda);
        ok(`UI has preset lambda=${c.lambda}`, Boolean(button));
        if (!button) continue;
        button.listeners.click();
        for (const [i, k] of [1, 2, 7].entries()) {
          ok(`UI lambda=${c.lambda}: P(>=${k}) readout and status`,
             get(`ro-p${k}`).innerHTML === c.expected[i] &&
             get('status').innerHTML.includes(`<strong>${c.expected[i]}</strong>`));
        }
        ok(`UI lambda=${c.lambda}: seven-or-more odds and formula`,
           get('ro-p7-sub').innerHTML === c.reciprocal &&
           get('formula-line').innerHTML.endsWith('= ' + c.expected[2]));
      }
      for (const [position, expected] of [[0, '3.1×10^-34%'], [1000, '96.0%']]) {
        get('expo').value = String(position);
        get('expo').listeners.input();
        ok(`UI slider ${position}: seven-or-more readout, status and formula`,
           get('ro-p7').innerHTML === expected &&
           get('status').innerHTML.includes(`<strong>${expected}</strong>`) &&
           get('formula-line').innerHTML.endsWith('= ' + expected));
      }
      for (const [value, expected] of [[50, '0.8%'], [90, '47.8%'], [99, '93.2%']]) {
        get('surv').value = String(value);
        get('surv').listeners.input();
        ok(`UI survival control at ${value}%`,
           get('surv-out').textContent === expected && get('surv-now').textContent === value + '%');
      }
    } catch (e) {
      ok('interactive model executes with the DOM harness', false, String(e));
    }
  }
}

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
