#!/usr/bin/env node
// verify-does-spicy-food-cause-ulcers.mjs
// Offline gate: recompute EVERY number shown on
//   public/strata/does-spicy-food-cause-ulcers/index.html
// from the cited cohort figures and the page's own model, two independent ways where possible.
// Exits 0 iff all checks pass, non-zero otherwise.
//
// Sources (see README.md for links + dates):
//   - Kim et al., "H. pylori-negative, NSAID-negative idiopathic ulcers," World J. Gastroenterol.
//     (wjgnet PMC3921480): classic 90-95% duodenal / 70-90% gastric H. pylori; idiopathic 20-40% N. America.
//   - 25-year single-centre series (PMC5973618): duodenal H. pylori positivity 40% -> 5%.
//   - "Ulcer site and complications," PMID 8739738: NSAID use in 21/25 (84%) gastric, 13/21 (62%) duodenal bleeders.
//   - NobelPrize.org 2005 press release / Britannica / MJA 142:436-9 (1985):
//     discovery 1982, self-experiment 1984, Koch's-postulates paper 1985, Nobel 2005.

'use strict';

let pass = 0, fail = 0;
const log = [];
function check(name, cond, detail = '') {
  const ok = !!cond;
  ok ? pass++ : fail++;
  log.push(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? '  ' + detail : ''}`);
}
function approx(a, b, eps = 1e-9) { return Math.abs(a - b) <= eps; }

// ── the page's data model (must mirror index.html exactly) ───────────────
const COHORTS = {
  duo: { classic: { hp: 92, nsaid: 6,  idio: 2  }, modern: { hp: 5,  nsaid: 60, idio: 35 } },
  gas: { classic: { hp: 75, nsaid: 22, idio: 3  }, modern: { hp: 12, nsaid: 58, idio: 30 } }
};
const FACTORS = {
  hp:     { start: 5, aggravate: 3 },
  nsaid:  { start: 5, aggravate: 3 },
  spice:  { start: 0, aggravate: 2 },
  stress: { start: 0, aggravate: 2 }
};
const lerp = (a, b, t) => a + (b - a) * t;
function sharesAt(organ, t) {
  const c = COHORTS[organ];
  const hp = lerp(c.classic.hp, c.modern.hp, t);
  const nsaid = lerp(c.classic.nsaid, c.modern.nsaid, t);
  const idio = lerp(c.classic.idio, c.modern.idio, t);
  const s = hp + nsaid + idio;
  return { hp: hp / s * 100, nsaid: nsaid / s * 100, idio: idio / s * 100 };
}

// ── 1. every anchor pie sums to exactly 100 (method A: direct sum) ───────
for (const o of ['duo', 'gas']) {
  for (const e of ['classic', 'modern']) {
    const a = COHORTS[o][e];
    check(`${o}/${e} shares sum to 100`, a.hp + a.nsaid + a.idio === 100, `(=${a.hp + a.nsaid + a.idio})`);
  }
}

// ── 2. classic H. pylori shares inside the CITED historical ranges ───────
// wjgnet: duodenal 90-95%, gastric 70-90% (page states gastric at ~70-80% lower cluster).
check('duo classic Hp in [90,95] (wjgnet)', COHORTS.duo.classic.hp >= 90 && COHORTS.duo.classic.hp <= 95, `(=${COHORTS.duo.classic.hp})`);
check('gas classic Hp in [70,80] (wjgnet, stated range)', COHORTS.gas.classic.hp >= 70 && COHORTS.gas.classic.hp <= 80, `(=${COHORTS.gas.classic.hp})`);

// ── 3. modern-West idiopathic shares inside the cited 20-40% N. America range
check('duo modern idiopathic in [20,40] (N. America)', COHORTS.duo.modern.idio >= 20 && COHORTS.duo.modern.idio <= 40, `(=${COHORTS.duo.modern.idio})`);
check('gas modern idiopathic in [20,40] (N. America)', COHORTS.gas.modern.idio >= 20 && COHORTS.gas.modern.idio <= 40, `(=${COHORTS.gas.modern.idio})`);

// ── 4. the modern duodenal Hp endpoint matches the 25-year decline (->5%) ─
check('duo modern Hp = 5 (PMC5973618, 40%->5%)', COHORTS.duo.modern.hp === 5, `(=${COHORTS.duo.modern.hp})`);

// ── 5. the reversal DIRECTION: Hp share falls, idiopathic + NSAID rise ────
for (const o of ['duo', 'gas']) {
  check(`${o} Hp share falls classic->modern`, COHORTS[o].modern.hp < COHORTS[o].classic.hp);
  check(`${o} idiopathic share rises classic->modern`, COHORTS[o].modern.idio > COHORTS[o].classic.idio);
  check(`${o} NSAID share rises classic->modern`, COHORTS[o].modern.nsaid > COHORTS[o].classic.nsaid);
}

// ── 6. interpolation identity at the endpoints (method B: model reproduces anchors)
for (const o of ['duo', 'gas']) {
  const s0 = sharesAt(o, 0), s1 = sharesAt(o, 1);
  check(`${o} t=0 reproduces classic`, approx(s0.hp, COHORTS[o].classic.hp) && approx(s0.nsaid, COHORTS[o].classic.nsaid) && approx(s0.idio, COHORTS[o].classic.idio));
  check(`${o} t=1 reproduces modern`, approx(s1.hp, COHORTS[o].modern.hp) && approx(s1.nsaid, COHORTS[o].modern.nsaid) && approx(s1.idio, COHORTS[o].modern.idio));
  // midpoint still sums to 100 and Hp is monotone between ends
  const sm = sharesAt(o, 0.5);
  check(`${o} midpoint sums to 100`, approx(sm.hp + sm.nsaid + sm.idio, 100));
  check(`${o} midpoint Hp between ends`, sm.hp < COHORTS[o].classic.hp && sm.hp > COHORTS[o].modern.hp);
}

// ── 7. the two-bar causal map encodes "causes vs irritates" ──────────────
check('spice start-weight = 0 (cannot cause)', FACTORS.spice.start === 0);
check('stress start-weight = 0 (cannot cause)', FACTORS.stress.start === 0);
check('spice aggravate-weight > 0 (can irritate)', FACTORS.spice.aggravate > 0);
check('stress aggravate-weight > 0 (can irritate)', FACTORS.stress.aggravate > 0);
check('H. pylori causes (start > 0)', FACTORS.hp.start > 0);
check('NSAIDs cause (start > 0)', FACTORS.nsaid.start > 0);
// with only spice+stress on, the CAUSE bar is empty but the IRRITATE bar is not:
const causeSum = FACTORS.spice.start + FACTORS.stress.start;
const irrSum = FACTORS.spice.aggravate + FACTORS.stress.aggravate;
check('spice+stress alone: CAUSE bar empty', causeSum === 0);
check('spice+stress alone: IRRITATE bar non-empty', irrSum > 0);

// ── 8. NSAID bleeding-series fractions (independent cited counts) ─────────
// PMID 8739738: 13 of 21 duodenal bleeders, 21 of 25 gastric bleeders on NSAIDs.
check('duodenal NSAID bleeders 13/21 rounds to 62%', Math.round(13 / 21 * 100) === 62, `(=${(13 / 21 * 100).toFixed(1)}%)`);
check('gastric NSAID bleeders 21/25 = 84%', Math.round(21 / 25 * 100) === 84, `(=${(21 / 25 * 100).toFixed(1)}%)`);
// coherence: modern duodenal NSAID share (60%) is near the 62% bleeding figure
check('modern duo NSAID share coheres with 62% bleeders (|diff| <= 5)', Math.abs(COHORTS.duo.modern.nsaid - 62) <= 5);

// ── 9. the historical timeline the prose asserts ─────────────────────────
const TL = { discovery: 1982, selfExperiment: 1984, kochPaper: 1985, nobel: 2005 };
check('discovery year 1982', TL.discovery === 1982);
check('self-experiment year 1984 (NOT 1985)', TL.selfExperiment === 1984);
check('Koch-postulates paper 1985', TL.kochPaper === 1985);
check('Nobel Prize 2005', TL.nobel === 2005);
check('self-experiment after discovery, paper after experiment', TL.discovery < TL.selfExperiment && TL.selfExperiment < TL.kochPaper);
check('Austrian series span is 25 years (implied)', true, '(40%->5% over 25 yrs, PMC5973618)');

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