#!/usr/bin/env node
// verify-dollar-cost-averaging-vs-lump-sum.mjs
//
// Offline gate for /strata/dollar-cost-averaging-vs-lump-sum/. It loads the SAME bundled
// series the page ships (series.json: Shiller monthly S&P Composite price, dividends, CPI,
// 1871-01..2024-06, plus the 3-month T-bill TB3MS aligned by month) and recomputes every
// headline the page shows, exiting 0 only if all checks pass. Where possible each fact is
// verified two independent ways.
//
// The engine (identical to the page's inline script):
//   equity total return  eq[t+1] = eq[t] * (P[t+1] + D[t]/12) / P[t)     (dividends reinvested)
//   bond proxy (10y CM)  bo[t+1] = bo[t] * (1 + y0/12 + DUR*(y0 - y1))   (income + duration*Dy)
//   cash on the sideline = 3-mo T-bill from 1934, the 10y yield before T-bills traded
//   LUMP end   = W * A[tE] / A[t0]
//   DCA  end   = sum_k (W/N) * cashF(t0,k) * A[tE] / A[t0+k]
//   win        = LUMP end > DCA end
//
// Run:  node research/dollar-cost-averaging-vs-lump-sum/verify-dollar-cost-averaging-vs-lump-sum.mjs

'use strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const S = JSON.parse(fs.readFileSync(path.join(here, 'series.json'), 'utf8'));
const RTRC = JSON.parse(fs.readFileSync(path.join(here, 'shiller-rtr.json'), 'utf8')).RTR;
const { n, P, D, CPI, GS10, TB } = S;

// ---- build the engine ------------------------------------------------------------
const eq = new Float64Array(n); eq[0] = 1;
for (let t = 0; t < n - 1; t++) eq[t + 1] = eq[t] * ((P[t + 1] + D[t] / 12) / P[t]);
const DUR = 8.0;
const bo = new Float64Array(n); bo[0] = 1;
for (let t = 0; t < n - 1; t++) { const y0 = (GS10[t] || 0) / 100, y1 = (GS10[t + 1] || 0) / 100; bo[t + 1] = bo[t] * (1 + y0 / 12 + DUR * (y0 - y1)); }
const shortRate = (i) => (TB[i] != null ? TB[i] : (GS10[i] || 0));
const cumCash = new Float64Array(n); cumCash[0] = 1;
for (let t = 0; t < n - 1; t++) cumCash[t + 1] = cumCash[t] * (1 + shortRate(t) / 100 / 12);
const cashF = (t0, k, on) => (on ? cumCash[t0 + k] / cumCash[t0] : 1);

const portCache = new Map();
function portIndex(w) {
  if (w >= 0.999) return eq;
  const key = w.toFixed(4); if (portCache.has(key)) return portCache.get(key);
  const A = new Float64Array(n); A[0] = 1;
  for (let i = 0; i < n - 1; i++) { const er = eq[i + 1] / eq[i] - 1, br = bo[i + 1] / bo[i] - 1; A[i + 1] = A[i] * (1 + w * er + (1 - w) * br); }
  portCache.set(key, A); return A;
}
const idx = (y, m) => (y - 1871) * 12 + (m - 1);
const monY = (i) => 1871 + Math.floor(i / 12);
const monM = (i) => i % 12 + 1;
const dlabel = (i) => monY(i) + '-' + ('0' + monM(i)).slice(-2);

// method A: ratio comparison (W factors out)
function raceRatio(a, b, H, N, w, on) {
  const A = portIndex(w);
  let wins = 0, tot = 0, sumL = 0, sumD = 0, nL = 0, nD = 0, sLE = 0, worst = Infinity, worstAt = -1;
  a = Math.max(0, a);
  for (let t0 = a; t0 <= b; t0++) {
    const tE = t0 + H; if (tE >= n) break;
    const lump = A[tE] / A[t0]; let dca = 0;
    for (let k = 0; k < N; k++) dca += (1 / N) * cashF(t0, k, on) * (A[tE] / A[t0 + k]);
    tot++; sumL += lump; sumD += dca;
    const edge = (lump - dca) / dca;
    if (lump > dca) { wins++; nL++; sLE += edge; } else { nD++; }
    if (edge < worst) { worst = edge; worstAt = t0; }
  }
  return { winRate: tot ? wins / tot * 100 : 0, tot, avgEdge: sumD ? (sumL / sumD - 1) * 100 : 0,
    avgLumpWin: nL ? sLE / nL * 100 : 0, worst: worst === Infinity ? 0 : worst * 100, worstAt };
}
// method B: full dollar-by-dollar simulation of actual share counts
function raceDollars(a, b, H, N, w, on, W) {
  const A = portIndex(w), s = W / N; let wins = 0, tot = 0;
  a = Math.max(0, a);
  for (let t0 = a; t0 <= b; t0++) {
    const tE = t0 + H; if (tE >= n) break;
    const lumpEnd = (W / A[t0]) * A[tE];
    let dcaEnd = 0;
    for (let k = 0; k < N; k++) { const dollars = s * cashF(t0, k, on); dcaEnd += (dollars / A[t0 + k]) * A[tE]; }
    tot++; if (lumpEnd > dcaEnd) wins++;
  }
  return { winRate: tot ? wins / tot * 100 : 0, tot };
}

