// verify.mjs — every claim on /strata/st-petersburg-paradox/, checked.
//
//   node research/st-petersburg-paradox/verify.mjs
//
// Exact claims are checked by arithmetic; the one asymptotic claim (Feller's weak
// law) is checked by seeded simulation against its *structural* signature — a
// running average that keeps climbing and tracks log2(n) — not against hand-copied
// numbers. Deterministic: same seeds → same result on every machine.

import {
  partialMean, cdfAtPow, medianPayout, expectedLog2Payout, geometricMeanPayout,
  cappedMean, fairPriceForBankroll, fellerTrial, mulberry32, playOnce, lifetimeAverage,
} from './engine.mjs';

let pass = 0, fail = 0;
const near = (a, b, tol = 1e-9) => Math.abs(a - b) <= tol;
function ok(name, cond, got) {
  if (cond) { pass++; console.log(`  ✓ ${name}`); }
  else { fail++; console.log(`  ✗ ${name}  — got ${got}`); }
}

console.log('\nST. PETERSBURG PARADOX — verification\n');

// ── 1. The infinite arithmetic mean ───────────────────────────────────────
console.log('1. The arithmetic mean is the sum 1+1+1+… (each term exactly 1)');
ok('partial mean over N=10 tosses = 10', near(partialMean(10), 10), partialMean(10));
ok('partial mean over N=50 tosses = 50', near(partialMean(50), 50), partialMean(50));
ok('partial mean over N=1000 tosses = 1000', near(partialMean(1000), 1000), partialMean(1000));
ok('every doubling contributes exactly 1 (mean grows without bound)',
   partialMean(1000) > partialMean(500) && near(partialMean(1000) - partialMean(999), 1), partialMean(1000));

// ── 2. The distribution: most plays pay almost nothing ─────────────────────
console.log('\n2. The payout distribution — P(payout ≤ 2^m) = 1 − 2^(−m)');
ok('P(payout ≤ 2)  = 1/2',   near(cdfAtPow(1), 0.5), cdfAtPow(1));
ok('P(payout ≤ 4)  = 3/4',   near(cdfAtPow(2), 0.75), cdfAtPow(2));
ok('P(payout ≤ 8)  = 7/8 (87.5% of plays pay 8 or less)', near(cdfAtPow(3), 0.875), cdfAtPow(3));
ok('P(payout ≤ 32) = 31/32 (96.875%)', near(cdfAtPow(5), 31 / 32), cdfAtPow(5));

// ── 3. Median payout = 2 ───────────────────────────────────────────────────
console.log('\n3. The MEDIAN payout — the typical game');
ok('median payout = 2 (half of all plays end on the first toss)', medianPayout() === 2, medianPayout());

// ── 4. Geometric mean = 4  (Bernoulli 1738, log utility) ───────────────────
console.log('\n4. The GEOMETRIC mean payout = 4  (E[log2 payout] = Σ k·2^(−k) = 2)');
ok('E[log2 payout] = 2', near(expectedLog2Payout(), 2, 1e-9), expectedLog2Payout());
ok('geometric mean payout = 2^2 = 4', near(geometricMeanPayout(), 4, 1e-9), geometricMeanPayout());
// cross-check E[log2] by seeded sampling of real plays
{
  const rnd = mulberry32(20260701);
  let s = 0; const N = 2_000_000;
  for (let i = 0; i < N; i++) s += Math.log2(playOnce(rnd));
  const est = s / N;
  ok('E[log2 payout] ≈ 2 by 2M-play simulation (|est−2| < 0.02)', Math.abs(est - 2) < 0.02, est.toFixed(4));
}

// ── 5. The three averages disagree — the whole point ───────────────────────
console.log('\n5. One game, three "averages", three answers');
ok('median (2) < geometric mean (4) < arithmetic mean (∞)',
   medianPayout() === 2 && near(geometricMeanPayout(), 4) && near(partialMean(1000), 1000, 1e-6) && partialMean(1000) > 4,
   `${medianPayout()}, ${geometricMeanPayout()}, ${partialMean(1000)}→∞`);

// ── 6. The finite house: fair price = log2(bankroll) + 1 ───────────────────
console.log('\n6. A house with bankroll W = 2^L: fair price of the capped game = L + 1');
ok('cap at 2^20 ($≈1.05M): fair price = 21', near(cappedMean(20), 21), cappedMean(20));
ok('cap at 2^40 ($≈1.10T): fair price = 41', near(cappedMean(40), 41), cappedMean(40));
ok('cap at 2^60: fair price = 61', near(cappedMean(60), 61), cappedMean(60));
ok('$1,000,000 bankroll → L=19, price=20', (() => { const r = fairPriceForBankroll(1e6); return r.L === 19 && r.price === 20; })(),
   JSON.stringify(fairPriceForBankroll(1e6)));
ok('$1 trillion bankroll → L=39, price=40', (() => { const r = fairPriceForBankroll(1e12); return r.L === 39 && r.price === 40; })(),
   JSON.stringify(fairPriceForBankroll(1e12)));
ok('all money on Earth (~$4.5e14) → L=48, price=49', (() => { const r = fairPriceForBankroll(4.5e14); return r.L === 48 && r.price === 49; })(),
   JSON.stringify(fairPriceForBankroll(4.5e14)));

