#!/usr/bin/env node
// verify-what-happens-if-you-dont-sleep.mjs
// Offline gate for public/strata/what-happens-if-you-dont-sleep/index.html.
//
// It reproduces EVERY number shown on the page from the digitized study data and
// from first principles, prints one line per check, and exits 0 only if all pass.
// Where possible it verifies a claim TWO independent ways.
//
// The moat: the flagship "6h/night x14d ~= one sleepless night, 4h/night x14d ~= two
// sleepless nights" equivalence is DIGITIZED from Van Dongen 2003, Sleep 26(2):117,
// Figure 1A (PVT lapses) and read off against the total-sleep-deprivation arm of the
// SAME figure. It is never a hardcoded round constant: the code stores the transcribed
// (day, lapses) series and DISCOVERS which sleepless-night level each dose reaches.
// It is then cross-checked, independently, against the paper's own excess-wakefulness
// model (daily excess above the fitted 15.84 h/day threshold), which predicts the same
// 2:1 dose ratio without touching the figure read-offs.
//
//   node research/what-happens-if-you-dont-sleep/verify-what-happens-if-you-dont-sleep.mjs

let PASS = 0, FAIL = 0;
function ok(name, cond, detail) {
  const mark = cond ? "PASS" : "FAIL";
  if (cond) PASS++; else FAIL++;
  console.log(`  [${mark}] ${name}${detail ? "  ->  " + detail : ""}`);
  return cond;
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }
const f = (x, d = 1) => Number(x).toFixed(d);

// ─────────────────────────────────────────────────────────────────────────────
// DIGITIZED DATA: hand-read from Van Dongen HPA, Maislin G, Mullington JM, Dinges DF,
// "The Cumulative Cost of Additional Wakefulness," Sleep 2003;26(2):117-126.
//   PVT.*  : psychomotor-vigilance lapses per test bout, chronic restriction, days 1..14  (Fig 1A)
//   TSD    : the 0h (total-sleep-deprivation) arm, nights 0..3 (night 0 = baseline)        (Fig 1A)
//   SSS6   : Stanford Sleepiness Scale (1..7) for the everyday 6h case, days 1..14         (Fig 1B)
// Read to chart resolution (~+-1 lapse, ~+-0.3 scale point). These MUST match the arrays
// embedded in the page's inline <script>.
// ─────────────────────────────────────────────────────────────────────────────
const PVT = {
  h8: [2.3, 2.4, 2.5, 2.5, 2.6, 2.7, 2.7, 2.8, 2.9, 2.9, 3.0, 3.1, 3.2, 3.3],
  h6: [3.0, 3.5, 4.0, 4.5, 5.1, 5.6, 6.1, 6.6, 7.1, 7.6, 8.2, 8.7, 9.2, 9.7],
  h4: [3.5, 4.4, 5.3, 6.2, 7.1, 7.9, 8.8, 9.7, 10.6, 11.5, 12.4, 13.3, 14.2, 15.1],
};
const TSD = { night: [0, 1, 2, 3], lapses: [2.5, 10.1, 14.6, 19.0] };
const SSS6 = [2.6, 2.9, 3.1, 3.3, 3.4, 3.4, 3.5, 3.5, 3.6, 3.6, 3.6, 3.7, 3.7, 3.7];
const SSS_2NIGHT = 5.6; // approx SSS level at 2 nights TSD (Fig 1B): 6h never reaches it
const TOL = 2.0;        // reading resolution: two lapse levels "match" if within this

const day14 = 13; // index of day 14

// the paper's fitted excess-wakefulness parameters (verbatim reported values)
const THRESH = 15.84;                 // fitted critical wake period, h/day (+- 0.73 s.e.)
const THRESH_SE = 0.73;
const SLEEP_NEED = 24 - THRESH;       // = 8.16 h/day to break even
const dailyExcess = (tib) => Math.max(0, (24 - tib) - THRESH); // sleep obtained ~= time in bed

