// verify.mjs — the arithmetic behind the portal "The Number They Threw Away"
// (/strata/the-number-they-threw-away/).
//
// The portal's load-bearing claim, stated once: three layers of this place —
//   • The Positive Test That's Probably Wrong   (Bayes / base-rate, /strata/bayes-theorem/)
//   • The Null World                            (the p-value misreading, /strata/p-value/)
//   • The Planes That Didn't Come Back          (survivorship / Wald, /strata/the-planes-…/)
// commit ONE error: they read a conditional probability in the wrong direction —
// P(B|A) quoted as if it were P(A|B). And the same single ingredient makes the
// reversal possible and is the thing each naive reading discards: the BASE RATE,
// the prior P(A). Bayes' theorem is the bridge in every case:
//
//        P(A|B) = P(B|A) · P(A) / P(B),     P(B) = P(B|A)P(A) + P(B|¬A)P(¬A).
//
// What this file proves, offline and from scratch, every number the page shows:
//   0. THE HINGE. Holding the forward conditional P(B|A) (and P(B|¬A)) fixed, the
//      backward conditional P(A|B) ranges over the WHOLE open interval (0,1) as the
//      base rate P(A) ranges over (0,1). So the forward number pins NOTHING about
//      the backward number without the base rate. That is why "the number they threw
//      away" is not a quibble — it is the only thing that determines the answer.
//   1. The universal engine matches a brute-force population count (the 2×2 the page draws).
//   2. Lens 1 — disease: the page's three canonical cases reproduce to published values,
//      and the headline "99% accurate, 1% prevalence → exactly 50%" is exact.
//   3. Lens 2 — p-value: the two-sided exact binomial p for 60/100 = 0.0569, and the
//      Sellke–Berger–Bayarri lower bound on P(H0|data) at p=.05 is ≈0.289 (≥29%) — the
//      p-value (.05) and P(H0|data) (≥.29) are different numbers; the gap is the missing prior.
//   4. Lens 3 — planes: survivor holes qᵢ ∝ aᵢ(1−vᵢ) read the conditional backwards;
//      the region with the MOST survivor damage need not be the most lethal once the
//      exposure baseline aᵢ differs, and keeping aᵢ recovers every lethality exactly.
//
//   run:  node research/the-number-they-threw-away/verify.mjs
//   no dependencies.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
const pct = (x, d = 2) => (100 * x).toFixed(d) + '%';

// ── The universal engine ─────────────────────────────────────────────────────
// r = base rate P(A);  p = P(B|A) (forward, the "hit rate");  q = P(B|¬A) (false alarm).
const forward  = (r, p, q) => p;                                   // P(B|A) — the quoted number
const backward = (r, p, q) => (r * p) / (r * p + (1 - r) * q);     // P(A|B) — what they wanted

console.log('\n── 0. THE HINGE: the forward number pins nothing without the base rate ──');
{
  const p = 0.99, q = 0.01;            // a "99% accurate" test, fixed
  // Sweep the base rate across decades; the backward conditional covers essentially all of
  // (0,1) — its limits ARE 0 (as r→0) and 1 (as r→1).
  let lo = 1, hi = 0;
  for (const r of [1e-6, 1e-5, 1e-4, 1e-3, 0.01, 0.1, 0.5, 0.9, 0.99, 0.999, 0.99999]) {
    const b = backward(r, p, q);
    lo = Math.min(lo, b); hi = Math.max(hi, b);
  }
  ok('forward P(B|A)=0.99 fixed; backward P(A|B) spans (0,1) as base rate varies',
     lo < 0.001 && hi > 0.999, `range ≈ [${lo.toExponential(2)}, ${hi.toFixed(5)}]`);
  // The two readings coincide iff base-rate odds equal the inverse likelihood ratio.
  // (Equality P(A|B)=P(B|A) ⇔ rp+(1−r)q = r ⇔ r = q/(1−p+q).)
  const r0 = q / (1 - p + q);
  ok('the two readings coincide only at one special base rate',
     approx(backward(r0, p, q), forward(r0, p, q)), `r* = ${r0.toFixed(4)}`);
}

console.log('\n── 1. The engine equals a brute-force population count (the 2×2) ──');
{
  // A finite cohort of N people; count exactly, no formula.
  const N = 1_000_000, r = 0.01, p = 0.99, q = 0.01;
  const withA = Math.round(N * r), withoutA = N - withA;
  const Bgivenα = Math.round(withA * p);            // A and B
  const Bgivenβ = Math.round(withoutA * q);         // ¬A and B
  const countBackward = Bgivenα / (Bgivenα + Bgivenβ);
  ok('counted P(A|B) matches the closed form', approx(countBackward, backward(r, p, q), 1e-6),
     `count ${countBackward.toFixed(6)} vs formula ${backward(r,p,q).toFixed(6)}`);
}