// ---- run the checks --------------------------------------------------------------
let passed = 0, failed = 0;
function check(name, cond, detail) {
  const tag = cond ? 'PASS' : 'FAIL';
  console.log(`${tag}  ${name}${detail ? '  ::  ' + detail : ''}`);
  cond ? passed++ : failed++;
}
console.log('=== dollar-cost-averaging-vs-lump-sum :: recomputed from the bundled series ===');
console.log(`series: ${dlabel(0)} to ${dlabel(n - 1)}, ${n} monthly rows (${S.source})\n`);

// (0) SOURCE PIN
check('source pin: first row 1871-01', monY(0) === 1871 && monM(0) === 1);
check('source pin: last row 2024-06', monY(n - 1) === 2024 && monM(n - 1) === 6);
check('source pin: row count 1842', n === 1842, `n=${n}`);
check('source pin: CPI present and positive (for real readouts)', CPI.every((c) => c > 0));

// (1) EQUITY ENGINE cross-check vs Shiller's own Real Total Return column (independent source)
let worstRel = 0, worstRelAt = 0;
for (let t = 0; t < n - 1; t++) {
  const gMine = eq[t + 1] / eq[t];                                   // my nominal TR growth
  const gShiller = (RTRC[t + 1] * CPI[t + 1]) / (RTRC[t] * CPI[t]);  // Shiller real*CPI = nominal growth
  const rel = Math.abs(gMine - gShiller) / gShiller;
  if (rel > worstRel) { worstRel = rel; worstRelAt = t; }
}
check('equity total-return matches Shiller RTR column within 0.1%/mo',
  worstRel < 0.001, `worst monthly diff ${(worstRel * 100).toFixed(4)}% at ${dlabel(worstRelAt)}`);

// (2) VANGUARD 2012 US FRAME reproduces ~67% and ~2.3% magnitude (60/40, 12mo, 10yr, 1926-2011)
const vg12 = raceRatio(idx(1926, 1), idx(2011, 12), 120, 12, 0.6, true);
const vg12eq = raceRatio(idx(1926, 1), idx(2011, 12), 120, 12, 1.0, true);
console.log(`   [Vanguard 2012 US]  60/40 = ${vg12.winRate.toFixed(1)}% win, +${vg12.avgEdge.toFixed(2)}% avg edge  |  100% equity = ${vg12eq.winRate.toFixed(1)}% win, +${vg12eq.avgEdge.toFixed(2)}% avg edge  (published: 67%, +2.3%)`);
check('Vanguard-2012 US 60/40 12mo/10yr win-rate in 62-71%', vg12.winRate >= 62 && vg12.winRate <= 71, `${vg12.winRate.toFixed(1)}%`);
check('Vanguard-2012 US average edge near published 2.3% (1-4%)', vg12.avgEdge >= 1 && vg12.avgEdge <= 4, `+${vg12.avgEdge.toFixed(2)}%`);

// (3) VANGUARD 2023 FRAME reproduces ~68% direction (1yr horizon, 3mo spread, 1976-2022)
const vg23 = raceRatio(idx(1976, 1), idx(2022, 12), 12, 3, 1.0, true);
console.log(`   [Vanguard 2023]  single US index, 1yr/3mo = ${vg23.winRate.toFixed(1)}%  (published global: 68%)`);
check('Vanguard-2023 1yr/3mo win-rate in 58-72%', vg23.winRate >= 58 && vg23.winRate <= 72, `${vg23.winRate.toFixed(1)}%`);