// Dawson & Reid 1997, Nature 388:235: BAC-equivalent, reaction-time tasks only.
// TWO published points only (17h -> 0.05%, 24h -> 0.10%). 22h is NOT an anchor:
// it is the straight-line interpolation between them (~0.086%), never a published value.
const BAC_ANCHORS = [[17, 0.05], [24, 0.10]];
const BAC_RATE_FULL = 0.004; // %/h averaged over 10-26h (paper headline)
function bacEquiv(h) {
  const a = BAC_ANCHORS;
  if (h <= a[0][0]) {
    const s0 = (a[1][1] - a[0][1]) / (a[1][0] - a[0][0]);
    return Math.max(0, a[0][1] + (h - a[0][0]) * s0);
  }
  for (let i = 0; i < a.length - 1; i++) {
    if (h <= a[i + 1][0]) {
      const s = (a[i + 1][1] - a[i][1]) / (a[i + 1][0] - a[i][0]);
      return a[i][1] + (h - a[i][0]) * s;
    }
  }
  const n = a.length - 1, sl = (a[n][1] - a[n - 1][1]) / (a[n][0] - a[n - 1][0]);
  return a[n][1] + (h - a[n][0]) * sl;
}

// find the nearest sleepless-night level (1..3) to a given lapse count
function nearestNight(lapses) {
  let best = -1, bd = Infinity;
  for (let i = 1; i < TSD.night.length; i++) {
    const d = Math.abs(TSD.lapses[i] - lapses);
    if (d < bd) { bd = d; best = TSD.night[i]; }
  }
  return { night: best, diff: bd };
}
// simple least-squares slope of y over x (integer days)
function slope(y) {
  const n = y.length; let sx = 0, sy = 0, sxx = 0, sxy = 0;
  for (let i = 0; i < n; i++) { const x = i + 1; sx += x; sy += y[i]; sxx += x * x; sxy += x * y[i]; }
  return (n * sxy - sx * sy) / (n * sxx - sx * sx);
}

console.log("\n=== PANEL 1 & 2: THE AWARENESS GAP + DOSE-RESPONSE (digitized, Van Dongen 2003 Fig 1A/1B) ===");

// METHOD A: the equivalence discovered from the digitized figure read-offs
const n6 = nearestNight(PVT.h6[day14]);
const n4 = nearestNight(PVT.h4[day14]);
ok("6h/night day-14 PVT lapses match ONE sleepless night",
   n6.night === 1 && n6.diff < TOL,
   `6h=${f(PVT.h6[day14])} vs 1-night=${f(TSD.lapses[1])}, |diff|=${f(n6.diff)} < ${TOL}`);
ok("4h/night day-14 PVT lapses match TWO sleepless nights",
   n4.night === 2 && n4.diff < TOL,
   `4h=${f(PVT.h4[day14])} vs 2-nights=${f(TSD.lapses[2])}, |diff|=${f(n4.diff)} < ${TOL}`);
ok("the 6h~1-night and 4h~2-nights readings are kept DISTINCT (never collapsed)",
   n6.night !== n4.night, `6h->${n6.night} night, 4h->${n4.night} nights`);
ok("6h day-14 is NOT within tolerance of the 2-night level (distinctness is real)",
   Math.abs(PVT.h6[day14] - TSD.lapses[2]) > TOL,
   `|6h - 2night| = ${f(Math.abs(PVT.h6[day14] - TSD.lapses[2]))} > ${TOL}`);
ok("4h day-14 is NOT within tolerance of the 1-night level (distinctness is real)",
   Math.abs(PVT.h4[day14] - TSD.lapses[1]) > TOL,
   `|4h - 1night| = ${f(Math.abs(PVT.h4[day14] - TSD.lapses[1]))} > ${TOL}`);
ok("8h/night stays within a baseline band across 14 days (protective)",
   PVT.h8[day14] < TSD.lapses[0] + 2,
   `8h day-14 = ${f(PVT.h8[day14])} < baseline ${f(TSD.lapses[0])} + 2`);
ok("PVT lapses climb monotonically for 6h and 4h",
   PVT.h6.every((v, i) => i === 0 || v >= PVT.h6[i - 1]) &&
   PVT.h4.every((v, i) => i === 0 || v >= PVT.h4[i - 1]), "non-decreasing series");
ok("objective climb is near-linear (4h slope R about 2x the 6h slope)",
   approx(slope(PVT.h4) / slope(PVT.h6), 2, 0.35),
   `slope4=${f(slope(PVT.h4), 2)}/day, slope6=${f(slope(PVT.h6), 2)}/day, ratio=${f(slope(PVT.h4) / slope(PVT.h6), 2)}`);

// the awareness gap itself: subjective flattens while objective climbs
ok("subjective sleepiness PLATEAUS (6h SSS gain over days 7->14 < 0.5 pt)",
   (SSS6[day14] - SSS6[6]) < 0.5, `SSS: d7=${f(SSS6[6])} -> d14=${f(SSS6[day14])}`);
