// verify.mjs — the check behind "Still Awake".
//   node research/still-awake/verify.mjs
//
// Two jobs:
//  (1) reproduce the exponential-decay model the page uses and assert its
//      mathematical properties (half-life halving, superposition, band ordering,
//      crossing-time monotonicity);
//  (2) assert the page's cited CONSTANTS (half-life bands + drink mg) match the
//      sourced literature in the footer — so the numbers can never silently drift
//      away from their citations.
//
// Sources for the constants (also linked on the page):
//   NIH/NCBI NBK223808 (Pharmacology of Caffeine) — mean ~5 h, range 1.5–9.5 h,
//     OC "can double", smoking ~50% shorter.
//   StatPearls NBK519490 — smoker half-life reduced up to ~50%; pregnancy 3rd
//     trimester up to ~15 h.
//   FDA "Spilling the Beans" + Mayo Clinic — drink caffeine content.
//   Drake et al. 2013 (PMC3805807) — no safe sleep floor; 400 mg disrupts 6 h out.

import { readFileSync } from 'fs';

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => { console.log((cond ? '  ok   ' : '  FAIL ') + name + (extra ? '  ' + extra : '')); cond ? pass++ : fail++; };
const near = (a, b, tol) => Math.abs(a - b) <= tol;

/* ── the model (mirrors the page) ───────────────────────────────────────── */
// caffeine still present at absolute time t (minutes), for half-life T (hours)
function residualAt(drinks, tMin, T) {
  let s = 0;
  for (const d of drinks) { if (tMin < d.t) continue; s += d.mg * Math.pow(0.5, (tMin - d.t) / 60 / T); }
  return s;
}
function crossing(drinks, level, T, tStart, tEnd) {
  if (residualAt(drinks, tStart, T) <= level) return tStart;
  for (let t = tStart; t <= tEnd; t += 1) if (residualAt(drinks, t, T) <= level) return t;
  return null;
}

/* ── (1) model properties ───────────────────────────────────────────────── */
console.log('[model]');
{
  const one = [{ mg: 100, t: 0 }];
  ok('after exactly one half-life, 100 mg → 50 mg', near(residualAt(one, 5 * 60, 5), 50, 1e-9), residualAt(one, 300, 5).toFixed(6));
  ok('after two half-lives → 25 mg', near(residualAt(one, 10 * 60, 5), 25, 1e-9));
  ok('at t=0 the full dose is present', near(residualAt(one, 0, 5), 100, 1e-9));
  ok('before the drink, nothing is present', residualAt([{ mg: 100, t: 120 }], 0, 5) === 0);

  // superposition: two 100 mg drinks an hour apart at t=60min after the second,
  // vs summing each independently
  const two = [{ mg: 100, t: 0 }, { mg: 100, t: 60 }];
  const manual = 100 * Math.pow(0.5, (120) / 60 / 5) + 100 * Math.pow(0.5, (60) / 60 / 5);
  ok('superposition = sum of independent decays', near(residualAt(two, 120, 5), manual, 1e-9));

  // band ordering: a SHORTER half-life clears FASTER, so later on it must be LOWER
  const tLate = 8 * 60;
  ok('shorter half-life ⇒ lower residual later (band orders correctly)',
     residualAt(one, tLate, 3) < residualAt(one, tLate, 7),
     residualAt(one, tLate, 3).toFixed(1) + ' < ' + residualAt(one, tLate, 7).toFixed(1));

  // crossing monotonicity: fast edge crosses a level no later than the slow edge
  const cf = crossing(one, 25, 3, 0, 48 * 60), cs = crossing(one, 25, 7, 0, 48 * 60);
  ok('fast edge crosses reference no later than slow edge', cf !== null && cs !== null && cf <= cs, cf + ' ≤ ' + cs);

  // a known crossing: 100 mg, T=5h, level 25 mg → exactly 2 half-lives = 600 min
  ok('crossing 100→25 mg at T=5h lands at 2 half-lives (600 min)', near(crossing(one, 25, 5, 0, 48 * 60), 600, 1), crossing(one, 25, 5, 0, 48 * 60));

  // the fixed bug: crossing must be measured AFTER the last drink — a later,
  // bigger coffee must not be "cleared" by an earlier dip below the level.
  const late = [{ mg: 110, t: 0 }, { mg: 150, t: 90 }];
  const naive = crossing(late, 100, 5, 0, 48 * 60);          // from first drink — an early dip
  const lastT = Math.max(...late.map(d => d.t));
  const correct = crossing(late, 100, 5, lastT, 48 * 60);    // from last drink — the real answer
  ok('crossing after the last drink is later than a naive first-dip crossing', correct > naive, naive + ' → ' + correct);
  ok('after the last drink the residual is still above the reference (dip was spurious)', residualAt(late, lastT, 5) > 100);
}

