#!/usr/bin/env node
// verify-lottery-lump-sum-or-annuity.mjs
//
// Offline gate for /strata/lottery-lump-sum-or-annuity/ ("The Pot That Was Never Cash").
// It rebuilds EVERY headline the page shows from the bundled, dated drawing data and the
// fixed structural rules, and exits 0 only if all checks pass. Where possible each fact is
// checked two independent ways.
//
// The structure (Powerball and Mega Millions, identical):
//   30 payments, the first immediate (t=0), each 5% larger than the last,
//   whose 30 amounts sum to the advertised jackpot.
//     schedule   pays[t] = (advertised / SUM_{k=0..29} 1.05^k) * 1.05^t
//     present value  PV(r) = SUM_{t=0..29} pays[t] / (1+r)^t
//     cash option   = the present value the lottery would use to buy the stream (Treasury STRIPS)
//     implied rate  r*  such that PV(r*) = published cash value
//
// Bundled primary drawings (source-pinned, dated):
//   Powerball,     Dec 17 2025: advertised $1,250,000,000  cash $572,100,000   (powerball.com)
//   Mega Millions, Oct 24 2025: advertised $680,000,000    cash $318,200,000   (megamillions.com)
//
// Run:  node research/lottery-lump-sum-or-annuity/verify-lottery-lump-sum-or-annuity.mjs

'use strict';

const N = 30, GROWTH = 0.05;

// ---- bundled primary drawings (must match the values printed on the panel) --------
const DRAWINGS = {
  powerball:    { game: 'Powerball',     date: 'December 17, 2025', advertised: 1.25e9, cash: 572.1e6 },
  megamillions: { game: 'Mega Millions', date: 'October 24, 2025',  advertised: 680e6,  cash: 318.2e6 },
};

// ---- the model (identical to the page's inline JS) --------------------------------
const factorSum = () => { let S = 0; for (let t = 0; t < N; t++) S += Math.pow(1 + GROWTH, t); return S; };
const FS = factorSum();
const buildSchedule = (adv) => { const p0 = adv / FS, a = []; for (let t = 0; t < N; t++) a.push(p0 * Math.pow(1 + GROWTH, t)); return a; };
const pv = (pays, r) => { let v = 0; for (let t = 0; t < N; t++) v += pays[t] / Math.pow(1 + r, t); return v; };
function solveRate(pays, target) {                       // PV strictly decreasing in r
  let lo = 0, hi = 1;
  for (let i = 0; i < 200; i++) { const m = (lo + hi) / 2; if (pv(pays, m) > target) lo = m; else hi = m; }
  return (lo + hi) / 2;
}
const money = (x) => '$' + Math.round(x).toLocaleString('en-US');

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

console.log('lottery-lump-sum-or-annuity :: offline verifier');
console.log(`structure: ${N} payments, first immediate, each ${GROWTH * 100}% larger; SUM(1.05^t) = ${FS.toFixed(6)}`);
console.log('');

// 1) SCHEDULE RECONSTRUCTS THE HEADLINE (Powerball)
console.log('[1] schedule rebuilds the advertised jackpot (Powerball, Dec 17 2025)');
{
  const d = DRAWINGS.powerball;
  const pays = buildSchedule(d.advertised);
  const sum = pays.reduce((a, b) => a + b, 0);
  check('30 payments sum to the advertised $1.25B', approx(sum, d.advertised, 1e-9), money(sum));
  check('first payment is immediate and about $18.81M', approx(pays[0], 18.81e6, 2e-3), money(pays[0]));
  check('last payment is about $77.44M', approx(pays[N - 1], 77.44e6, 2e-3), money(pays[N - 1]));
  check('each payment is exactly 5% larger than the last', approx(pays[1] / pays[0], 1.05, 1e-12) && approx(pays[15] / pays[14], 1.05, 1e-12));
  // independent: geometric-series closed form for the sum
  const closed = pays[0] * (Math.pow(1.05, 30) - 1) / (1.05 - 1);
  check('geometric closed form matches the summed schedule', approx(closed, sum, 1e-6));
}

// 2) CASH FRACTION reproduces the pinned official pair
console.log('\n[2] cash fraction = published cash / advertised');
{
  const d = DRAWINGS.powerball;
  const frac = d.cash / d.advertised;
  check('572.1M / 1.25B = 45.77%', approx(frac, 0.4577, 1e-3), (frac * 100).toFixed(4) + '%');
}

// 3) IMPLIED RATE SOLVE
console.log('\n[3] implied rate: solve PV(r) = published cash value');
{
  const d = DRAWINGS.powerball;
  const pays = buildSchedule(d.advertised);
  const r = solveRate(pays, d.cash);
  check('PV at the solved rate equals the published cash', approx(pv(pays, r), d.cash, 1e-6), money(pv(pays, r)));
  check('implied rate is about 4.90% (band 4.7%-5.1%)', r > 0.047 && r < 0.051, (r * 100).toFixed(4) + '%');
}

