#!/usr/bin/env node
/*
  Offline gate for /strata/do-gift-cards-expire/.
  Recomputes every date and rule shown on the page from the statute, TWO
  independent ways where a date is involved, and exits non-zero on any failure.

  Statutory basis (all primary):
    - Funds floor: expiration no earlier than 5 years from issuance / last load
        15 U.S.C. 1693l-1(c)(2);  12 CFR 1005.20(e)(2)
    - Fee rule: no dormancy/inactivity/service fee unless no activity for a full
        12 months, and no more than one such fee per calendar month
        15 U.S.C. 1693l-1(b)(2);  12 CFR 1005.20(d)
    - Exclusion: loyalty/award/promotional cards not covered
        12 CFR 1005.20(b)
    - Effective date of the Fed final rule: 2010-08-22
  State layer (dated, changeable patchwork; verifier checks the arithmetic + fork,
  not the immutability of any state rule):
    - CA: no expiration on gift certificates
    - NY: 9-year minimum for purchases on/after 2022-12-10
    - Escheat (DE/NY/NJ/GA/DC ...): reclaimable unclaimed property after a dormancy period
    - ~37 states (CA/TX/FL/IL/OH/PA ...): issuer keeps the balance as breakage
*/

const FED_FLOOR_YEARS = 5;
const FEE_WINDOW_MONTHS = 12;
const NY_MIN_YEARS = 9;
const NY_CUTOFF = "2022-12-10";
const EFFECTIVE_DATE = "2010-08-22";

// ── two independent date routines ────────────────────────────────────────
// Method A: calendar-field arithmetic (mirrors the page).
function addMonthsA(iso, n) {
  const [y, m, d] = iso.split("-").map(Number);
  const tot = (m - 1) + n;
  const ny = y + Math.floor(tot / 12);
  const nm = ((tot % 12) + 12) % 12;          // 0..11
  const dim = new Date(ny, nm + 1, 0).getDate();
  const nd = Math.min(d, dim);
  return fmt(ny, nm + 1, nd);
}
// Method B: independent implementation via a running month counter and a
// hand-rolled days-in-month table (leap-year aware), never touching the Date
// object for the field math.
function daysInMonthB(y, m /*1..12*/) {
  const leap = (y % 4 === 0 && y % 100 !== 0) || (y % 400 === 0);
  return [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
}
function addMonthsB(iso, n) {
  let [y, m, d] = iso.split("-").map(Number); // m is 1..12
  let total = y * 12 + (m - 1) + n;           // absolute month index
  let ny = Math.floor(total / 12);
  let nm = (total % 12) + 1;                   // 1..12
  let nd = Math.min(d, daysInMonthB(ny, nm));
  return fmt(ny, nm, nd);
}
const addYearsA = (iso, n) => addMonthsA(iso, n * 12);
const addYearsB = (iso, n) => addMonthsB(iso, n * 12);
function fmt(y, m, d) {
  return `${y}-${String(m).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
}
function cmp(a, b) { return a < b ? -1 : a > b ? 1 : 0; } // ISO strings sort chronologically

// ── the page's statutory computations (reproduced) ───────────────────────
const STATES = {
  OTHER: { fundsRule: "fed", escheat: false },
  CA:    { fundsRule: "never", escheat: false },
  NY:    { fundsRule: "ny9", escheat: true, dormancy: 5 },
  TX:    { fundsRule: "fed", escheat: false },
  FL:    { fundsRule: "fed", escheat: false },
  IL:    { fundsRule: "fed", escheat: false },
  OH:    { fundsRule: "fed", escheat: false },
  PA:    { fundsRule: "fed", escheat: false },
  DE:    { fundsRule: "fed", escheat: true, dormancy: 5 },
  NJ:    { fundsRule: "fed", escheat: true, dormancy: 5 },
  GA:    { fundsRule: "fed", escheat: true, dormancy: 5 },
  DC:    { fundsRule: "fed", escheat: true, dormancy: 3 },
};
const TYPES = {
  store:   { covered: true },
  network: { covered: true },
  promo:   { covered: false },
};

function fundsExpiry(purchase, typeKey, stateKey, addYears) {
  const t = TYPES[typeKey], st = STATES[stateKey];
  if (!t.covered) return { covered: false };
  if (st.fundsRule === "never") return { covered: true, never: true };
  let yrs = FED_FLOOR_YEARS;
  if (st.fundsRule === "ny9" && cmp(purchase, NY_CUTOFF) >= 0) yrs = NY_MIN_YEARS;
  return { covered: true, years: yrs, date: addYears(purchase, yrs) };
}
function feeWindow(purchase, typeKey, addMonths) {
  if (!TYPES[typeKey].covered) return { covered: false };
  return { covered: true, date: addMonths(purchase, FEE_WINDOW_MONTHS) };
}
function moneyFork(purchase, stateKey, addYears) {
  const st = STATES[stateKey];
  if (st.escheat) return { escheat: true, dormancy: st.dormancy, date: addYears(purchase, st.dormancy) };
  return { escheat: false };
}

// ── test harness ─────────────────────────────────────────────────────────
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 : ""}`); }
}

console.log("verify: do-gift-cards-expire  (CARD Act / EFTA 1693l-1; Reg E 1005.20)\n");

// (0) the two date routines must agree on a spread of dates/offsets (incl. leap edges)
console.log("[0] two independent date routines agree");
{
  const cases = [
    ["2025-12-25", 60], ["2024-02-29", 60], ["2020-02-29", 12], ["2022-12-10", 108],
    ["2023-01-31", 1], ["2023-01-31", 13], ["2000-02-29", 12], ["2019-08-31", 6],
    ["2025-12-25", 12], ["2025-12-25", 108], ["2100-02-28", 12], ["2023-03-31", -1],
  ];
  let agree = true, ex = "";
  for (const [iso, n] of cases) {
    const a = addMonthsA(iso, n), b = addMonthsB(iso, n);
    if (a !== b) { agree = false; ex = `${iso}+${n}mo: A=${a} B=${b}`; break; }
  }
  check("addMonthsA === addMonthsB across leap/EOM cases", agree, agree ? `(${cases.length} cases)` : ex);
}

