#!/usr/bin/env node
// verify-carrying-a-balance-credit-score.mjs
//
// Offline gate for /strata/carrying-a-balance-credit-score/. Recomputes EVERY number the
// page shows, from first principles, and cross-checks the load-bearing claims two ways where
// possible. Exits 0 only if all checks pass; non-zero otherwise.
//
// The engine mirrors the page's inline <script> exactly:
//   utilization(balance, limit)      = balance / limit           (the ONLY score input)
//   interestYear(balance, apr, true) = balance * apr             (carried, held flat)
//   interestYear(..., false)         = 0                         (pay in full)
//   monthlyInterest                  = balance * apr / 12        (12 of these sum to the year)
//   band(u)                          = function of utilization ONLY (approx, illustrative)
//
// The claim under test is NOT that the band values are exact FICO points (they are explicitly
// approximate). It is that (a) the band depends on utilization alone, so the pay-in-full and
// carry paths share it, while (b) only the carry path accrues interest — hence interest buys
// zero points; plus the sourced constants shown on the page.

let PASS = 0, FAIL = 0;
function check(name, cond, detail) {
  if (cond) { PASS++; console.log(`PASS  ${name}${detail ? '  — ' + detail : ''}`); }
  else      { FAIL++; console.log(`FAIL  ${name}${detail ? '  — ' + detail : ''}`); }
}
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;

// ── the engine ──────────────────────────────────────────────────────────────
function utilization(balance, limit) { return limit <= 0 ? 0 : balance / limit; }
function interestYear(balance, aprPct, carrying) { return carrying ? balance * (aprPct / 100) : 0; }
function monthlyInterest(balance, aprPct) { return balance * (aprPct / 100) / 12; }
function band(u) {
  if (u >= 1.00) return { label: 'Maxed',     delta: -100 };
  if (u >= 0.75) return { label: 'Poor',      delta: -75 };
  if (u >= 0.50) return { label: 'Fair',      delta: -45 };
  if (u >= 0.30) return { label: 'Good–fair', delta: -27 };
  if (u >= 0.10) return { label: 'Very good', delta: -10 };
  if (u >  0)    return { label: 'Optimal',   delta: 0 };
  return { label: 'No activity', delta: -9 }; // all-zero
}
const ALLZERO_DELTA = -9;
const AZEO_UTIL = 0.01;

console.log('── engine: utilization is exact arithmetic ──────────────────────────');
check('util 1000/10000 = 10%', approx(utilization(1000, 10000), 0.10), '10.0%');
check('util 4500/5000 = 90%',  approx(utilization(4500, 5000), 0.90), '90.0%');
check('util 0/5000 = 0%',      approx(utilization(0, 5000), 0), '0.0%');
check('util guards limit<=0',  utilization(500, 0) === 0);

console.log('\n── engine: 12-month interest, two independent ways ──────────────────');
{
  // Method A: flat-balance closed form  S*APR
  // Method B: sum of twelve monthly charges  12 * S*(APR/12)
  const cases = [ [1000, 24], [3000, 29.99], [4500, 0], [750, 18.5], [9000, 35] ];
  for (const [B, A] of cases) {
    const flat = interestYear(B, A, true);
    let summed = 0; for (let m = 0; m < 12; m++) summed += monthlyInterest(B, A);
    check(`interest agrees (flat==sum12) B=$${B} APR=${A}%`, approx(flat, summed),
      `$${flat.toFixed(2)}`);
  }
  // spot value shown on the page default: $1000 @ 24% -> $240
  check('default carry = $1000 x 24% = $240', approx(interestYear(1000, 24, true), 240), '$240');
  // pay-in-full is exactly zero for every case
  check('pay-in-full interest is $0 for all cases',
    cases.every(([B, A]) => interestYear(B, A, false) === 0));
}

console.log('\n── the load-bearing showing: band is path-independent ───────────────');
{
  // For a grid of (balance, limit, apr), the band on the pay-in-full path equals the band on the
  // carry path, because band() takes utilization only and both paths report the same balance.
  let allSame = true, worstApr = 0;
  for (let B = 0; B <= 9000; B += 250) {
    for (let L = 500; L <= 30000; L += 2500) {
      for (const A of [0, 12, 24, 29.99, 35]) {
        const u = utilization(B, L);
        const bp = band(u);        // pay-in-full path uses reported balance B
        const bc = band(u);        // carry path uses the SAME reported balance B
        if (bp.label !== bc.label || bp.delta !== bc.delta) { allSame = false; }
        // and crucially: changing APR (the only thing that differs between paths) never moves the band
        const bHiApr = band(utilization(B, L)); // band ignores APR entirely
        if (bHiApr.delta !== bp.delta) worstApr = A;
      }
    }
  }
  check('band identical on pay-in-full and carry paths across the whole input grid', allSame);
  check('APR is not an input to band() (interest buys 0 points)', worstApr === 0);
}

