#!/usr/bin/env node
// Offline gate for the immersive stratum "The Clock Was Never the Problem"
// (is-the-5-second-rule-real). Recomputes every number shown on the page from
// the same transfer model, and independently re-checks that the model lands on
// the reported findings of the primary sources.
//
// Model (mirrors the inline <script> in public/strata/.../index.html):
//   transfer% = TREF * m(food) * s(surface) * tf(t)
//     TREF  = 97   (max: watermelon on smooth steel at 300 s; paper's "up to ~97%")
//     m     = { melon 1.00, bread 0.35, gummy 0.004 }   moisture (tracks water activity)
//     s     = { steel 1.00, tile 0.97, wood 0.68, carpet 0.10 }   surface efficiency
//     tf(t) = 0.90 + 0.10 * ln(t/0.5)/ln(600)           smooth, monotone, no step at 5 s
//
// PRIMARY sources the checks are anchored to:
//   Miranda RC, Schaffner DW. Appl. Environ. Microbiol. 82(21):6490-6496 (2016).
//     DOI 10.1128/AEM.01838-16 . Open access PMC5066366.
//   Dawson P et al. J. Appl. Microbiol. 102(4):945-953 (2007).
//     DOI 10.1111/j.1365-2672.2006.03171.x .
//
// Exit 0 iff all checks pass.

const TREF = 97;
const MOIST = { gummy: 0.004, bread: 0.35, melon: 1.00 };
const SURF = { steel: 1.00, tile: 0.97, wood: 0.68, carpet: 0.10 };
const AW = { gummy: 0.72, bread: 0.94, melon: 0.99 };

const tf = (t) => 0.90 + 0.10 * Math.log(t / 0.5) / Math.log(600);
function transfer(food, surf, t) {
  const v = TREF * MOIST[food] * SURF[surf] * tf(t);
  return Math.max(0, Math.min(100, v));
}

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

console.log("== is-the-5-second-rule-real : offline verifier ==\n");

// ─────────────────────────────────────────────────────────────────────────
// METHOD 1 : recompute the exact numbers the page displays
// ─────────────────────────────────────────────────────────────────────────
console.log("-- Method 1: recompute the shown numbers from the model --");

// tf anchor values used to reason about the curve
check("tf(<1s=0.5) = 0.900", approx(tf(0.5), 0.900, 1e-9), `tf=${tf(0.5).toFixed(4)}`);
check("tf(300) = 1.000", approx(tf(300), 1.000, 1e-9), `tf=${tf(300).toFixed(4)}`);
check("tf monotone increasing in t (no cliff, no step)", (() => {
  let prev = -1;
  for (let i = 0; i <= 400; i++) {
    const t = 0.5 * Math.pow(600, i / 400);
    const v = tf(t);
    if (v < prev - 1e-12) return false;
    prev = v;
  }
  return true;
})());

// headline anchor cells the page + prose assert
const wSteel300 = transfer("melon", "steel", 300);
check("watermelon/steel/300s = up-to-~97% (90..97 band)", wSteel300 >= 90 && wSteel300 <= 97,
  `${wSteel300.toFixed(1)}%`);
const wSteelInstant = transfer("melon", "steel", 0.5);
check("watermelon/steel/<1s already high (>=85%)", wSteelInstant >= 85, `${wSteelInstant.toFixed(1)}%`);
const gSteelInstant = transfer("gummy", "steel", 0.5);
check("gummy/steel/<1s near/below detection (<0.5%)", gSteelInstant < 0.5, `${gSteelInstant.toFixed(3)}%`);
const gCarpetInstant = transfer("gummy", "carpet", 0.5);
check("gummy range reaches ~0.1% or below (carpet/<1s)", gCarpetInstant < 0.1, `${gCarpetInstant.toFixed(4)}%`);

// the money-shot number pair (moisture beats the clock)
const wetInstant = transfer("melon", "steel", 0.5);
const dry5min = transfer("gummy", "steel", 300);
check("watermelon @<1s > gummy @300s (instant wet dirtier than 5-min dry)",
  wetInstant > dry5min, `${wetInstant.toFixed(1)}% vs ${dry5min.toFixed(3)}%`);

// three-dial swing readouts shown in the .dials panel (food=melon, surf=steel, t=5)
const tSwing = transfer("melon", "steel", 300) / transfer("melon", "steel", 0.5);
const sSwing = transfer("melon", "steel", 5) / transfer("melon", "carpet", 5);
const mSwing = transfer("melon", "steel", 5) / transfer("gummy", "steel", 5);
check("time-dial swing ~ +11% (<1s->300s)", approx((tSwing - 1) * 100, 11, 1), `+${((tSwing - 1) * 100).toFixed(1)}%`);
check("surface-dial swing ~10x (carpet->steel)", approx(sSwing, 10, 0.5), `${sSwing.toFixed(1)}x`);
check("moisture-dial swing ~250x (gummy->watermelon)", approx(mSwing, 250, 1), `${mSwing.toFixed(0)}x`);

// water-activity labels shown on the food buttons
check("watermelon aw = 0.99", AW.melon === 0.99);
check("gummy aw = 0.72", AW.gummy === 0.72);

