#!/usr/bin/env node
// verify-start-investing-at-25-vs-35.mjs
//
// Recomputes EVERY number shown on /strata/start-investing-at-25-vs-35/ from first
// principles, two independent ways where possible (closed-form annuity vs a
// month-by-month simulation), one line per check. Exits 0 iff all pass.
//
// Engine convention (pinned, and guarded below): MONTHLY contributions, MONTHLY
// compounding, end-of-month deposits (ordinary annuity):
//     FV = M * ((1+i)^n - 1)/i,   i = r/12, n = months
//     lump growth  P0 * (1+i)^n
//
// Run: node research/start-investing-at-25-vs-35/verify-start-investing-at-25-vs-35.mjs

let fails = 0;
function check(label, cond, detail) {
  const tag = cond ? 'PASS' : 'FAIL';
  if (!cond) fails++;
  console.log(`[${tag}] ${label}${detail ? '  ::  ' + detail : ''}`);
}
const approx = (a, b, tol) => Math.abs(a - b) <= tol;
const usd = (n) => '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

// ── Method 1: closed form ────────────────────────────────────────────────
function fvAnnuity(M, r, months) {
  const i = r / 12;
  if (months <= 0) return 0;
  return i === 0 ? M * months : M * ((Math.pow(1 + i, months) - 1) / i);
}
function grow(P, r, months) { return P * Math.pow(1 + r / 12, months); }
function finalBalance(startAge, stopAge, M, r, retireAge) {
  const contribEnd = Math.min(stopAge, retireAge);
  const mContrib = Math.round((contribEnd - startAge) * 12);
  const mCoast = Math.round((retireAge - contribEnd) * 12);
  return grow(fvAnnuity(M, r, Math.max(0, mContrib)), r, mCoast);
}

// ── Method 2: independent month-by-month simulation ──────────────────────
// b_{k+1} = b_k*(1+i) + (contributing ? M : 0). Provably equals the closed form.
function simulate(startAge, stopAge, M, r, retireAge) {
  const i = r / 12;
  const contribEnd = Math.min(stopAge, retireAge);
  const N = Math.round((retireAge - startAge) * 12);
  const stopK = Math.round((contribEnd - startAge) * 12);
  let b = 0;
  for (let t = 0; t < N; t++) { b = b * (1 + i) + (t < stopK ? M : 0); }
  return b;
}

const M = 300, R = 0.07, RET = 65;
console.log('== engine: monthly contributions, monthly compounding, ordinary annuity; M=$300, r=7%, retire 65 ==\n');

// ── two engines must agree (this is what lets "closed form" and "simulation" count as independent) ──
{
  const cases = [[25, 65], [35, 65], [25, 35], [45, 65]];
  let ok = true, worst = 0;
  for (const [s, stop] of cases) {
    const cf = finalBalance(s, stop, M, R, RET), sm = simulate(s, stop, M, R, RET);
    worst = Math.max(worst, Math.abs(cf - sm));
    ok = ok && approx(cf, sm, 0.01);
  }
  check('closed form and month-by-month simulation agree to a cent', ok, 'max diff ' + worst.toExponential(2));
}

// ══ (1) SAME-CONTRIBUTION FRAME ══════════════════════════════════════════
const start25 = fvAnnuity(M, R, 480);   // 40 yrs
const start35 = fvAnnuity(M, R, 360);   // 30 yrs
check('same-contribution: start-25 balance = $787,444', approx(start25, 787444, 1), usd(start25));
check('same-contribution: start-35 balance = $365,991', approx(start35, 365991, 1), usd(start35));
check('same-contribution: (sim) start-25 = $787,444', approx(simulate(25, 65, M, R, RET), 787444, 1), usd(simulate(25, 65, M, R, RET)));
check('same-contribution: (sim) start-35 = $365,991', approx(simulate(35, 65, M, R, RET), 365991, 1), usd(simulate(35, 65, M, R, RET)));
const sameRatio = start25 / start35;
check('same-contribution ratio = 2.152 (a 10-yr head start MORE than doubles)', approx(sameRatio, 2.152, 0.001), sameRatio.toFixed(4) + 'x');
check('dollars in: start-25 = $144,000, start-35 = $108,000', M * 480 === 144000 && M * 360 === 108000, '$' + (M * 480) + ' vs $' + (M * 360));

// ratio is INVARIANT to the monthly contribution (linear system) -> recompute at 3 different M
{
  let ok = true, seen = [];
  for (const m of [100, 300, 1000]) {
    const ratio = fvAnnuity(m, R, 480) / fvAnnuity(m, R, 360);
    seen.push(m + '->' + ratio.toFixed(6));
    ok = ok && approx(ratio, sameRatio, 1e-9);
  }
  check('same-contribution ratio is invariant to M (2.1515x at M=$100/$300/$1000)', ok, seen.join('  '));
}