// 4) CROSSOVER PROPERTY (monotone in the discount rate)
console.log('\n[4] crossover: verdict is a monotone function of the discount rate');
{
  const d = DRAWINGS.powerball;
  const pays = buildSchedule(d.advertised);
  const r = solveRate(pays, d.cash);
  check('at r = implied rate, annuity PV equals the cash option', approx(pv(pays, r), d.cash, 1e-6));
  check('for r > implied, cash option exceeds annuity PV (cash wins)', pv(pays, r + 0.005) < d.cash && pv(pays, r + 0.02) < d.cash);
  check('for r < implied, annuity PV exceeds cash option (annuity wins)', pv(pays, r - 0.005) > d.cash && pv(pays, r - 0.02) > d.cash);
  // strict monotonicity of PV across a sweep
  let mono = true;
  for (let x = 0; x < 0.11; x += 0.005) if (pv(pays, x + 0.005) >= pv(pays, x)) mono = false;
  check('PV(r) is strictly decreasing across 0%-11%', mono);
}

// 5) FUNDING-RATE SENSITIVITY: cash fraction strictly DECREASING in the funding rate
console.log('\n[5] funding-rate sensitivity: higher rate -> smaller cash fraction');
{
  const d = DRAWINGS.powerball;
  const pays = buildSchedule(d.advertised);
  const fracAt = (r) => pv(pays, r) / d.advertised;
  check('cash fraction at 2% > at 5% > at 8%', fracAt(0.02) > fracAt(0.05) && fracAt(0.05) > fracAt(0.08),
        `${(fracAt(0.02) * 100).toFixed(1)}% > ${(fracAt(0.05) * 100).toFixed(1)}% > ${(fracAt(0.08) * 100).toFixed(1)}%`);
  check('a fixed "50%" claim would fail: low rate pushes past 60%, high rate below 40%', fracAt(0.01) > 0.60 && fracAt(0.10) < 0.40,
        `${(fracAt(0.01) * 100).toFixed(1)}% .. ${(fracAt(0.10) * 100).toFixed(1)}%`);
}

// 6) TAX SCENARIO ARITHMETIC (labeled, federal-only, never one canonical take-home)
console.log('\n[6] tax scenarios: withholding vs true liability (labeled, not a take-home)');
{
  const d = DRAWINGS.powerball;
  const withheld = 0.24 * d.cash;
  const liability = 0.37 * d.cash;
  const owed = liability - withheld;
  check('withholding-vs-liability gap is 37% - 24% = 13 points', approx(0.37 - 0.24, 0.13, 1e-9));
  check('24% withheld on the cash value is about $137.3M', approx(withheld, 137.3e6, 2e-3), money(withheld));
  check('37% top-bracket liability is about $211.7M', approx(liability, 211.7e6, 2e-3), money(liability));
  check('so about $74.4M is owed at filing (federal-only, state excluded)', approx(owed, 74.4e6, 3e-3), money(owed));
  check('the gap equals 13% of the cash value', approx(owed, 0.13 * d.cash, 1e-9));
}

// 7) SECOND-DRAWING GUARD: the ~46% is structural, not cherry-picked
console.log('\n[7] second drawing guard (Mega Millions, Oct 24 2025)');
{
  const d = DRAWINGS.megamillions;
  const pays = buildSchedule(d.advertised);
  const sum = pays.reduce((a, b) => a + b, 0);
  const frac = d.cash / d.advertised;
  const r = solveRate(pays, d.cash);
  check('Mega Millions schedule sums to its advertised $680M', approx(sum, d.advertised, 1e-9), money(sum));
  check('Mega Millions cash fraction lands in the ~44-48% band', frac > 0.44 && frac < 0.48, (frac * 100).toFixed(4) + '%');
  check('Mega Millions implied rate is also a plausible Treasury-era yield', r > 0.044 && r < 0.052, (r * 100).toFixed(4) + '%');
}

// 8) SOURCE PIN: bundled figures match the values printed on the panel
console.log('\n[8] source pin: bundled pairs match the printed / cited figures');
{
  check('Powerball pair pinned to $1.25B / $572.1M, Dec 17 2025',
        DRAWINGS.powerball.advertised === 1.25e9 && DRAWINGS.powerball.cash === 572.1e6 && DRAWINGS.powerball.date === 'December 17, 2025');
  check('Mega Millions pair pinned to $680M / $318.2M, Oct 24 2025',
        DRAWINGS.megamillions.advertised === 680e6 && DRAWINGS.megamillions.cash === 318.2e6 && DRAWINGS.megamillions.date === 'October 24, 2025');
}

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