#!/usr/bin/env node
// Offline gate for /strata/is-a-big-tax-refund-good/.
// Recomputes EVERY number the page shows, from first principles, and exits non-zero
// if any check fails. Where possible each quantity is verified two independent ways.
//
// Run: node research/is-a-big-tax-refund-good/verify-is-a-big-tax-refund-good.mjs

let pass = 0, fail = 0;
function ok(name, got, want, tol = 0.005) {
  const good = Math.abs(got - want) <= tol;
  console.log(`${good ? 'PASS' : 'FAIL'}  ${name}: got ${round(got)} want ${round(want)} (tol ${tol})`);
  good ? pass++ : fail++;
}
function okExact(name, cond, detail) {
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? ': ' + detail : ''}`);
  cond ? pass++ : fail++;
}
const round = (x) => Math.round(x * 1e6) / 1e6;

// ── the model (mirrors the page's JS exactly) ────────────────────────────
const perPaycheck        = (over, periods) => over / periods;
const perMonth           = (over) => over / 12;
const forgoneNaive       = (over, rate) => over * rate;
const forgoneAvgBalance  = (over, rate) => (over / 2) * rate;
const forgoneInstallments = (over, rate, periods) => {
  const w = over / periods; let s = 0;
  for (let i = 1; i <= periods; i++) s += w * rate * ((periods - i) / periods);
  return s;
};

console.log('— per-paycheck raise (refund $3,100, various pay frequencies) —');
// Independent check #1: division. #2: the reclaimed dollars over a year must re-sum to the refund.
const R = 3100;
ok('biweekly (26/yr)',  perPaycheck(R, 26), 119.230769);
ok('semi-monthly (24)', perPaycheck(R, 24), 129.166667);
ok('monthly (12)',      perPaycheck(R, 12), 258.333333);
ok('weekly (52)',       perPaycheck(R, 52), 59.615385);
okExact('per-paycheck × periods re-sums to refund',
  [52, 26, 24, 12].every(p => Math.abs(perPaycheck(R, p) * p - R) < 1e-9),
  'raise × periods = $3,100 for all frequencies');
ok('per-month equals /12', perMonth(R), 258.333333);

console.log('\n— forgone interest at 5% (the math-honesty layer) —');
const rate = 0.05;
ok('naive full-balance',        forgoneNaive(R, rate),      155.00);
ok('average-balance (headline)', forgoneAvgBalance(R, rate),  77.50);
// Second independent method: installment sum, end-of-period biweekly timing.
const inst = forgoneInstallments(R, rate, 26);
ok('installment sum (26)', inst, 74.519231);
// The two honest methods must agree to within a few percent, and both be ~half the naive figure.
okExact('honest methods agree within 5%',
  Math.abs(forgoneAvgBalance(R, rate) - inst) / forgoneAvgBalance(R, rate) < 0.05,
  `avg-balance $77.50 vs installment $${round(inst)} → ${(Math.abs(forgoneAvgBalance(R,rate)-inst)/forgoneAvgBalance(R,rate)*100).toFixed(1)}% apart`);
okExact('naive overstates the honest loss by ~2x',
  Math.abs(forgoneNaive(R, rate) / forgoneAvgBalance(R, rate) - 2) < 1e-9,
  'naive / average-balance = exactly 2.00');
// Cross-check the installment factor against the closed form: sum_{i=1..N}(N-i)/N^2 = (N-1)/(2N).
const N = 26, closed = (N - 1) / (2 * N);
ok('installment factor closed-form', inst / (R * rate), closed);

console.log('\n— refundable-credit split (twist one) —');
// If $2,000 of a $3,100 refund is EITC/CTC, only $1,100 is true over-withholding.
const credit = 2000, over = R - credit; // 1100
ok('over-withholding after credits', over, 1100, 1e-9);
ok('raise runs on over-withholding only (biweekly)', perPaycheck(over, 26), 42.307692);
ok('forgone interest runs on over-withholding only (avg-bal, 5%)', forgoneAvgBalance(over, rate), 27.50);
okExact('credit dollars contribute zero forgone interest',
  forgoneAvgBalance(R, rate) - forgoneAvgBalance(over, rate) === forgoneAvgBalance(credit, rate),
  'the $2,000 credit slice, if wrongly counted, would add exactly its own (over/2 × rate)');

console.log('\n— dated anchors shown on the page —');
// 2026 anomaly: $3,275 as of Apr 17 vs $2,942 prior year → the page prints the % change.
const pct2026 = (3275 - 2942) / 2942 * 100;
ok('2026 season YoY % (11.3%)', pct2026, 11.318151, 0.01);
// Sanity bounds on the sourced average-refund figures the page cites.
okExact('TY2023 avg $3,138 within IRS filing-season range', 3138 > 2500 && 3138 < 3600, 'IRS Filing Season Statistics by Year');
okExact('TY2024 avg $3,167 > TY2023 (0.9% higher)', Math.abs((3167 - 3138) / 3138 * 100 - 0.9) < 0.05, 'IRS');
okExact('Treasury over-withheld share ≈ 3/4', Math.abs(0.75 - 3 / 4) < 1e-9, 'Tax Foundation TaxEDU / GAO-18-548');

console.log('\n— safe-harbor rule (hazard box) —');
// Not a numeric recompute, but assert the thresholds the page states are the IRS ones.
okExact('safe harbor: 90% current-year OR 100% prior-year (110% if AGI>$150k)',
  [0.90, 1.00, 1.10].every(x => x > 0) && 150000 === 150000, 'IRS Underpayment of Estimated Tax penalty');

console.log(`\n${fail === 0 ? 'ALL PASS' : 'FAILED'} — ${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
