#!/usr/bin/env node
// Offline gate for /strata/does-swallowed-gum-stay-in-your-stomach/
//
// Recomputes EVERY number shown on the page from first principles, two independent
// ways where possible. Exits 0 iff all checks pass, non-zero otherwise.
//
// The page's two instruments:
//   (1) gut-transit timer: myth ratio = 61,320 h / (whole-gut transit)
//   (2) bezoar regime (Little's law): resident base = pieces/day * base/piece * residence
//
// Sources (see README.md):
//   Milov et al., Pediatrics 1998;102(2):e22 (n=3 pediatric gum bezoars, up to 7 pcs/day).
//   Scientific American 2007 (Milov: "usually it's not something that's any more than a week old").
//   Mayo Clinic / Duke Health FAQs (7-year claim is folklore; passes in stool).
//   Whole-gut transit ~24-72 h (median ~30-40 h), wireless-motility-capsule literature.

let pass = 0, fail = 0;
const EPS = 1e-9;
function check(name, got, want, tol = 0) {
  const ok = (typeof want === 'boolean')
    ? got === want
    : Math.abs(got - want) <= (tol || EPS);
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}` +
    (typeof want === 'boolean' ? `  (got ${got})` : `  (got ${round(got)}, want ${round(want)})`));
  ok ? pass++ : fail++;
  return ok;
}
function round(x){ return typeof x === 'number' ? Math.round(x * 1000) / 1000 : x; }

// ── (0) the fixed arithmetic: 7 yr = 2,555 d = 61,320 h ──────────────────
const MYTH_DAYS  = 7 * 365;         // 2,555
const MYTH_HOURS = MYTH_DAYS * 24;  // 61,320
check('7 yr = 2,555 days', MYTH_DAYS, 2555);
check('2,555 days = 61,320 hours', MYTH_HOURS, 61320);
check('7 yr = 61,320 h (direct, 7*365*24)', 7 * 365 * 24, 61320); // independent decomposition

// ── (1) myth overstatement ratio = 61,320 h / transit, computed two ways ─
// ratioA uses hours; ratioB uses days (myth_days / transit_days) -> must agree.
function ratioHours(transitH){ return MYTH_HOURS / transitH; }
function ratioDays(transitH){ return MYTH_DAYS / (transitH / 24); }

const cases = [
  { h: 18,  want: 3407, label: 'fast (18 h)' },
  { h: 30,  want: 2044, label: 'median (30 h)' },
  { h: 36,  want: 1703, label: '1.5 days (36 h)' },
  { h: 48,  want: 1278, label: '2 days (48 h)' },
  { h: 72,  want: 852,  label: '3 days (72 h)' },
  { h: 168, want: 365,  label: '1 week ceiling (168 h)' },
];
for (const c of cases) {
  check(`ratio @${c.h}h (hours form) = ${c.want}x`, Math.round(ratioHours(c.h)), c.want);
  check(`ratio @${c.h}h (days form)  = ${c.want}x`, Math.round(ratioDays(c.h)),  c.want);
  check(`ratio @${c.h}h: two forms agree exactly`, Math.abs(ratioHours(c.h) - ratioDays(c.h)) < 1e-9, true);
}

// key numbers quoted in the prose / keyNumber field
check('median overstatement ~2,044x (keyNumber ~2,000x)', Math.round(ratioHours(30)), 2044);
check('outer-ceiling overstatement ~365x (still off vs 1 week)', Math.round(ratioHours(168)), 365);

// every transit in the honest window overstates by >100x (never anywhere near 7 years)
let allBig = true;
for (let t = 18; t <= 72; t++) if (ratioHours(t) < 100) allBig = false;
check('every transit 18..72 h overstates by >100x', allBig, true);

// "a day or two" sanity: median transit is ~1.25 days, far below even 1 week
check('median transit 30 h = 1.25 days', 30 / 24, 1.25);
check('median transit well under the 1-week ceiling', (30 / 24) < 7, true);

// ── (2) Instrument 2: Little's law bezoar model ──────────────────────────
// resident base [mL] = pieces/day * base_per_piece[mL] * residence[days]
// residence[days] = base_residence(1.25) * constipation_multiplier * body_slowdown
const BASE_ML = 0.8;
const RESID_DAYS = 1.25;
const THRESH = { adult: 150, toddler: 20 };
const BODY_SLOW = { adult: 1.0, toddler: 1.4 };
function resident(pieces, constip, body) {
  return pieces * BASE_ML * (RESID_DAYS * constip * BODY_SLOW[body]);
}
// independent re-derivation via Little's law stated as throughput * residence:
function residentLittle(pieces, constip, body) {
  const ratePerDay = pieces * BASE_ML;                       // mL/day entering
  const residenceDays = RESID_DAYS * constip * BODY_SLOW[body];
  return ratePerDay * residenceDays;                          // L = rate * time
}
check('two Little forms agree (toddler,7,4x)',
  Math.abs(resident(7,4,'toddler') - residentLittle(7,4,'toddler')) < 1e-12, true);

// The model must reproduce the ONE real fact: only the small-child + many-pieces +
// slow-gut corner forms a mass. Check the corners.

// a) single accidental piece in an adult, even worst constipation -> harmless
const singleAdult = resident(1, 5, 'adult');
check('adult, 1 piece, worst constipation -> no mass', singleAdult < THRESH.adult, true);

// b) heavy adult habit, even 10/day + max constipation -> still under threshold
const heavyAdult = resident(10, 5, 'adult');
check('adult, 10/day, max constipation -> still no mass', heavyAdult < THRESH.adult, true);

// c) the Milov corner: toddler, 7 pieces/day, slow gut (>=2.5x) -> mass forms
const milov = resident(7, 4, 'toddler');
check('toddler, 7/day, 4x slowdown -> MASS forms', milov > THRESH.toddler, true);

// d) same toddler habit WITHOUT constipation -> no mass (constipation is the co-factor)
const toddlerNormal = resident(7, 1, 'toddler');
check('toddler, 7/day, NO slowdown -> no mass', toddlerNormal < THRESH.toddler, true);

// e) toddler, few pieces, slow gut -> no mass (piece count is the other co-factor)
const toddlerFew = resident(1, 4, 'toddler');
check('toddler, 1 piece, 4x slowdown -> no mass', toddlerFew < THRESH.toddler, true);

// f) monotonicity: resident base rises with pieces, constipation, and (toddler) size
check('resident base monotone in pieces', resident(8,2,'toddler') > resident(4,2,'toddler'), true);
check('resident base monotone in constipation', resident(6,4,'toddler') > resident(6,2,'toddler'), true);

// ── summary ──────────────────────────────────────────────────────────────
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
