#!/usr/bin/env node
// Offline gate for /strata/does-coffee-dehydrate-you/.
// Recomputes every number shown on the page from first principles / the real
// digitized study data, and asserts the two load-bearing facts:
//   (1) Killer 2014's reported hydration markers are statistically identical
//       (coffee vs water), and the model reproduces that ~19 mL null gap;
//   (2) Zhang 2015's measured diuretic effect (+120 mL / +21% per ~300 mg at
//       rest, ES 0.54 -> 0.10 with exercise) is reproduced, and the resulting
//       fluid balance is net-positive across ALL realistic coffee inputs while
//       flipping net-negative only in the pill / no-fluid / non-habituated corner.
// Exits 0 on all-pass, non-zero otherwise. No network, no dependencies.

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

// ────────────────────────────────────────────────────────────────────────
// A. DIGITIZED PRIMARY DATA (Killer, Blannin & Jeukendrup, PLoS ONE 2014)
//    Reported means +/- SD, coffee arm vs water arm; not simulated.
// ────────────────────────────────────────────────────────────────────────
const KILLER = {
  totalBodyWater: { coffee: 51.5, water: 51.4, sdC: 1.4, sdW: 1.3, p: 0.90 }, // kg
  urine24h:       { coffee: 2409, water: 2428, sdC: 660, sdW: 669 },          // mL, NS
  bodyMassChange: { coffee: -0.39, water: -0.39 },                            // kg, identical
  n: 50
};

console.log('== A. Killer 2014 digitized markers (coffee vs water) ==');

// 1) Total body water difference is tiny and reported non-significant (p=0.90).
{
  const d = KILLER.totalBodyWater.coffee - KILLER.totalBodyWater.water;
  check('TBW difference is +0.1 kg (< 0.5% of ~51 kg), reported p=0.90 NS',
        approx(d, 0.1, 1e-9) && Math.abs(d) / KILLER.totalBodyWater.water < 0.005 && KILLER.totalBodyWater.p > 0.05,
        `d=${d.toFixed(2)} kg, p=${KILLER.totalBodyWater.p}`);
}

// 2) 24-h urine volume: the coffee-vs-water gap is ~19 mL, well inside 1 SD noise.
const urineGap = Math.abs(KILLER.urine24h.coffee - KILLER.urine24h.water); // 19 mL
{
  const pooledSD = Math.sqrt((KILLER.urine24h.sdC ** 2 + KILLER.urine24h.sdW ** 2) / 2);
  // Cohen's d for the paired-ish comparison as a plausibility bound: |d| must be trivially small.
  const cohend = urineGap / pooledSD;
  check('24-h urine gap = 19 mL, and effect size is trivially small (<0.05)',
        approx(urineGap, 19, 1e-9) && cohend < 0.05,
        `gap=${urineGap} mL, pooledSD=${pooledSD.toFixed(0)} mL, d=${cohend.toFixed(4)}`);
}

// 3) Body-mass change identical.
check('Body-mass change identical (-0.39 kg both arms)',
      approx(KILLER.bodyMassChange.coffee, -0.39, 1e-9) &&
      approx(KILLER.bodyMassChange.water, -0.39, 1e-9),
      `${KILLER.bodyMassChange.coffee} vs ${KILLER.bodyMassChange.water}`);

// ────────────────────────────────────────────────────────────────────────
// B. THE MODEL (identical constants to the page's inline script)
// ────────────────────────────────────────────────────────────────────────
const ZHANG_ML = 120;    // extra urine (mL) per reference dose, at rest, non-habituated
const ZHANG_DOSE = 300;  // reference dose (mg)
const ZHANG_PCT = 0.21;  // same effect as a relative +21%
const ES_REST = 0.54;    // Zhang resting effect size
const ES_EX = 0.10;      // Zhang exercise effect size (NS)
const HAB = 0.15;        // habituated residual multiplier (calibrated to Killer's ~19 mL null)
const EX_FACTOR = ES_EX / ES_REST;

function extraOut(dose, habituated, exercising) {
  let f = ZHANG_ML * (dose / ZHANG_DOSE);
  if (habituated) f *= HAB;
  if (exercising) f *= EX_FACTOR;
  return f;
}
function netHydration(servings, ml, mg, habituated, exercising) {
  return servings * ml - extraOut(servings * mg, habituated, exercising);
}

console.log('\n== B. Zhang 2015 diuretic term ==');

// 4) Reference: 300 mg, at rest, non-habituated -> +120 mL exactly.
check('extraOut(300 mg, rest, naive) = +120 mL (Zhang absolute effect)',
      approx(extraOut(300, false, false), 120, 1e-9),
      `${extraOut(300, false, false).toFixed(1)} mL`);

// 5) Independent cross-check: the +120 mL and +21% are two views of one effect.
//    120 mL == 21% of an implied ~571 mL baseline urine over the dosing window.
{
  const impliedBaseline = ZHANG_ML / ZHANG_PCT; // 571.4 mL
  check('+120 mL == +21% of ~571 mL baseline (two independent Zhang expressions agree)',
        approx(impliedBaseline, 571.4, 0.5) && approx(ZHANG_ML, ZHANG_PCT * impliedBaseline, 1e-9),
        `implied baseline = ${impliedBaseline.toFixed(1)} mL`);
}