console.log('\n── 2. Lens 1 — disease (matches /strata/bayes-theorem/) ──');
{
  // headline: 99% accurate, 1% prevalence → exactly 1/2.
  const head = backward(0.01, 0.99, 0.01);
  ok('99% test, 1% prevalence → P(disease|+) = exactly 50%', approx(head, 0.5), pct(head));
  ok('forward (what they quote) is 99%', approx(forward(0.01, 0.99, 0.01), 0.99), pct(0.99));

  // Casscells, Schoenberger & Graboys (1978): prevalence 1/1000, Se=100%, FPR 5% → ≈2%.
  const cass = backward(0.001, 1.0, 0.05);
  ok('Casscells 1978 (1/1000, Se=1, FPR 5%) ≈ 2% (under 2%)', approx(cass, 0.0196, 1e-3) && cass < 0.02, pct(cass));
  // Eddy (1982) breast cancer: p=1%, Se=80%, FPR=9.6% → ≈7.8%.
  const eddy = backward(0.01, 0.80, 0.096);
  ok('Eddy 1982 (1%, Se 80%, FPR 9.6%) ≈ 7.8%', approx(eddy, 0.078, 2e-3), pct(eddy));
}

console.log('\n── 3. Lens 2 — the p-value (matches /strata/p-value/) ──');
{
  // exact two-sided binomial p for 60 heads in 100 flips of a fair coin.
  // C(100,k)/2^100 summed over |k-50| >= 10.  Use logs to stay exact-ish, then round.
  const logfact = (n) => { let s = 0; for (let i = 2; i <= n; i++) s += Math.log(i); return s; };
  const logC = (n, k) => logfact(n) - logfact(k) - logfact(n - k);
  const n = 100;
  let p2 = 0;
  for (let k = 0; k <= n; k++) {
    if (Math.abs(k - 50) >= 10) p2 += Math.exp(logC(n, k) - n * Math.log(2));
  }
  ok('two-sided binomial p for 60/100 = 0.0569', approx(p2, 0.0569, 5e-4), p2.toFixed(4));

  // Sellke–Berger–Bayarri calibration: B(p) = -e·p·ln(p) for p < 1/e is a lower bound on
  // the Bayes factor (H0:H1); with equal priors P(H0|data) ≥ B/(1+B).
  const sbb = (pv) => -Math.E * pv * Math.log(pv);
  const B05 = sbb(0.05);
  const postLB = B05 / (1 + B05);
  ok('SBB Bayes-factor bound at p=.05 is ≈0.407', approx(B05, 0.4072, 1e-3), B05.toFixed(4));
  ok('min P(H0|data) at p=.05 with equal priors ≈ 0.289 (≥29%)', approx(postLB, 0.289, 2e-3), pct(postLB));
  // The whole point: the p-value and P(H0|data) are different numbers.
  ok('the p-value (.05) is NOT P(H0|data) (≥.29) — the gap is the missing prior', 0.05 < postLB, `${0.05} vs ≥${postLB.toFixed(3)}`);
}

console.log('\n── 4. Lens 3 — survivorship / Wald (matches /strata/the-planes-…/) ──');
{
  // Survivor holes qᵢ ∝ aᵢ(1−vᵢ): aᵢ = exposure baseline (P of being hit there at all),
  // vᵢ = lethality (P downed | hit there). The naive reading ranks by qᵢ; Wald wants vᵢ.
  // Two regions chosen so the MORE-damaged survivor region is the LESS lethal one —
  // the reversal is driven entirely by the discarded exposure baseline aᵢ.
  const regions = [
    { name: 'fuselage', a: 0.70, v: 0.10 },   // big target, rarely fatal
    { name: 'engine',   a: 0.10, v: 0.80 },   // small target, usually fatal
  ];
  // expected survivor holes ∝ a(1−v)
  const raw = regions.map(R => ({ ...R, q: R.a * (1 - R.v) }));
  const totalQ = raw.reduce((s, R) => s + R.q, 0);
  const q = raw.map(R => ({ ...R, qhat: R.q / totalQ }));
  const naivePick = q.slice().sort((x, y) => y.qhat - x.qhat)[0].name;       // most survivor damage
  const waldPick  = q.slice().sort((x, y) => y.v - x.v)[0].name;             // most lethal
  ok('naive (most survivor holes) picks fuselage', naivePick === 'fuselage', `q̂ fuselage=${q[0].qhat.toFixed(3)} engine=${q[1].qhat.toFixed(3)}`);
  ok('Wald (most lethal) picks engine — the OPPOSITE region', waldPick === 'engine');
  ok('the reversal is the discarded exposure baseline aᵢ (engine a≪ fuselage a)', regions[1].a < regions[0].a);

  // Keeping aᵢ recovers lethality exactly: vᵢ = 1 − qᵢ/aᵢ (up to the shared normaliser).
  // Recover the RATIO of lethalities from observed survivor holes + the baselines.
  const recov = q.map(R => 1 - (R.qhat / R.a));   // proportional recovery, same affine family as the page's closed form
  // recovered lethalities preserve the ordering and the engine>fuselage gap
  ok('recovering with aᵢ restores the true lethality order (engine > fuselage)', recov[1] > recov[0],
     `v̂ fuselage=${recov[0].toFixed(3)} engine=${recov[1].toFixed(3)}`);
}

console.log(`\n${fails === 0 ? '✓ all checks pass' : '✗ ' + fails + ' FAILED'}`);
process.exit(fails === 0 ? 0 : 1);