/* ── (2) the page's constants match the cited literature ────────────────── */
console.log('\n[page constants vs citations]');
const html = readFileSync(new URL('../../public/tools/still-awake/index.html', import.meta.url).pathname, 'utf8');

function grabBand(key) {
  const re = new RegExp(key + ":\\s*\\{[^}]*band:\\s*\\[\\s*([\\d.]+)\\s*,\\s*([\\d.]+)\\s*\\]");
  const m = html.match(re); return m ? [parseFloat(m[1]), parseFloat(m[2])] : null;
}
function grabDrink(key) {
  const re = new RegExp("key:'" + key + "'[^}]*mg:\\s*(\\d+)");
  const m = html.match(re); return m ? parseInt(m[1], 10) : null;
}

const bands = { typical: [4, 6], smoker: [2.5, 4], contra: [7, 11], pregnant3: [10, 15] };
for (const [k, want] of Object.entries(bands)) {
  const got = grabBand(k);
  ok('half-life band ' + k + ' = ' + want.join('–') + ' h', got && got[0] === want[0] && got[1] === want[1], got ? got.join('–') : 'not found');
}
// cross-check the bands against the source relationships
ok('typical band sits inside the population range 1.5–9.5 h', bands.typical[0] >= 1.5 && bands.typical[1] <= 9.5);
ok('smoker band is shorter than typical (CYP1A2 induction)', bands.smoker[1] <= bands.typical[0] + 0.001);
ok('contraception band is ~1.5–2× typical', near(bands.contra[0] / bands.typical[0], 1.75, 0.5) && bands.contra[1] > bands.typical[1]);
ok('pregnancy 3rd-tri upper edge ≈ up to ~15 h (StatPearls)', bands.pregnant3[1] === 15);

const drinks = { coffee: 95, espresso: 63, blacktea: 47, greentea: 28, cola: 35, energy: 80 };
for (const [k, want] of Object.entries(drinks)) {
  ok('drink mg ' + k + ' = ' + want + ' mg (FDA/Mayo)', grabDrink(k) === want, String(grabDrink(k)));
}

/* ── (3) the honesty guardrails are present in the page copy ─────────────── */
console.log('\n[honesty guardrails present]');
ok('states "not medical advice"', /not medical advice/i.test(html));
ok('names CYP1A2 genotype as unknowable', /CYP1A2/.test(html));
ok('says there is no proven safe sleep threshold', /no proven .*(safe|threshold)/i.test(html));
ok('cites Drake 2013 for the 6-hour finding', /Drake/i.test(html) && /6\s*h/i.test(html));
ok('flags absorption as an instantaneous simplification', /instantaneous/i.test(html));
ok('links the primary sources (NIH bookshelf)', /NBK223808/.test(html) && /NBK519490/.test(html));

console.log('\n' + (fail === 0 ? pass + ' passes / 0 failures — ALL CHECKS PASS' : pass + ' passes / ' + fail + ' FAILURES'));
process.exit(fail === 0 ? 0 : 1);