// ══ (2) STOP-EARLY FRAME (the flip) ══════════════════════════════════════
const early = grow(fvAnnuity(M, R, 120), R, 360);   // pay 25-35, coast to 65
const late = fvAnnuity(M, R, 360);                  // pay 35-65
check('stop-early: early (pay 25-35, coast) = $421,453', approx(early, 421453, 1), usd(early));
check('stop-early: late (pay 35-65) = $365,991', approx(late, 365991, 1), usd(late));
check('stop-early: (sim) early = $421,453', approx(simulate(25, 35, M, R, RET), 421453, 1), usd(simulate(25, 35, M, R, RET)));
check('stop-early: late equals same-contribution start-35 (identical computation)', approx(late, start35, 1e-9), usd(late));
const stopRatio = early / late;
check('stop-early ratio out = 1.152 (less in, more out)', approx(stopRatio, 1.152, 0.001), stopRatio.toFixed(4) + 'x');
const earlyIn = M * 120, lateIn = M * 360;
check('stop-early: early put in EXACTLY one third of late ($36,000 vs $108,000)', earlyIn * 3 === lateIn, '$' + earlyIn + ' * 3 = $' + (earlyIn * 3) + ' = $' + lateIn);
check('stop-early: early ends ahead despite one third the dollars', early > late, usd(early) + ' > ' + usd(late));
check('stop-early: delta of displayed (rounded) balances = $55,462', Math.round(early) - Math.round(late) === 55462, '$' + (Math.round(early) - Math.round(late)));

// ══ (3) THE FLOOR (break-even return) ════════════════════════════════════
function earlyF(r) { return grow(fvAnnuity(M, r, 120), r, 360); }
function lateF(r) { return fvAnnuity(M, r, 360); }
function breakEven() {
  let lo = 0.001, hi = 0.12;
  for (let k = 0; k < 200; k++) { const mid = (lo + hi) / 2; if (earlyF(mid) - lateF(mid) > 0) hi = mid; else lo = mid; }
  return (lo + hi) / 2;
}
const be = breakEven();
check('floor: break-even rate = 6.109% (early ties late at 65)', approx(be * 100, 6.109, 0.005), (be * 100).toFixed(4) + '%');
check('floor: at 6.00% the LATE saver wins ($296,093 < $301,355)',
  earlyF(0.06) < lateF(0.06) && approx(earlyF(0.06), 296093, 1) && approx(lateF(0.06), 301355, 1),
  usd(earlyF(0.06)) + ' < ' + usd(lateF(0.06)));
check('floor: at 7.00% the EARLY saver wins', earlyF(0.07) > lateF(0.07), usd(earlyF(0.07)) + ' > ' + usd(lateF(0.07)));
check('floor: at 5.00% the late saver wins clearly ($208,128 < $249,678)',
  earlyF(0.05) < lateF(0.05) && approx(earlyF(0.05), 208128, 1) && approx(lateF(0.05), 249678, 1),
  usd(earlyF(0.05)) + ' < ' + usd(lateF(0.05)));
check('floor: the sign flip straddles the solved root (6% below wins-late, 7% above wins-early)',
  (earlyF(0.06) - lateF(0.06) < 0) && (earlyF(0.07) - lateF(0.07) > 0), 'straddled');

// ══ (4) THE MECHANISM (true at every rate, incl. below the floor) ════════
// Per-dollar head start of investing 10 years earlier, ANNUAL-compounding statement.
check('mechanism: (1.07)^10 = 1.9672 (a dollar at 25 vs 35, annual)', approx(Math.pow(1.07, 10), 1.9672, 0.0001), Math.pow(1.07, 10).toFixed(4) + 'x');
{
  let ok = true, seen = [];
  for (const r of [0.05, 0.061, 0.07]) {   // includes rates BELOW the 6.109% floor
    const headStart = Math.pow(1 + r, 10);
    // definition check: value of $1 at r for 10 extra years, annual compounding
    const oneDollar = 1 * Math.pow(1 + r, 10);
    seen.push((r * 100).toFixed(1) + '%->' + headStart.toFixed(4) + 'x');
    ok = ok && approx(headStart, oneDollar, 1e-12) && headStart > 1;
  }
  check('mechanism holds at every rate incl. below the floor (5%,6.1%,7%): head start = (1+r)^10 > 1', ok, seen.join('  '));
}

