// verify.mjs — Bayes' theorem, the base-rate engine behind the stratum
// "The Positive Test That's Probably Wrong" (/strata/bayes-theorem/).
//
// What this checks, offline and from scratch:
//   1. Compare the Bayes posterior P(D|+) = P·Se / (P·Se + (1−P)·(1−Sp))
//      with rounded finite-population counts for six selected cases, within a
//      tolerance of one positive person divided by the number of positives.
//   2. The odds form: posterior odds = prior odds × likelihood ratio LR+ = Se/(1−Sp).
//      The two formulas agree to machine precision across a random sweep.
//   3. The page's headline default — a "99% accurate" test (Se=Sp=0.99) for a
//      1%-prevalent disease — gives a posterior of EXACTLY 1/2. A positive is a coin flip.
//   4. Selected literature examples and a rounded adaptation are recomputed:
//        • Casscells, Schoenberger & Graboys (1978): p=1/1000, Se=1, FPR=5% → ≈2%.
//        • Eddy (1982), rounded breast-cancer adaptation: p=1%, Se=80%, FPR=9.6% → ≈7.8%.
//        • Gigerenzer et al. (2007) mammography: p=1%, Se=90%, FPR=9% → ≈9.2%.
//   5. Structural facts the page asserts: the posterior is strictly increasing in
//      prevalence, → 0 as p → 0 and → 1 as p → 1 (fixed Se > 0 and FPR > 0); and
//      base-rate neglect is exactly "answer Se instead of P(D|+)".
//
//   run:  node research/bayes-theorem/verify.mjs
//
// The arithmetic checks use Node only. The optional Lean run needs lean/Bayes.lean.
// Selected calculations are checked here; displayed strings have a separate browser check.

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) => (100 * x).toFixed(2) + '%';

// ── The two formulas ────────────────────────────────────────────────────────
// P  = prevalence / prior P(D)
// Se = sensitivity = P(+ | D)            (true-positive rate)
// Sp = specificity = P(− | ¬D)           (true-negative rate); 1−Sp = false-positive rate
function posterior(P, Se, Sp) {
  const tp = P * Se;                 // P(D and +)
  const fp = (1 - P) * (1 - Sp);     // P(¬D and +)
  return tp / (tp + fp);             // P(D | +) = TP / (TP + FP)
}
// Odds form: O(D|+) = O(D) · LR+, with O = p/(1−p) and LR+ = Se/(1−Sp).
function posteriorOdds(P, Se, Sp) {
  const priorOdds = P / (1 - P);
  const LRplus = Se / (1 - Sp);
  const postOdds = priorOdds * LRplus;
  return postOdds / (1 + postOdds);  // back to a probability
}

console.log('\n— 1. Bayes posterior == brute-force frequency count over a population —');
{
  // The page draws N=10,000 people and counts. Reproduce that count and compare to
  // the closed form. We round to whole people exactly as a real grid must.
  const N = 10000;
  let worst = 0;
  const cases = [
    [0.01, 0.99, 0.99], [0.001, 1.0, 0.95], [0.01, 0.80, 0.904],
    [0.1, 0.95, 0.90], [0.5, 0.70, 0.70], [0.02, 0.85, 0.95],
  ];
  for (const [P, Se, Sp] of cases) {
    const sick = Math.round(N * P);
    const healthy = N - sick;
    const tp = Math.round(sick * Se);            // sick people who test positive
    const fp = Math.round(healthy * (1 - Sp));   // healthy people who test positive
    const countPost = tp / (tp + fp);
    const formPost = posterior(P, Se, Sp);
    // With N=10,000 and these clean rates the rounding error is tiny but nonzero;
    // require agreement to within one person's worth of probability.
    const tol = 1 / (tp + fp);
    worst = Math.max(worst, Math.abs(countPost - formPost));
    ok(`count==formula  p=${pct(P)} Se=${pct(Se)} Sp=${pct(Sp)}  →  ${pct(formPost)}`,
       Math.abs(countPost - formPost) <= tol, `count=${pct(countPost)} (${tp}/${tp + fp})`);
  }
  console.log(`     worst count-vs-formula gap over the sweep: ${worst.toExponential(2)}`);
}

console.log('\n— 2. Probability form == odds form (random sweep, 200k draws) —');
{
  let worst = 0, n = 200000;
  // deterministic LCG so the proof is reproducible
  let s = 123456789 >>> 0;
  const rnd = () => (s = (1103515245 * s + 12345) >>> 0) / 4294967296;
  for (let i = 0; i < n; i++) {
    const P = 0.0005 + rnd() * 0.999;       // (0,1)
    const Se = 0.5 + rnd() * 0.499;         // an informative test
    const Sp = 0.5 + rnd() * 0.499;
    worst = Math.max(worst, Math.abs(posterior(P, Se, Sp) - posteriorOdds(P, Se, Sp)));
  }
  ok(`probability form and odds form agree to 1e-9 over ${n.toLocaleString('en-US')} cases`,
     worst < 1e-9, `max gap = ${worst.toExponential(2)}`);
}