// 6) Exercise negation: resting diuresis strictly larger than exercising.
check('exercise attenuates diuresis (rest > exercise for same dose)',
      extraOut(300, false, false) > extraOut(300, false, true),
      `rest=${extraOut(300, false, false).toFixed(0)} mL, exercise=${extraOut(300, false, true).toFixed(1)} mL`);

// 7) The exercise factor equals Zhang's own effect-size ratio.
check('exercise factor = ES_ex / ES_rest = 0.10/0.54',
      approx(EX_FACTOR, 0.10 / 0.54, 1e-12),
      `factor=${EX_FACTOR.toFixed(4)}`);

console.log('\n== C. The page reproduces Killer\'s null ==');

// 8) Model on Killer's protocol: 4x200 mL, 300 mg (4 mg/kg @75 kg), habituated, rest.
//    The coffee-vs-water gap the model predicts must sit inside the paper's ~19 mL NS band.
{
  const modelGap = extraOut(300, true, false); // = pure-water line minus coffee net
  check('model gap for Killer protocol is > 0 but <= 19 mL (matches the NS null)',
        modelGap > 0 && modelGap <= urineGap + 1e-9,
        `model=${modelGap.toFixed(1)} mL, paper gap=${urineGap} mL`);
  // and the coffee net stays essentially at the water line
  const inK = 4 * 200, coffeeNet = netHydration(4, 200, 75, true, false);
  check('Killer coffee net sits at the pure-water line (within 19 mL)',
        approx(coffeeNet, inK, urineGap + 1e-9),
        `coffee net=${coffeeNet.toFixed(0)} mL vs water line=${inK} mL`);
}

console.log('\n== D. Volume dominance + net-positive across all realistic coffee ==');

// 9) Volume dominance arithmetic: ~800 mL in vs ~120 mL extra out (naive, rest).
{
  const fluidIn = 4 * 200, out = extraOut(300, false, false);
  check('volume dominance: 800 mL in dwarfs ~120 mL extra out (in > 5x out)',
        approx(fluidIn, 800, 1e-9) && approx(out, 120, 1e-9) && fluidIn > 5 * out,
        `in=${fluidIn} mL, out=${out} mL, ratio=${(fluidIn / out).toFixed(1)}x`);
}

// 10) Net-positive across the ENTIRE realistic-coffee grid (>= 150 mL/serving),
//     every servings count, every habituation and rest/exercise combination.
{
  let worst = Infinity, worstCase = '';
  for (let n = 1; n <= 8; n++)
    for (let ml = 150; ml <= 250; ml += 10)
      for (let mg = 40; mg <= 120; mg += 5)
        for (const h of [false, true])
          for (const e of [false, true]) {
            const net = netHydration(n, ml, mg, h, e);
            if (net < worst) { worst = net; worstCase = `${n}x${ml}mL@${mg}mg h=${h} e=${e}`; }
          }
  check('net > 0 for EVERY realistic coffee input (fluid >= 150 mL/serving)',
        worst > 0,
        `worst net = ${worst.toFixed(0)} mL at ${worstCase}`);
}

// 11) Even espresso (little fluid) still nets positive at a full day's servings.
check('espresso (4x30 mL, 63 mg, naive, rest) still nets positive',
      netHydration(4, 30, 63, false, false) > 0,
      `${netHydration(4, 30, 63, false, false).toFixed(0)} mL`);

console.log('\n== E. The boundary flip (isolating exactly when the myth is right) ==');

// 12) Two caffeine pills (0 mL fluid, 200 mg each), non-habituated, at rest -> net negative.
{
  const pillNet = netHydration(2, 0, 200, false, false);
  check('caffeine pills (2 x 200 mg, 0 mL, naive, rest) net-negative',
        pillNet < 0,
        `net = ${pillNet.toFixed(0)} mL`);
}

// 13) The flip requires ALL THREE conditions. Coffee-with-fluid never flips;
//     habituation alone rescues it; and the same dose delivered WITH a cup of
//     water is positive. This proves the myth's corner is narrow.
{
  const nakedDose = netHydration(1, 0, 300, false, false);          // pills, naive, rest -> negative
  const withWater = netHydration(1, 250, 300, false, false);        // same dose + a cup -> positive
  const habituatedNaked = netHydration(1, 0, 300, true, false);     // pills but habituated -> ~ -18, still tiny
  check('same 300 mg flips sign purely on whether fluid rides along (naked<0, with-water>0)',
        nakedDose < 0 && withWater > 0,
        `naked=${nakedDose.toFixed(0)} mL, with 250 mL water=${withWater.toFixed(0)} mL`);
  check('habituation shrinks even the naked-dose deficit ~6x (tolerance defuses it)',
        Math.abs(habituatedNaked) < Math.abs(nakedDose) / 5,
        `naive=${nakedDose.toFixed(0)} mL vs habituated=${habituatedNaked.toFixed(0)} mL`);
}

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