#!/usr/bin/env node
// Offline gate for /strata/renting-throwing-money-away/
// Recomputes EVERY number shown on the page from first principles, two independent
// ways where possible. Exits 0 iff all checks pass, non-zero otherwise.
//
// Sources for the claimed numbers:
//   Ben Felix / PWL Capital, "Rent or Own Your Home? A Handy 5% Rule"
//   https://pwlcapital.com/rent-or-own-your-home-5-rule/
//   Components: ~1% property tax + ~1% maintenance + ~3% cost of capital = 5%.
//   Break-even monthly rent = home price x 5% / 12.  $500,000 -> $2,083.33/mo.

let pass = 0, fail = 0;
function check(name, ok, got, want) {
  const line = ok ? 'PASS' : 'FAIL';
  console.log(`[${line}] ${name}` + (got !== undefined ? `  got=${got}` + (want !== undefined ? ` want=${want}` : '') : ''));
  ok ? pass++ : fail++;
}
const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;

// ── finance primitives (identical to the page) ────────────────────────────
function mortgagePayment(P, rMonthly, n) {
  if (rMonthly === 0) return P / n;
  const f = Math.pow(1 + rMonthly, n);
  return P * rMonthly * f / (f - 1);
}
function balanceAfter(P, rMonthly, n, k) {
  if (rMonthly === 0) return P * (1 - k / n);
  const M = mortgagePayment(P, rMonthly, n);
  const fk = Math.pow(1 + rMonthly, k);
  return P * fk - M * (fk - 1) / rMonthly;
}

// ══════════════════════════════════════════════════════════════════════════
// 1. THE 5% LINE  (Felix headline — exact arithmetic)
// ══════════════════════════════════════════════════════════════════════════
const tax = 0.01, maint = 0.01, coc = 0.03;
const rate5 = tax + maint + coc;
check('5% rule components sum to 5%', near(rate5, 0.05), rate5, 0.05);

const price = 500000;
const annual = price * rate5;
check('$500k annual unrecoverable cost = $25,000', near(annual, 25000), annual, 25000);

const breakeven = annual / 12;
check('break-even monthly rent = $2,083.33', near(breakeven, 2083.3333, 1e-3), breakeven.toFixed(4), '2083.3333');

// independent route: price / (1/0.05) / 12  == price*0.05/12
const breakeven2 = (price / (1 / 0.05)) / 12;
check('break-even via price / (1/5%) / 12 agrees', near(breakeven, breakeven2), breakeven2.toFixed(4));

// ══════════════════════════════════════════════════════════════════════════
// 2. MORTGAGE PAYMENT  (closed form vs amortize-to-zero)
// ══════════════════════════════════════════════════════════════════════════
const loan = 400000, rM = 0.065 / 12, n = 360;
const M = mortgagePayment(loan, rM, n);
check('30y payment on $400k @ 6.5% ≈ $2,528.27/mo', near(M, 2528.27, 0.5), M.toFixed(2), '2528.27');

// independent: run the amortization forward; balance must land on ~0 at term
let bal = loan;
for (let i = 0; i < n; i++) bal = bal * (1 + rM) - M;
check('amortize 360 payments -> ending balance ≈ 0', Math.abs(bal) < 1e-4, bal.toExponential(2), '~0');

// remaining balance after 108 months: closed form vs forward recursion
const k = 108;
const balClosed = balanceAfter(loan, rM, n, k);
let balLoop = loan;
for (let i = 0; i < k; i++) balLoop = balLoop * (1 + rM) - M;
check('balance @108mo: closed form == recursion', near(balClosed, balLoop, 1e-4), balClosed.toFixed(2), balLoop.toFixed(2));

// ── amortization split of payment 1 (shown on the page) ───────────────────
const int1 = loan * rM, prin1 = M - int1;
check('payment-1 interest = loan*rate/12', near(int1, 400000 * 0.065 / 12), int1.toFixed(2));
check('payment-1 principal = M - interest', near(prin1, M - int1), prin1.toFixed(2));
check('payment 1 is >85% interest (the "throwing away" point)', int1 / M > 0.85, (100 * int1 / M).toFixed(1) + '%');

// ══════════════════════════════════════════════════════════════════════════
// 3. THE NET-WORTH RACE  (month-loop simulation == closed-form assembly)
// ══════════════════════════════════════════════════════════════════════════
const BUY_FRAC = 0.05, SELL_FRAC = 0.05, TERM_YEARS = 30;

function simulate(price, downFrac, rateA, retA, aprA, years, monthlyRent, taxF, maintF) {
  const H = price, D = downFrac * H, loanP = H - D;
  const buyClose = BUY_FRAC * H;
  const r = rateA / 12, ret = retA / 12, apr = aprA, nn = TERM_YEARS * 12;
  const pay = mortgagePayment(loanP, r, nn);
  const mTax = H * taxF / 12, mMaint = H * maintF / 12;
  const ownerOutlay = pay + mTax + mMaint;
  const diff = ownerOutlay - monthlyRent;
  let renterInvest = D + buyClose, ownerInvest = 0;
  const months = Math.round(years * 12);
  for (let i = 1; i <= months; i++) {
    renterInvest *= (1 + ret); ownerInvest *= (1 + ret);
    if (diff > 0) renterInvest += diff; else ownerInvest += (-diff);
  }
  const homeVal = H * Math.pow(1 + apr, years);
  const balF = balanceAfter(loanP, r, nn, months);
  const sellClose = SELL_FRAC * homeVal;
  const ownerNW = homeVal - balF - sellClose + ownerInvest;
  return { ownerNW, renterNW: renterInvest, pay, ownerOutlay, diff, homeVal, balF };
}