console.log('\n— 3. The headline default: a "99% accurate" test, 1% disease → EXACTLY 1/2 —');
{
  const post = posterior(0.01, 0.99, 0.99);
  ok('Se=Sp=0.99, p=1%  ⇒  P(D|+) = 0.5 exactly', approx(post, 0.5), `= ${post}`);
  // why exactly half: TP = p·Se and FP = (1−p)·(1−Sp); at Se=Sp and p=1−Sp they're equal.
  ok('the equality is structural: TP == FP here', approx(0.01 * 0.99, 0.99 * 0.01));
  // a 1-in-1000 disease with the same 99% test craters the positive to ~9%
  const rare = posterior(0.001, 0.99, 0.99);
  ok('same 99% test, 1-in-1000 disease  ⇒  ≈ 9.0%', approx(rare, 0.0902, 5e-4), `= ${pct(rare)}`);
}

console.log('\n4. Literature examples and a rounded adaptation');
{
  // Casscells, Schoenberger & Graboys, NEJM 1978: prevalence 1/1000, false-positive
  // rate 5%, (test taken as sensitive, Se≈1). Correct answer ≈ 2%; the most common
  // answer given by Harvard medical staff/students was 95% (only ~18% correct).
  const casscells = posterior(0.001, 1.0, 0.95);
  ok('Casscells 1978 (p=0.1%, Se=100%, FPR=5%)  ≈ 2%', approx(casscells, 0.0196, 5e-4), `= ${pct(casscells)}`);

  // Rounded adaptation of Eddy 1982: prevalence 1%, sensitivity 80%, FPR 9.6%.
  // Eddy used sensitivity 79.2%, giving 1/13; this adaptation gives 25/322.
  const eddy = posterior(0.01, 0.80, 1 - 0.096);
  ok('Eddy 1982 rounded adaptation (p=1%, Se=80%, FPR=9.6%)  ≈ 7.8%', approx(eddy, 25 / 322, 1e-12), `= ${pct(eddy)}`);

  // Gigerenzer et al. 2007, p.55, mammography figures: p=1%, Se=90%, FPR=9% → ≈9.2%.
  const gig = posterior(0.01, 0.90, 1 - 0.09);
  ok('Gigerenzer et al. 2007 (p=1%, Se=90%, FPR=9%)  ≈ 9.2%', approx(gig, 10 / 109, 1e-12), `= ${pct(gig)}`);
}

console.log('\n— 5. Structural facts the page claims —');
{
  // (a) strictly increasing in prevalence when fixed Se > 0 and FPR > 0
  let mono = true;
  const Se = 0.9, Sp = 0.9;  // LR+ = 9 > 1
  let prev = -1;
  for (let p = 0.0001; p < 1; p += 0.0007) {
    const v = posterior(p, Se, Sp);
    if (v <= prev) mono = false;
    prev = v;
  }
  ok('posterior is strictly increasing in prevalence at fixed Se=Sp=0.9', mono);

  // (b) limits
  ok('p → 0  ⇒  posterior → 0 at fixed Se=Sp=0.9', posterior(1e-9, 0.9, 0.9) < 1e-7);
  ok('p → 1  ⇒  posterior → 1 at fixed Se=Sp=0.9', posterior(1 - 1e-9, 0.9, 0.9) > 1 - 1e-7);
  ok('specificity 100% gives posterior 1 at every tested positive prevalence',
     [1e-9, 1 / 100000, 0.01, 0.5, 1].every(p => posterior(p, 0.5, 1) === 1));

  // (c) base-rate neglect, precisely stated: the classic wrong answer is to report
  // the sensitivity (≈ "the test is 90% accurate, so 90%") instead of P(D|+).
  // The two diverge wildly exactly when the disease is rare.
  const wrong = 0.90;                       // what people say
  const right = posterior(0.01, 0.90, 0.90); // what's true
  ok('base-rate neglect = reporting Se (90%) for the true posterior (≈8.3%)',
     approx(right, 0.0833, 5e-4) && wrong - right > 0.8, `Se=${pct(wrong)} vs truth=${pct(right)}`);

  // (d) a perfectly USELESS test (Se = 1−Sp, LR+ = 1) leaves the prior unchanged
  ok('a useless test (Se = 1−Sp) never moves the prior', approx(posterior(0.137, 0.4, 0.6), 0.137));
}