// ─────────────────────────────────────────────────────────────────────────
// METHOD 2 : independent structural re-checks against the papers' FINDINGS
// (assert the qualitative claims hold, without reusing Method-1 point values)
// ─────────────────────────────────────────────────────────────────────────
console.log("\n-- Method 2: independent structural checks vs the papers' findings --");

// Miranda&Schaffner finding A: transfer occurs at the shortest contact time (no safe window)
check("no safe window: every food/surface transfers > 0 at <1 s",
  ["gummy", "bread", "melon"].every(fd => ["steel", "tile", "wood", "carpet"].every(sf =>
    transfer(fd, sf, 0.5) > 0)));

// Finding B: NO cliff at 5 s. The <1s->5s change is tiny and there is no discontinuity.
const stepEarly = transfer("melon", "steel", 5) / transfer("melon", "steel", 0.5) - 1;
check("no 5 s cliff: <1s->5s changes transfer < 10%", stepEarly < 0.10, `+${(stepEarly * 100).toFixed(1)}%`);
// discontinuity probe: sample densely across 5 s, no jump
check("transfer(t) continuous across t=5 (no step)", (() => {
  // a true step/cliff would leave a finite jump as delta->0; a continuous
  // curve shrinks the difference in proportion to the shrinking delta.
  const wide = Math.abs(transfer("melon", "tile", 5.5) - transfer("melon", "tile", 4.5));
  const narrow = Math.abs(transfer("melon", "tile", 5.05) - transfer("melon", "tile", 4.95));
  return narrow < wide * 0.2; // ~10x smaller delta -> ~10x smaller gap: no cliff
})());

// Finding C: contact time is statistically significant but WEAKEST of three drivers.
// -> the full time swing is smaller than the surface swing is smaller than the moisture swing,
//    checked across ALL food/surface combinations, not just the default cell.
let orderingHolds = true;
for (const fd of ["gummy", "bread", "melon"]) {
  const tS = transfer(fd, "steel", 300) / transfer(fd, "steel", 0.5);          // time dial
  const sS = transfer(fd, "steel", 5) / transfer(fd, "carpet", 5);              // surface dial
  if (!(tS < sS)) orderingHolds = false;
}
for (const sf of ["steel", "tile", "wood", "carpet"]) {
  const sS = transfer("melon", sf, 5) / transfer("melon", "carpet", 5) || 1;
  const mS = transfer("melon", sf, 5) / transfer("gummy", sf, 5);              // moisture dial
  if (!(mS > sS)) orderingHolds = false;
}
check("time is weakest dial: time-swing < surface-swing < moisture-swing (all combos)", orderingHolds);

// time swing must be modest everywhere (a "weak" driver): <1s->300s always < 15%
let timeWeakEverywhere = true;
for (const fd of ["gummy", "bread", "melon"]) {
  for (const sf of ["steel", "tile", "wood", "carpet"]) {
    const r = transfer(fd, sf, 300) / transfer(fd, sf, 0.5);
    if (r > 1.15) timeWeakEverywhere = false;
  }
}
check("time swing < +15% for every food/surface (weakest driver)", timeWeakEverywhere);

// Finding D (both papers): carpet has the LOWEST transfer; smooth surfaces the highest.
let carpetLowest = true, smoothHighest = true;
for (const fd of ["gummy", "bread", "melon"]) {
  for (const t of [0.5, 5, 30, 300]) {
    const c = transfer(fd, "carpet", t);
    for (const sf of ["steel", "tile", "wood"]) {
      if (transfer(fd, sf, t) < c - 1e-12) carpetLowest = false;
    }
    // smooth (steel/tile) >= wood >= carpet
    if (!(transfer(fd, "steel", t) >= transfer(fd, "wood", t) &&
          transfer(fd, "wood", t) >= transfer(fd, "carpet", t))) smoothHighest = false;
  }
}
check("carpet is the lowest surface at every food/time (Miranda + Dawson)", carpetLowest);
check("ordering steel/tile >= wood >= carpet (smooth highest)", smoothHighest);

// Finding E: moisture dominates. For any fixed surface/time, watermelon >> gummy by > 100x.
let moistureDominates = true;
for (const sf of ["steel", "tile", "wood", "carpet"]) {
  for (const t of [0.5, 5, 30, 300]) {
    if (transfer("melon", sf, t) / transfer("gummy", sf, t) < 100) moistureDominates = false;
  }
}
check("moisture dominates: watermelon/gummy ratio > 100x at every surface/time", moistureDominates);

// Dawson 2007 corroboration: model reproduces tile >> carpet ordering (its headline contrast).
check("Dawson ordering reproduced: tile transfer >> carpet transfer (wet food, 5 s)",
  transfer("melon", "tile", 5) > 5 * transfer("melon", "carpet", 5),
  `${transfer("melon", "tile", 5).toFixed(1)}% vs ${transfer("melon", "carpet", 5).toFixed(1)}%`);

// clamp sanity: nothing exceeds 100% or drops below 0
let clamped = true;
for (const fd of ["gummy", "bread", "melon"])
  for (const sf of ["steel", "tile", "wood", "carpet"])
    for (const t of [0.5, 1, 5, 30, 300]) {
      const v = transfer(fd, sf, t);
      if (v < 0 || v > 100) clamped = false;
    }
check("all transfers within [0,100]%", clamped);

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