// ── 7. How long until the paradox bites (jackpot waiting time) ─────────────
console.log('\n7. Plays needed for a ≥ 2^m payout to be more likely than not');
function playsForEvenChance(m) {
  const p = Math.pow(2, -(m - 1)); // P(single play pays ≥ 2^m) = 2^(−(m−1))
  return Math.log(0.5) / Math.log(1 - p);
}
ok('≥ 2^10 (=1,024): ~355 plays for 50% odds', Math.round(playsForEvenChance(10)) === 355, Math.round(playsForEvenChance(10)));
ok('≥ 2^20 (≈$1.05M): ~363,408 plays for 50% odds', Math.abs(playsForEvenChance(20) - 363408) < 5, Math.round(playsForEvenChance(20)));
{
  // simulate: in ~363k plays, at least one payout ≥ 2^20 should occur about half the time
  let hits = 0; const trials = 60;
  for (let t = 0; t < trials; t++) {
    const rnd = mulberry32((0xB105 ^ (t * 2654435761)) >>> 0);
    let got = false;
    for (let i = 0; i < 363408 && !got; i++) if (playOnce(rnd) >= Math.pow(2, 20)) got = true;
    if (got) hits++;
  }
  const frac = hits / trials;
  ok('simulation: ≈50% of 363,408-play lifetimes see a ≥$1M jackpot (0.30–0.70)', frac >= 0.30 && frac <= 0.70, frac.toFixed(2));
}

// ── 8. Feller's weak law (1945): S_n / (n·log2 n) → 1 in probability ────────
// Structural signature: the running average A_n = S_n/n keeps CLIMBING with n
// (no ordinary law of large numbers) and tracks log2(n) — the ratio A_n/log2(n)
// drifts toward 1 from above, while the additive gap A_n − log2(n) stays in a
// tight band. Checked on a seeded ladder n = 2^8 … 2^16, 400 lifetimes each.
console.log('\n8. Feller (1945): the running average never settles — it grows like log2(n)');
const ladder = [8, 10, 12, 14, 16].map((m) => fellerTrial(12345, 2 ** m, 400));
for (const r of ladder) {
  console.log(`     n=2^${Math.round(r.log2n)}  median A_n=${r.median.toFixed(2)}  log2n=${r.log2n}  ratio=${r.ratio.toFixed(3)}  gap=${(r.median - r.log2n).toFixed(2)}`);
}
ok('median A_n strictly INCREASES with n (no convergence)',
   ladder.every((r, i) => i === 0 || r.median > ladder[i - 1].median), ladder.map((r) => r.median.toFixed(1)).join(','));
ok('ratio A_n/log2n stays in (1.0, 1.5) — the n·log2n scale is right',
   ladder.every((r) => r.ratio > 1.0 && r.ratio < 1.5), ladder.map((r) => r.ratio.toFixed(3)).join(','));
ok('ratio A_n/log2n DECREASES toward 1 as n grows (weak-law convergence)',
   ladder.every((r, i) => i === 0 || r.ratio < ladder[i - 1].ratio + 1e-9), ladder.map((r) => r.ratio.toFixed(3)).join(','));
ok('additive gap A_n − log2n stays bounded in [1.5, 3.5] (parallel growth)',
   ladder.every((r) => (r.median - r.log2n) >= 1.5 && (r.median - r.log2n) <= 3.5),
   ladder.map((r) => (r.median - r.log2n).toFixed(2)).join(','));
// robustness across independent seeds at n=2^14
{
  const gaps = [1, 7, 99999, 424242].map((s) => { const r = fellerTrial(s, 2 ** 14, 400); return r.median - r.log2n; });
  ok('gap ≈ 2.5 robustly across 4 independent seeds (all in [1.8, 3.2])',
     gaps.every((g) => g >= 1.8 && g <= 3.2), gaps.map((g) => g.toFixed(2)).join(','));
}

// ── 9. Why there is no ordinary law of large numbers: the mean is not typical ─
// Heavy right tail: the AVERAGE-across-lifetimes sits well above the TYPICAL
// (median) lifetime, because rare jackpots drag it up — so "the average" is not
// what any ordinary player experiences. That gap is the reason the strong law
// fails here, and it does not close as n grows.
console.log('\n9. The mean-across-lifetimes stays far above the typical lifetime (heavy tail)');
for (const m of [10, 12, 14, 16]) {
  const r = fellerTrial(12345, 2 ** m, 600);
  const mean = r.avgs.reduce((a, b) => a + b, 0) / r.avgs.length;
  console.log(`     n=2^${m}: typical (median) A_n=${r.median.toFixed(2)}   mean-of-A_n=${mean.toFixed(2)}   inflation=${(mean / r.median).toFixed(2)}×`);
  ok(`n=2^${m}: mean-of-averages exceeds the typical average by ≥1.25× (rare jackpots dominate)`,
     mean > 1.25 * r.median, (mean / r.median).toFixed(2));
}

// ── summary ────────────────────────────────────────────────────────────────
console.log(`\n${fail === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${pass}/${pass + fail} checks\n`);
process.exit(fail === 0 ? 0 : 1);