// ── 6. The kernel — the same counts as INTEGER cohort counts, then Lean re-checks —
//    research/bayes-theorem/lean/Bayes.lean hands these exact counts to Lean's kernel
//    (zero imports; `by decide` for the enumerated counts, `by omega` for the universal
//    theorems). Here we (a) recompute the integer counts the kernel proves, over the
//    identical finite populations, and (b) if `lean` is on PATH, run the proof live and
//    confirm its axiom verdict. The kernel proves for EVERY population what §2 sampled.
console.log('\n— 6. The kernel (integer cohort counts — what Bayes.lean proves) —');
{
  // A population is (tp, fn, fp, tn); a plain count over it is a probability.
  const positives = (tp, fp) => tp + fp;

  // (1) The clinic, enumerated: N=1000, prev 1%, Se 90%, FPR 10%.
  const clinic = { tp: 9, fn: 1, fp: 99, tn: 891 };
  const cTotal = clinic.tp + clinic.fn + clinic.fp + clinic.tn;
  ok('kernel: clinic is 1000 people', cTotal === 1000, `=${cTotal}`);
  ok('kernel: 10 sick, 108 positive', (clinic.tp + clinic.fn) === 10 && positives(clinic.tp, clinic.fp) === 108);
  ok('kernel: only 9 of 108 positives are truly sick — 9/108 = 1/12',
     clinic.tp * 12 === positives(clinic.tp, clinic.fp) * 1, `${clinic.tp}/${positives(clinic.tp, clinic.fp)}`);
  ok('kernel: false alarms swamp true cases 11:1', clinic.fp === 11 * clinic.tp, `${clinic.fp}=11·${clinic.tp}`);
  ok('kernel: fewer than 1 positive in 10 is real', clinic.tp * 10 < positives(clinic.tp, clinic.fp));

  // (2) The flagship headline, exact counts over N=10000: prev 1%, Se=Sp=99%.
  const sick = Math.round(10000 * 0.01);                 // 100
  const ftp = Math.round(sick * 0.99);                   // 99
  const ffp = Math.round((10000 - sick) * 0.01);         // 99
  ok('kernel: flagship counts exact (100 sick, 99 TP, 99 FP)', sick === 100 && ftp === 99 && ffp === 99);
  ok('kernel: 99% test on a 1-in-100 disease → 99/198 = 1/2 (a coin flip)',
     ftp * 2 === positives(ftp, ffp) * 1, `${ftp}/${positives(ftp, ffp)}`);

  // (3) Literature examples and the rounded Eddy adaptation as exact integer ratios.
  const bounded = (num, den, loBps, hiBps) => (loBps * den <= num * 10000) && (num * 10000 < hiBps * den);
  ok('kernel: Casscells 20:999 → 20/1019 in [1.96%,1.97%)', bounded(20, 1019, 196, 197));
  ok('kernel: rounded Eddy adaptation 25:297 → 25/322 in [7.76%,7.77%)', bounded(25, 322, 776, 777));
  ok('kernel: Gigerenzer et al. 2007 10:99 → 10/109 in [9.17%,9.18%)', bounded(10, 109, 917, 918));

  // (4) The universal theorem, checked as a JS invariant over a wide integer sweep — the
  //     kernel proves it for ALL naturals; here we merely confirm no counterexample exists
  //     in a large finite window (Lean removes the "finite window" caveat entirely).
  let reversalHolds = true;
  for (let s = 0; s <= 60; s++) for (let tp = 0; tp <= s; tp++) for (let fp = s + 1; fp <= 80; fp++) {
    if (!(tp < fp && 2 * tp < tp + fp)) reversalHolds = false;
  }
  ok('kernel: rarity_beats_accuracy holds on the sweep (Lean proves it ∀)', reversalHolds);
}

// Live kernel run — only if Lean is installed (it is one command away; see
// research/bayes-theorem/lean/install-lean-nix.sh). Static-only otherwise.
{
  const { execSync } = await import('node:child_process');
  const { existsSync } = await import('node:fs');
  const leanFile = new URL('./lean/Bayes.lean', import.meta.url).pathname;
  let leanOnPath = false;
  try { execSync('command -v lean', { stdio: 'ignore' }); leanOnPath = true; } catch { /* not installed */ }
  if (!leanOnPath) {
    console.log('  (skip: lean not on PATH — install: bash research/bayes-theorem/lean/install-lean-nix.sh)');
  } else if (!existsSync(leanFile)) {
    ok('lean: Bayes.lean present', false);
  } else {
    let out = '';
    try { out = execSync(`lean ${JSON.stringify(leanFile)}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); }
    catch (e) { out = (e.stdout || '') + (e.stderr || ''); ok('lean: Bayes.lean typechecks (no errors)', false, out.slice(0, 300)); }
    const clean = !/error/i.test(out);
    ok('lean: Bayes.lean typechecks (no errors)', clean);
    ok('lean: the_base_rate_decides depends on NO axioms',
       /the_base_rate_decides'? does not depend on any axioms/.test(out));
    ok('lean: rarity_beats_accuracy footprint is [propext, Quot.sound]',
       /rarity_beats_accuracy'? depends on axioms: \[propext, Quot\.sound\]/.test(out));
    ok('lean: no sorry / Classical.choice / native_decide in footprint',
       !/sorry|Classical\.choice|native/i.test(out));
  }
}

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