const sim = simulate(500000, 0.20, 0.065, 0.065, 0.035, 9, breakeven, tax, maint);

// independent closed-form check of the renter path:
//   FV = (D+buy)*(1+ret)^m  +  diff * [((1+ret)^m - 1)/ret]     (ordinary annuity)
const ret = 0.065 / 12, m = 108;
const growth = Math.pow(1 + ret, m);
const renterClosed = (100000 + 0.05 * 500000) * growth + sim.diff * ((growth - 1) / ret);
check('renter net worth: month-loop == closed-form annuity',
  near(sim.renterNW, renterClosed, 1e-4), sim.renterNW.toFixed(2), renterClosed.toFixed(2));

// independent closed-form check of the owner path
const homeVal9 = 500000 * Math.pow(1.035, 9);
const bal9 = balanceAfter(400000, 0.065 / 12, 360, 108);
const ownerClosed = homeVal9 - bal9 - 0.05 * homeVal9; // owner invests nothing at defaults (diff>0)
check('owner outlay exceeds break-even rent (owner invests $0 at defaults)', sim.diff > 0, sim.diff.toFixed(2));
check('owner net worth == closed-form assembly',
  near(sim.ownerNW, ownerClosed, 1e-4), sim.ownerNW.toFixed(2), ownerClosed.toFixed(2));

// the page's default verdict: renting wins the 9-year race
check('at defaults, renter is ahead after 9 years', sim.renterNW > sim.ownerNW,
  `renter ${Math.round(sim.renterNW)} > owner ${Math.round(sim.ownerNW)}`);

// ── the ruler-twist must be real: pushing appreciation up flips it ─────────
const simHiApr = simulate(500000, 0.20, 0.065, 0.065, 0.075, 9, breakeven, tax, maint);
check('raise appreciation to 7.5% -> OWNER wins (leverage flip is real)',
  simHiApr.ownerNW > simHiApr.renterNW,
  `owner ${Math.round(simHiApr.ownerNW)} > renter ${Math.round(simHiApr.renterNW)}`);

// ── horizon effect, stated HONESTLY. With a persistent 3-pt return>appreciation
//    gap AND rent held constant, the renter wins at every horizon (the model
//    flatters renting by freezing rent). The transaction-cost/horizon flip is
//    real only when appreciation is competitive: then a SHORT stay favors the
//    renter (round-trip costs) and a LONG stay favors the owner (leverage).
const simDefLong = simulate(500000, 0.20, 0.065, 0.065, 0.035, 30, breakeven, tax, maint);
check('defaults (housing trails 3 pts): renter still wins at 30y (no pure-horizon flip)',
  simDefLong.renterNW > simDefLong.ownerNW,
  `renter ${Math.round(simDefLong.renterNW)} > owner ${Math.round(simDefLong.ownerNW)}`);

const compShort = simulate(500000, 0.20, 0.065, 0.065, 0.065, 3, breakeven, tax, maint);
const compLong = simulate(500000, 0.20, 0.065, 0.065, 0.065, 20, breakeven, tax, maint);
check('competitive appreciation, 3y stay -> RENTER wins (round-trip costs bite)',
  compShort.renterNW > compShort.ownerNW,
  `renter ${Math.round(compShort.renterNW)} > owner ${Math.round(compShort.ownerNW)}`);
check('competitive appreciation, 20y stay -> OWNER wins (leverage + amortized costs)',
  compLong.ownerNW > compLong.renterNW,
  `owner ${Math.round(compLong.ownerNW)} > renter ${Math.round(compLong.renterNW)}`);

// ── zero-rate degenerate guard ─────────────────────────────────────────────
check('zero-rate payment = principal / n', near(mortgagePayment(360000, 0, 360), 1000), mortgagePayment(360000, 0, 360));

// ══════════════════════════════════════════════════════════════════════════
console.log(`\n${pass} passed, ${fail} failed`);
console.log(`\nHeadline numbers verified:`);
console.log(`  5% rule: 1% tax + 1% maint + 3% cost of capital = 5%/yr of home value`);
console.log(`  $500,000 x 5% / 12 = $${breakeven.toFixed(2)}/mo break-even rent`);
console.log(`  $400k @ 6.5% 30y payment = $${M.toFixed(2)}/mo, payment-1 is ${(100 * int1 / M).toFixed(0)}% interest`);
console.log(`  default 9y race: renter $${Math.round(sim.renterNW).toLocaleString('en-US')} vs owner $${Math.round(sim.ownerNW).toLocaleString('en-US')}`);
process.exit(fail === 0 ? 0 : 1);