// ══ (5) CONVENTION PINS + pure-compounding easter egg ════════════════════
const DAMODARAN_NOMINAL = 10, DAMODARAN_REAL = 7;   // ~10% nominal / ~7% real, 1928-2024 (Damodaran, NYU Stern)
const DETENTS = [2, 4.5, 7, 10];
check('convention: page "stocks real" detent (7%) matches Damodaran real ~7%', DETENTS.includes(DAMODARAN_REAL), '7% real');
check('convention: page "stocks nominal" detent (10%) matches Damodaran nominal ~10%', DETENTS.includes(DAMODARAN_NOMINAL), '10% nominal');
const egg = 1000 * Math.pow(1.10, 45);   // $1,000 at 10% nominal, age 20 -> 65, ANNUAL compounding
check('easter egg: 1000 * (1.10)^45 = $72,890 (annual compounding)', approx(egg, 72890, 1), usd(egg));
check('easter egg: that is ~73x the deposit', approx(egg / 1000, 72.89, 0.01), (egg / 1000).toFixed(2) + 'x');

// ══ (6) COMPOUNDING-CONVENTION GUARD ═════════════════════════════════════
// The page pins monthly/monthly. Prove monthly != each annual convention (so the two
// can't be swapped silently) and pin the SIZE of each shift to what the page states:
// ~2% (start-of-year), ~6% (compounding-only), ~9% (year-end deposit).
const monthly25 = fvAnnuity(M, R, 480);                                   // page headline
const iEff = Math.pow(1 + R, 1 / 12) - 1;                                 // annual-effective monthly rate
const monthlyContribAnnualComp = M * ((Math.pow(1 + iEff, 480) - 1) / iEff);   // change only the compounding basis
const annualEnd = (M * 12) * ((Math.pow(1 + R, 40) - 1) / R);            // annual $3,600 at year-END
const annualDue = annualEnd * (1 + R);                                    // annual $3,600 at year-START
const pctShift = (x) => Math.abs(x - monthly25) / monthly25 * 100;
check('guard: page headline ($787,444) is the MONTHLY/monthly figure', approx(monthly25, 787444, 1), usd(monthly25));
check('guard: compounding-only change (monthly deposits, annual-effective) differs by ~6%', approx(pctShift(monthlyContribAnnualComp), 5.84, 0.2), usd(monthlyContribAnnualComp) + '  (' + pctShift(monthlyContribAnnualComp).toFixed(2) + '%)');
check('guard: annual year-END deposit differs by ~9%', approx(pctShift(annualEnd), 8.73, 0.2), usd(annualEnd) + '  (' + pctShift(annualEnd).toFixed(2) + '%)');
check('guard: annual year-START (due) deposit differs by ~2%', approx(pctShift(annualDue), 2.34, 0.2), usd(annualDue) + '  (' + pctShift(annualDue).toFixed(2) + '%)');
check('guard: every annual convention gives a DIFFERENT figure than monthly (no silent swap)',
  !approx(monthly25, monthlyContribAnnualComp, 1) && !approx(monthly25, annualEnd, 1) && !approx(monthly25, annualDue, 1),
  'all distinct');
// mechanism at the page's own MONTHLY convention: a dollar 10 yrs earlier = (1+r/12)^120
const monthlyHeadStart = Math.pow(1 + R / 12, 120);
check('guard: monthly-engine head start on $1 for 10 yrs = 2.01x (page states this, not 1.97x)', approx(monthlyHeadStart, 2.01, 0.005), monthlyHeadStart.toFixed(4) + 'x');

// ══ (extra) SEQUENCE-OF-RETURNS demo shown in the scope panel ════════════
const R_SET = [-0.15, -0.05, 0.05, 0.15, 0.25];
const mean = R_SET.reduce((a, b) => a + b, 0) / R_SET.length;
function seqEnd(order, contribOn) {
  const C = contribOn ? 1000 : 0, L = contribOn ? 0 : 5000;
  let b = L;
  for (const g of order) b = (b + C) * (1 + g);
  return b;
}
const rise = R_SET.slice().sort((a, b) => a - b);   // bad first, good last
const fall = rise.slice().reverse();
check('sequence: arithmetic mean of the return set is exactly 5%', approx(mean, 0.05, 1e-12), (mean * 100).toFixed(1) + '%');
check('sequence: with a LUMP, both orders end identical (order does not matter)', approx(seqEnd(rise, false), seqEnd(fall, false), 1e-9), usd(seqEnd(rise, false)));
check('sequence: with CONTRIBUTIONS, bad-first ($6,850) beats good-first ($4,699)',
  seqEnd(rise, true) > seqEnd(fall, true) && approx(seqEnd(rise, true), 6849.60, 0.05) && approx(seqEnd(fall, true), 4699.25, 0.05),
  usd(seqEnd(rise, true)) + ' vs ' + usd(seqEnd(fall, true)));

console.log('\n' + (fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'));
process.exit(fails === 0 ? 0 : 1);