// (1) federal 5-year funds floor, computed both ways
console.log("\n[1] federal 5-year funds floor (1693l-1(c)(2) / 1005.20(e)(2))");
{
  const p = "2025-12-25";
  const feA = fundsExpiry(p, "store", "OTHER", addYearsA);
  const feB = fundsExpiry(p, "store", "OTHER", addYearsB);
  check("store card floor = purchase + 5 yr (both routines)", feA.date === feB.date && feA.date === "2030-12-25", `= ${feA.date}`);
  check("floor years = 5", feA.years === 5);
  // a second purchase date
  const p2 = "2024-02-29", fe2 = fundsExpiry(p2, "store", "OTHER", addYearsA);
  check("leap-day purchase 2024-02-29 + 5 yr clamps to 2029-02-28", fe2.date === "2029-02-28", `= ${fe2.date}`);
}

// (2) 12-month fee window, and it precedes the 5-year floor
console.log("\n[2] 12-month fee window (1693l-1(b)(2) / 1005.20(d))");
{
  const p = "2025-12-25";
  const fwA = feeWindow(p, "store", addMonthsA), fwB = feeWindow(p, "store", addMonthsB);
  check("fee window = purchase + 12 mo (both routines)", fwA.date === fwB.date && fwA.date === "2026-12-25", `= ${fwA.date}`);
  const floor = fundsExpiry(p, "store", "OTHER", addYearsA).date;
  check("fee window (12 mo) is strictly before the funds floor (5 yr)", cmp(fwA.date, floor) < 0, `${fwA.date} < ${floor}`);
  check("one fee per calendar month cap is a constant, not a rate", FEE_WINDOW_MONTHS === 12);
}

// (3) California: covered funds never expire
console.log("\n[3] California: no expiration on gift certificates");
{
  const fe = fundsExpiry("2025-12-25", "store", "CA", addYearsA);
  check("CA covered store card: never expires", fe.covered === true && fe.never === true);
}

// (4) New York: 9-year minimum for purchases on/after 2022-12-10, else federal 5
console.log("\n[4] New York 9-year minimum (purchases on/after " + NY_CUTOFF + ")");
{
  const post = fundsExpiry("2023-01-01", "store", "NY", addYearsA);
  const postB = fundsExpiry("2023-01-01", "store", "NY", addYearsB);
  check("NY post-cutoff = +9 yr (both routines)", post.years === 9 && post.date === postB.date && post.date === "2032-01-01", `= ${post.date}`);
  const onCutoff = fundsExpiry(NY_CUTOFF, "store", "NY", addYearsA);
  check("NY exactly on cutoff 2022-12-10 = +9 yr", onCutoff.years === 9 && onCutoff.date === "2031-12-10", `= ${onCutoff.date}`);
  const pre = fundsExpiry("2020-01-01", "store", "NY", addYearsA);
  check("NY pre-cutoff falls back to federal +5 yr", pre.years === 5, `= ${pre.date}`);
  check("NY 9 yr > federal 5 yr (state can only add protection)", NY_MIN_YEARS > FED_FLOOR_YEARS);
}

// (5) promo/loyalty excluded: no federal floor, no fee cap
console.log("\n[5] loyalty/promotional exclusion (1005.20(b))");
{
  const fe = fundsExpiry("2025-12-25", "promo", "OTHER", addYearsA);
  const fw = feeWindow("2025-12-25", "promo", addMonthsA);
  check("promo card: funds floor NOT federally set", fe.covered === false);
  check("promo card: fee cap NOT federally set", fw.covered === false);
}

// (6) breakage vs escheat fork by state
console.log("\n[6] breakage vs escheat fork (state patchwork, dated)");
{
  const p = "2025-12-25";
  const de = moneyFork(p, "DE", addYearsA), deB = moneyFork(p, "DE", addYearsB);
  check("Delaware: escheats to state (reclaimable)", de.escheat === true);
  check("DE escheat date = purchase + dormancy (both routines)", de.date === deB.date && de.date === "2030-12-25", `= ${de.date} (~${de.dormancy}y)`);
  const dc = moneyFork(p, "DC", addYearsA);
  check("DC escheat date = purchase + 3 yr", dc.date === "2028-12-25", `= ${dc.date}`);
  for (const s of ["CA", "TX", "FL", "IL", "OH", "PA"]) {
    check(`${s}: kept by company (breakage, no escheat)`, moneyFork(p, s, addYearsA).escheat === false);
  }
}

// (7) plastic-vs-funds: network card funds floor equals store card floor
console.log("\n[7] bank-network card: money survives (funds floor unchanged)");
{
  const p = "2025-12-25";
  const net = fundsExpiry(p, "network", "OTHER", addYearsA);
  const store = fundsExpiry(p, "store", "OTHER", addYearsA);
  check("network funds floor = store funds floor (5 yr on the money, not the plastic)", net.date === store.date, `= ${net.date}`);
}

// (8) sanity on the fixed constants quoted on the page
console.log("\n[8] fixed statutory constants");
{
  check("effective date of the Fed final rule = 2010-08-22", EFFECTIVE_DATE === "2010-08-22");
  check("funds floor = 5 years", FED_FLOOR_YEARS === 5);
  check("fee window = 12 months", FEE_WINDOW_MONTHS === 12);
  check("NY minimum = 9 years", NY_MIN_YEARS === 9);
}

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