ok("felt sleepiness never reaches the 2-night level (the warning stays low)",
   SSS6[day14] < SSS_2NIGHT, `6h SSS d14 = ${f(SSS6[day14])} < 2-night ~${f(SSS_2NIGHT)}`);
const objMult = PVT.h6[day14] / PVT.h6[0];
const subjMult = (SSS6[day14] - 1) / (SSS6[0] - 1);
ok("the gap opens: objective multiplier >> subjective multiplier",
   objMult > subjMult + 1, `objective x${f(objMult)} vs subjective x${f(subjMult)} (day1->day14)`);

console.log("\n=== INDEPENDENT CROSS-CHECK: the paper's excess-wakefulness model (Fig 4B) ===");
// METHOD B: same 2:1 ordering derived from the fitted 15.84 h/day threshold, no figure used
const e4 = dailyExcess(4), e6 = dailyExcess(6), e8 = dailyExcess(8);
ok("threshold internal math reproduces both reported values: 15.84 + 8.16 = 24.00",
   approx(THRESH + SLEEP_NEED, 24, 1e-9),
   `critical wake ${f(THRESH, 2)}h + sleep need ${f(SLEEP_NEED, 2)}h = ${f(THRESH + SLEEP_NEED, 2)}h`);
ok("fitted threshold is 15.84 +- 0.73 h/day (subject-specific, not universal)",
   THRESH === 15.84 && THRESH_SE === 0.73, `${THRESH} +- ${THRESH_SE} h`);
ok("4h dose accrues excess wakefulness at ~2x the 6h rate (predicts 2 vs 1 nights)",
   approx(e4 / e6, 2, 0.15),
   `daily excess 4h=${f(e4, 2)}h, 6h=${f(e6, 2)}h, ratio=${f(e4 / e6, 2)}`);
ok("8h dose sits at ~break-even (near-zero excess -> flat), independently of the figure",
   e8 < 0.5, `8h daily excess = ${f(e8, 2)} h/day`);
ok("model ordering matches digitized ordering (4h > 6h > 8h in excess and in day-14 lapses)",
   e4 > e6 && e6 > e8 && PVT.h4[day14] > PVT.h6[day14] && PVT.h6[day14] > PVT.h8[day14],
   "both methods agree on the ordering");

console.log("\n=== PANEL 3: BAC-EQUIVALENT (Dawson & Reid 1997, reaction-time tasks only) ===");
ok("reproduces the TWO published anchors exactly: 17h=0.05%, 24h=0.10%",
   approx(bacEquiv(17), 0.05, 1e-9) && approx(bacEquiv(24), 0.10, 1e-9),
   `17h=${f(bacEquiv(17), 2)}% and 24h=${f(bacEquiv(24), 2)}% BAC-equiv (published)`);
ok("22h is an INTERPOLATION between the two published points (~0.086%), NOT a published value",
   approx(bacEquiv(22), 0.0857, 5e-3) && !BAC_ANCHORS.some(a => a[0] === 22),
   `bacEquiv(22)=${f(bacEquiv(22), 3)}% = straight-line midpoint; page labels it interpolated`);
ok("BAC-equivalent is monotone increasing in hours awake",
   bacEquiv(17) < bacEquiv(22) && bacEquiv(22) < bacEquiv(24), "0.05 < ~0.086 < 0.10");
const slopeLocal = (0.10 - 0.05) / (24 - 17); // ~0.00714 %/h in the 17-24h band
ok("headline rate ~0.004%/h (10-26h) is SHALLOWER than the local 17-24h slope (curve is non-linear)",
   BAC_RATE_FULL < slopeLocal,
   `full-range ${f(BAC_RATE_FULL, 3)}%/h < local ${f(slopeLocal, 3)}%/h`);
ok("the 0.004%/h average over 10-26h lands in the observed 0.05-0.10% band",
   (() => { const rise = BAC_RATE_FULL * (26 - 10); return rise > 0.05 && rise < 0.10; })(),
   `0.004 x 16h = ${f(BAC_RATE_FULL * 16, 3)}% (within 0.05-0.10)`);