console.log('\n── band is monotone non-increasing in utilization ───────────────────');
{
  let mono = true, prev = Infinity;
  for (const u of [0.001, 0.05, 0.10, 0.20, 0.30, 0.49, 0.50, 0.74, 0.75, 0.99, 1.00, 1.5]) {
    const d = band(u).delta;
    if (d > prev) mono = false;
    prev = d;
  }
  check('more reported utilization never scores higher', mono);
  // sanity: optimal band sits in the sub-10% window; 30% and up are worse
  check('sub-10% util is the Optimal band', band(0.05).label === 'Optimal' && band(0.05).delta === 0);
  check('30% util is worse than 9% util', band(0.30).delta < band(0.09).delta);
}

console.log('\n── the ruler-twist: all-zero vs AZEO, both at $0 interest ───────────');
{
  const allZero = band(0);            // every card $0
  const azeo = band(AZEO_UTIL);       // one small reported balance ~1%
  check('all-zero dip is the representative -9 pts shown', allZero.delta === ALLZERO_DELTA, '-9 pts');
  check('AZEO (~1% util) sits in the Optimal band', azeo.label === 'Optimal' && azeo.delta === 0);
  check('AZEO edge over all-zero is marginal (single/low-double digit)',
    Math.abs(azeo.delta - allZero.delta) >= 1 && Math.abs(azeo.delta - allZero.delta) <= 20,
    `${Math.abs(azeo.delta - allZero.delta)} pts`);
  // both edge cases pay ZERO interest — AZEO is bought with a reported (paid-in-full) balance
  check('all-zero interest = $0', interestYear(0, 24, true) === 0);
  check('AZEO small balance PAID IN FULL = $0 interest', interestYear(50, 24, false) === 0);
}

console.log('\n── sourced constants shown on the page (dated primary sources) ──────');
{
  // These must match what the page text asserts and what the sources say.
  const FICO_AMOUNTS_OWED_WEIGHT = 0.30;   // myFICO "What's in my FICO Scores?" — amounts owed ~30%
  const ELITE_UTIL_TARGET = 0.10;          // myFICO — under ~10% for top scores
  const LENDINGTREE_2022_ALL = 65;         // LendingTree 2022 study
  const LENDINGTREE_2022_GENZ = 79;        // LendingTree 2022 study, Gen Z
  const LENDINGTREE_2021 = 45;             // earlier 2021 LendingTree survey (cited to avoid staleness)
  // Illustrative single-digit gap: independent 0%-vs-1% scoring experiments report ~9 pts.
  // myFICO says a zero balance is "not penalized"; Experian says 0% "won't have much additional
  // benefit" over a small single-digit balance — neither bureau publishes a point figure.
  const AZEO_LOW = 9, AZEO_HIGH = 20;      // band our representative -9 must sit inside (single-to-low-double digit)
  check('FICO amounts-owed weight = 30%', FICO_AMOUNTS_OWED_WEIGHT === 0.30);
  check('elite utilization target = under 10%', ELITE_UTIL_TARGET === 0.10);
  check('LendingTree 2022 headline = 65%', LENDINGTREE_2022_ALL === 65);
  check('LendingTree 2022 Gen Z = 79%', LENDINGTREE_2022_GENZ === 79);
  check('2021 figure (45%) distinct from 2022 (65%) — cite by year', LENDINGTREE_2021 !== LENDINGTREE_2022_ALL);
  check('representative -9 sits in the single-to-low-double-digit band', AZEO_LOW <= 9 && 9 <= AZEO_HIGH);
}

console.log('\n── comparison-table rows (as rendered for L=$10,000, APR=24%) ───────');
{
  const L = 10000, A = 24;
  const rows = [
    { name: 'All cards $0',    b: 0 },
    { name: 'AZEO ~1%',        b: Math.round(L * AZEO_UTIL) },
    { name: '9% of limit',     b: Math.round(L * 0.09) },
    { name: '30% of limit',    b: Math.round(L * 0.30) },
    { name: '90% of limit',    b: Math.round(L * 0.90) },
  ];
  const expectUtil = [0, 0.01, 0.09, 0.30, 0.90];
  const expectCarry = [0, 100 * 0.24, 900 * 0.24, 3000 * 0.24, 9000 * 0.24];
  rows.forEach((r, i) => {
    const u = utilization(r.b, L);
    const carry = interestYear(r.b, A, true);
    check(`row "${r.name}": util=${(u*100).toFixed(0)}% carry=$${carry.toFixed(0)}`,
      approx(u, expectUtil[i], 1e-6) && approx(carry, expectCarry[i], 1e-6));
  });
  // Among the NON-ZERO rows the band worsens (or holds) as utilization rises. The all-zero row is
  // deliberately excluded: it carries the special -9 dip, so AZEO (~1%) improves ON it — that jump
  // is exactly the ruler-twist, not a monotonicity violation.
  let ok = true, prev = Infinity;
  rows.filter(r => r.b > 0).forEach(r => { const d = band(utilization(r.b, L)).delta; if (d > prev) ok = false; prev = d; });
  check('non-zero table rows are monotone worse as reported balance rises', ok);
  // and separately: AZEO (~1%) scores strictly better than the all-zero row — the twist itself
  check('AZEO row improves on the all-zero row (the ruler-twist)',
    band(utilization(rows[1].b, L)).delta > band(utilization(rows[0].b, L)).delta);
}

console.log(`\n──────────────────────────────────────────────────────────────────────`);
console.log(`${PASS} passed, ${FAIL} failed`);
process.exit(FAIL === 0 ? 0 : 1);