// (4) MONOTONICITY: lump win-rate non-decreasing as the DCA spread lengthens (full history, 100% eq)
const spreads = [3, 6, 12, 24, 36];
let mono = true, prev = -1; const sweep = [];
for (const N of spreads) { const wr = raceRatio(idx(1871, 1), n - 1 - 120, 120, N, 1.0, true).winRate; sweep.push(`${N}mo=${wr.toFixed(1)}%`); if (wr < prev - 1e-9) mono = false; prev = wr; }
console.log(`   [spread sweep, full history, 100% eq]  ${sweep.join('  ')}`);
check('lump win-rate non-decreasing as spread 3->36mo', mono);
check('36mo spread strictly beats 12mo spread (longer = surer)',
  raceRatio(idx(1871, 1), n - 1 - 120, 120, 36, 1.0, true).winRate > raceRatio(idx(1871, 1), n - 1 - 120, 120, 12, 1.0, true).winRate);

// (5) CASH-DRAG GUARD: 0% cash strictly inflates lump's measured win-rate vs the short rate
const withCash = raceRatio(idx(1871, 1), n - 1 - 120, 120, 12, 1.0, true).winRate;
const zeroCash = raceRatio(idx(1871, 1), n - 1 - 120, 120, 12, 1.0, false).winRate;
check('0% cash strictly raises lump win-rate vs short rate',
  zeroCash > withCash, `0%-cash ${zeroCash.toFixed(1)}% > short-rate ${withCash.toFixed(1)}%`);

// (6) AMOUNT INVARIANCE: win-rate identical at three windfall sizes (via the dollar simulation)
const wr1k = raceDollars(idx(1934, 1), idx(2011, 12), 120, 12, 1.0, true, 1000).winRate;
const wr100k = raceDollars(idx(1934, 1), idx(2011, 12), 120, 12, 1.0, true, 100000).winRate;
const wr5m = raceDollars(idx(1934, 1), idx(2011, 12), 120, 12, 1.0, true, 5000000).winRate;
check('win-rate amount-invariant across $1k / $100k / $5M',
  Math.abs(wr1k - wr100k) < 1e-9 && Math.abs(wr100k - wr5m) < 1e-9, `${wr1k.toFixed(3)}% == ${wr100k.toFixed(3)}% == ${wr5m.toFixed(3)}%`);

// (7) TWO INDEPENDENT METHODS AGREE: ratio comparison == dollar simulation (default frame)
const defRatio = raceRatio(idx(1871, 1), n - 1 - 120, 120, 12, 1.0, true).winRate;
const defDollars = raceDollars(idx(1871, 1), n - 1 - 120, 120, 12, 1.0, true, 100000).winRate;
console.log(`   [default frame, full history, 100% eq, 12mo/10yr]  ratio method ${defRatio.toFixed(2)}%  |  dollar sim ${defDollars.toFixed(2)}%`);
check('ratio method and dollar simulation give the same win-rate',
  Math.abs(defRatio - defDollars) < 1e-9, `${defRatio.toFixed(4)}% == ${defDollars.toFixed(4)}%`);
check('default headline is about two-thirds (60-68%)', defRatio >= 60 && defRatio <= 68, `${defRatio.toFixed(1)}%`);

// (8) DCA WINS THE CRASHES: the worst-for-lump window sits on a named historical crash
const worstAt = vg12eq.worstAt >= 0 ? vg12eq.worstAt : raceRatio(idx(1871, 1), n - 1 - 120, 120, 12, 1.0, true).worstAt;
const wy = monY(worstAt);
const isCrash = (wy >= 1928 && wy <= 1932) || (wy >= 1936 && wy <= 1938) || (wy >= 1905 && wy <= 1907) ||
                (wy >= 1972 && wy <= 1974) || (wy >= 1999 && wy <= 2001) || (wy >= 2006 && wy <= 2008);
console.log(`   [regret]  worst window for lump starts ${dlabel(vg12eq.worstAt)} (DCA +${(-vg12eq.worst).toFixed(1)}%)`);
check('worst-for-lump window coincides with a named crash', isCrash, `starts ${dlabel(worstAt)}`);

// ---- honest scope note (not a check, printed for the reader) ----------------------
const vg12_36 = raceRatio(idx(1926, 1), idx(2011, 12), 120, 36, 0.6, true).winRate;
console.log(`\nNOTE (named gap, not asserted): Vanguard reported lump beating 36-month DCA in ~90% of US`);
console.log(`  10-year spans; our single-index engine reaches ${vg12_36.toFixed(1)}% (60/40) on that frame. Same`);
console.log(`  direction (edge rises with the spread), different benchmark (Shiller S&P + Treasury vs a`);
console.log(`  proprietary local 60/40 blend). We show our reproducible number, not theirs.`);

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