console.log("\n=== PANEL 4: MULTI-SYSTEM (reported values asserted against the primary sources) ===");
// These are the studies' REPORTED inferential statistics; we check direction + significance
// and the correct labels. We do not re-derive p-values (no raw subject data).
const spiegel = { n: 11, nights: 6, tib: 4, glucoseP: 0.02, tshP: 0.01, glucoseDir: "lower", tshDir: "lower" };
ok("Spiegel 1999: glucose tolerance change is significant and LOWER (toward impaired)",
   spiegel.glucoseP < 0.05 && spiegel.glucoseDir === "lower",
   `p<${spiegel.glucoseP}, n=${spiegel.n} men, ${spiegel.tib}h x ${spiegel.nights} nights`);
ok("Spiegel 1999: thyrotropin (TSH) change is significant and LOWER",
   spiegel.tshP < 0.05 && spiegel.tshDir === "lower", `p<${spiegel.tshP}`);
ok("Spiegel effect is framed as transient/reversible IGT in healthy young men, NOT 'diabetes'",
   spiegel.n === 11 && spiegel.tib === 4 && spiegel.nights === 6, "11 healthy young men, 4h x 6 nights");
const yoo = { pct: 60, valence: "negative/aversive", nights: 1, kind: "total", journal: "Current Biology" };
ok("Yoo 2007: amygdala reactivity +60% to NEGATIVE/aversive images after ONE night TOTAL deprivation",
   yoo.pct === 60 && yoo.valence === "negative/aversive" && yoo.nights === 1 && yoo.kind === "total",
   `+${yoo.pct}%, ${yoo.valence}, ${yoo.nights} night ${yoo.kind}`);
ok("Yoo 2007 is cited as Current Biology 17(20):R877, NOT Nature Neuroscience (guardrail)",
   yoo.journal === "Current Biology", yoo.journal);

console.log("\n=== PANEL 5: TOTAL-DEPRIVATION TIMELINE (survivable; FFI is a DISTINCT pathway) ===");
const gardner = { hours: 264, days: 11, survived: true, recovered: true };
ok("Randy Gardner reached 264 h (~11 days) and SURVIVED + recovered (impairment, not death march)",
   gardner.hours === 264 && approx(gardner.days, gardner.hours / 24, 0.5) && gardner.survived && gardner.recovered,
   `${gardner.hours} h = ${f(gardner.hours / 24)} days`);
const ffi = { prion: true, gene: "PRNP D178N-129M", region: "anteromedial thalamus", killsBy: "neurodegeneration" };
ok("FFI kills by PRION thalamic neurodegeneration, NOT by sleeplessness per se (guardrail)",
   ffi.prion && ffi.killsBy === "neurodegeneration" && ffi.gene === "PRNP D178N-129M",
   `${ffi.gene}, ${ffi.region}, kills by ${ffi.killsBy}`);
ok("microsleeps onset (~24 h) precedes the 264 h record (timeline is ordered)",
   24 < gardner.hours, "~24 h microsleeps < 264 h record");

console.log("\n=== PAGE READOUTS: numbers the dashboard displays must recompute here ===");
ok("Panel 1 readout: 6h day-14 = " + f(PVT.h6[day14]) + " lapses = " +
   Math.round(PVT.h6[day14] / TSD.lapses[1] * 100) + "% of one sleepless night",
   Math.round(PVT.h6[day14] / TSD.lapses[1] * 100) === 96, "matches the page's percent-of-a-night readout");
ok("Panel 2 readouts: 8h/6h/4h day-14 = " + f(PVT.h8[day14]) + " / " + f(PVT.h6[day14]) + " / " + f(PVT.h4[day14]),
   PVT.h8[day14] === 3.3 && PVT.h6[day14] === 9.7 && PVT.h4[day14] === 15.1, "exact digitized endpoints");
ok("data arrays are the full 14-day series (no truncation)",
   PVT.h4.length === 14 && PVT.h6.length === 14 && PVT.h8.length === 14 && SSS6.length === 14, "14 points each");

// ─────────────────────────────────────────────────────────────────────────────
console.log(`\n${"=".repeat(70)}`);
console.log(`RESULT: ${PASS} passed, ${FAIL} failed.`);
if (FAIL === 0) {
  console.log("ALL CHECKS PASS: the page's numbers reproduce from the digitized study data,");
  console.log("two independent ways for the flagship equivalence. Exit 0.");
  process.exit(0);
} else {
  console.log("A CHECK FAILED: do not ship. Exit 1.");
  process.exit(1);
}
