#!/usr/bin/env node
// verify-does-hot-water-freeze-faster-than-cold.mjs
//
// Offline gate for /strata/does-hot-water-freeze-faster-than-cold/.
// Recomputes EVERY number the page shows, from Newton's law of cooling and the
// small, fully-stated freezing model, and checks self-consistency, where possible
// two independent ways. Exits 0 iff all checks pass.
//
//   Newton cooling      T(t)  = Tenv + (T0 - Tenv)*exp(-k*t)
//   time to a target    t*    = (1/k)*ln((T0 - Tenv)/(target - Tenv))
//   curve gap           D(t)  = (Th - Tc)*exp(-k*t)          > 0 for all finite t
//   evaporation         massLost(T0) = evap*E_MAX*T0/k       (integral of Newton cooling to 0C)
//   full-solid time     fullFreeze(T0) = t*(0C) + LAMBDA*(M0 - massLost(T0))
//   evap flip           evap* = [t*(Th,0) - t*(Tc,0)] / [LAMBDA*E_MAX*(Th-Tc)/k]
//   supercool lottery   Tn ~ Uniform[NUC_LO, NUC_HI]; seeded mulberry32 Monte Carlo
//   probe artifact      gapAtCross = (Th-Tc)*(-Tenv)/(Tc-Tenv);  false win when G*dh > gap
//
// These constants and formulas mirror the inline <script> in index.html exactly.
//
// Sources (see README.md):
//   Burridge & Linden (2016), Sci. Rep. 6:37665 - no robust Mpemba effect for water,
//     ~1 cm probe-height error manufactures a false positive.
//   Mpemba & Osborne (1969), Phys. Educ. 4:172 - the single origin dataset.
//   Lu & Raz (2017) PNAS; Kumar & Bechhoefer (2020) Nature - the effect is real in
//     engineered non-equilibrium systems.

const E_MAX = 1 / 6000;   // at evap=1, T0=90, k=0.03 -> massLost = 0.5
const LAMBDA = 200;       // latent-plateau minutes per unit mass
const M0 = 1;
const NUC_LO = -15, NUC_HI = -1;
const G_GRAD = 2.0;       // deg C per cm
const MC_N = 100, MC_SEED = 12345;

// mutable scenario (mirrors the page state)
let Th = 90, Tc = 25, k = 0.030, Tenv = -18, evap = 0;

const Tof = (T0, t) => Tenv + (T0 - Tenv) * Math.exp(-k * t);
const timeTo = (T0, target) => (1 / k) * Math.log((T0 - Tenv) / (target - Tenv));
const massLost = (T0) => evap * E_MAX * T0 / k;
const mAtZero = (T0) => Math.max(0, M0 - massLost(T0));
const fullFreeze = (T0) => timeTo(T0, 0) + LAMBDA * mAtZero(T0);
const diff = (t) => (Th - Tc) * Math.exp(-k * t);
const evapFlip = () => {
  const num = timeTo(Th, 0) - timeTo(Tc, 0);
  const den = LAMBDA * E_MAX * (Th - Tc) / k;
  return den > 0 ? num / den : Infinity;
};
const gapAtCross = () => (Th - Tc) * (-Tenv) / (Tc - Tenv);
const probeFlipDh = () => gapAtCross() / G_GRAD;

function mulberry32(a) {
  return function () {
    a |= 0; a = a + 0x6D2B79F5 | 0;
    let t = Math.imul(a ^ a >>> 15, 1 | a);
    t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}
const nucLo = () => Math.max(NUC_LO, Tenv + 0.5);
function monteCarloWins() {
  const rnd = mulberry32(MC_SEED), lo = nucLo(), hi = NUC_HI;
  if (hi <= lo) return 0;
  let wins = 0;
  for (let i = 0; i < MC_N; i++) {
    const TnH = lo + (hi - lo) * rnd();
    const TnC = lo + (hi - lo) * rnd();
    if (timeTo(Th, TnH) < timeTo(Tc, TnC)) wins++;
  }
  return wins;
}

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

console.log('-- Mpemba / cooling-curve model -- does-hot-water-freeze-faster-than-cold --\n');
console.log(`Default scenario: Th=${Th} Tc=${Tc} k=${k} Tenv=${Tenv} evap=${evap}\n`);

// --- Definition (a): the no-crossing theorem --------------------------------

// 1) Closed-form time-to-0C matches a numerically-integrated Newton cooling to 0C.
{
  const tClosed = timeTo(90, 0);
  // independent way: step dt until Tof crosses 0
  let t = 0, dt = 0.0005;
  while (Tof(90, t) > 0 && t < 1e5) t += dt;
  check('time-to-0C closed form == numeric integration (hot, 90C)',
    approx(tClosed, t, 2 * dt), `closed=${tClosed.toFixed(3)} numeric=${t.toFixed(3)} min`);
}

// 2) D(t) = (Th-Tc)*exp(-kt) is strictly positive on a dense grid: hot never crosses first.
{
  let ok = true, minD = Infinity;
  for (let t = 0; t <= 5000; t += 1) { const d = diff(t); if (d < minD) minD = d; if (d <= 0) ok = false; }
  check('def (a): hot minus cold > 0 for 0..5000 min (zero crossings = 0)',
    ok && Th > Tc, `min D = ${minD.toExponential(3)} deg C`);
}

// 3) Second, independent proof: at EVERY temperature the cold sample passes through,
//    the hot sample reaches it strictly later (monotone log map).
{
  let ok = true, worst = 0;
  for (let target = 0.5; target < Tc; target += 0.5) {
    const gap = timeTo(Th, target) - timeTo(Tc, target);
    worst = Math.min(worst, gap);
    if (gap <= 0) ok = false;
  }
  check('def (a): hot reaches every shared temperature later than cold',
    ok, `smallest lead of cold = ${worst.toFixed(3)} min (positive)`);
}

// 4) Under (a) the hot sample reaches 0C later than cold, by the exact log ratio.
{
  const tHot = timeTo(90, 0), tCold = timeTo(25, 0);
  const expectedHot = (1 / k) * Math.log(108 / 18);   // (90+18)/(0+18)
  const expectedCold = (1 / k) * Math.log(43 / 18);   // (25+18)/(0+18)
  check('def (a): hot 0C-time later than cold, both match ln-ratio',
    tHot > tCold && approx(tHot, expectedHot) && approx(tCold, expectedCold),
    `hot=${tHot.toFixed(2)} cold=${tCold.toFixed(2)} min`);
}

// --- Definition (b): full-solid with evaporation ----------------------------

// 5) Evaporation mass-loss integral: massLost(T0) = E*T0/k equals the direct
//    integral E*(T0-Tenv)/k*(1-exp(-k*t*)) over the cooling-to-0C phase.
{
  evap = 0.5;
  const E = evap * E_MAX;
  const T0 = 90, t1 = timeTo(T0, 0);
  const closed = E * T0 / k;
  const integral = E * (T0 - Tenv) / k * (1 - Math.exp(-k * t1));
  check('def (b): mass-loss closed form == cooling integral (T0=90)',
    approx(closed, integral, 1e-9), `closed=${closed.toFixed(4)} integral=${integral.toFixed(4)}`);
  evap = 0;
}

// 6) With no evaporation the hot sample is fully solid LATER than cold (never wins).
{
  evap = 0;
  check('def (b) evap=0: cold fully solid first (hot never wins)',
    fullFreeze(Tc) < fullFreeze(Th),
    `cold=${fullFreeze(Tc).toFixed(1)} < hot=${fullFreeze(Th).toFixed(1)} min`);
}

// 7) The evaporation flip threshold is correct: at evap = evap* the two full-solid
//    times are EQUAL; just above it the hot sample wins.
{
  const sStar = evapFlip();
  evap = sStar;
  const eq = approx(fullFreeze(Th), fullFreeze(Tc), 1e-6);
  evap = Math.min(1, sStar + 0.02);
  const hotWins = fullFreeze(Th) < fullFreeze(Tc);
  check('def (b): at evap* full-solid times equal; just above it hot wins',
    eq && hotWins && sStar > 0 && sStar < 1,
    `evap* = ${sStar.toFixed(3)}`);
  evap = 0;
}

// 8) The default-scenario flip threshold is ~0.42 (the number the page reports).
{
  evap = 0; Th = 90; Tc = 25; k = 0.030; Tenv = -18;
  const sStar = evapFlip();
  check('def (b): default flip threshold evap* ~ 0.42',
    approx(sStar, 0.425, 0.02), `evap* = ${sStar.toFixed(3)}`);
}

// --- Definition (c): the supercooling lottery -------------------------------

// 9) The seeded Monte Carlo is deterministic and reproduces bit-for-bit.
{
  Th = 90; Tc = 25;
  const w1 = monteCarloWins(), w2 = monteCarloWins();
  check('def (c): seeded MC deterministic (mulberry32, seed 12345)',
    w1 === w2, `hot wins ${w1}/${MC_N} on both runs`);
}

// 10) Definition (c) CAN flip the winner (unlike (a), which is exactly 0), but only
//     as a minority of lotteries at far-apart starts.
{
  Th = 90; Tc = 25;
  const wFar = monteCarloWins();
  check('def (c): flips a minority of lotteries even at far starts (0 < wins < 25, vs def (a) = 0)',
    wFar > 0 && wFar < 25, `hot wins ${wFar}/${MC_N} (~${wFar}% ; matches Mpemba-Osborne-era ~11/100 illustration)`);
}

// 11) Closer starts raise the win-rate substantially (the contingency the page shows).
{
  Th = 40; Tc = 25;
  const wNear = monteCarloWins();
  Th = 90; Tc = 25;
  const wFar = monteCarloWins();
  check('def (c): close starts (40 vs 25) win more than far (90 vs 25)',
    wNear > wFar && wNear >= 15, `near=${wNear}/${MC_N}  far=${wFar}/${MC_N}`);
}

// 12) MC agrees with the analytic win-probability P(58a < 43b) for 40-vs-25, to
//     Monte-Carlo tolerance (independent cross-check of the lottery).
{
  Th = 40; Tc = 25; Tenv = -18;
  const wNear = monteCarloWins() / MC_N;
  // hot wins when timeTo(Th,TnH) < timeTo(Tc,TnC)
  //   <=> (Th-Tenv)/(TnH-Tenv) < (Tc-Tenv)/(TnC-Tenv)
  //   <=> (Th-Tenv)*(TnC-Tenv) < (Tc-Tenv)*(TnH-Tenv)
  // with a=TnC-Tenv, b=TnH-Tenv uniform on [lo-Tenv, hi-Tenv]; integrate numerically.
  const lo = Math.max(NUC_LO, Tenv + 0.5), hi = NUC_HI;
  const A = Th - Tenv, B = Tc - Tenv, aLo = lo - Tenv, aHi = hi - Tenv;
  let inside = 0, tot = 0, Nq = 400;
  for (let i = 0; i < Nq; i++) for (let j = 0; j < Nq; j++) {
    const a = aLo + (aHi - aLo) * (i + 0.5) / Nq;  // TnC - Tenv
    const b = aLo + (aHi - aLo) * (j + 0.5) / Nq;  // TnH - Tenv
    tot++;
    if (A * a < B * b) inside++;   // A*(TnC-Tenv) < B*(TnH-Tenv)
  }
  const pAnalytic = inside / tot;
  check('def (c): MC win-rate matches analytic probability (40 vs 25)',
    Math.abs(wNear - pAnalytic) < 0.08,
    `MC=${(wNear * 100).toFixed(0)}%  analytic=${(pAnalytic * 100).toFixed(0)}%`);
  Th = 90; Tc = 25;
}

// --- The probe artifact (Burridge & Linden's ~1 cm false positive) ----------

// 13) gapAtCross closed form equals the direct curve gap at the cold crossing time.
{
  Th = 90; Tc = 25; Tenv = -18; k = 0.030;
  const tCold0 = timeTo(Tc, 0);
  const direct = diff(tCold0);           // (Th-Tc)*exp(-k*tCold0)
  const closed = gapAtCross();           // (Th-Tc)*(-Tenv)/(Tc-Tenv)
  check('probe: gap-at-crossing closed form == direct curve gap',
    approx(closed, direct, 1e-6), `closed=${closed.toFixed(2)} direct=${direct.toFixed(2)} deg C`);
}

// 14) Far apart, 1 cm (= 2 deg C error) cannot fake it; the needed offset is huge.
{
  Th = 90; Tc = 25; Tenv = -18;
  const flip = probeFlipDh();
  check('probe: far starts need a huge offset to fake a win (flip >> 1 cm)',
    flip > 3 && G_GRAD * 1 < gapAtCross(),
    `gap=${gapAtCross().toFixed(1)} deg C, flip offset = ${flip.toFixed(1)} cm`);
}

// 15) Close to the crossing, ~1 cm IS enough: the paper's mechanism, reproduced.
{
  Th = 30; Tc = 25; Tenv = -18;
  const flip = probeFlipDh();          // cm needed to fake a win
  const fakedAt1cm = G_GRAD * 1.2 > gapAtCross();
  check('probe: close starts (30 vs 25) -> ~1 cm offset fakes a win',
    flip < 1.5 && fakedAt1cm,
    `gap=${gapAtCross().toFixed(2)} deg C, flip offset = ${flip.toFixed(2)} cm`);
  Th = 90; Tc = 25;
}

// --- The headline claims ----------------------------------------------------

// 16) Key number: under definition (a), across the whole plausible parameter box,
//     hot reproduces the effect 0 times (never crosses 0C first). Independent sweep.
{
  let everHotFirst = false, samples = 0;
  for (let th = 30; th <= 95; th += 5)
    for (let tc = 5; tc < th; tc += 5)
      for (const kk of [0.01, 0.03, 0.06])
        for (const te of [-25, -18, -8]) {
          Th = th; Tc = tc; k = kk; Tenv = te; samples++;
          if (timeTo(Th, 0) <= timeTo(Tc, 0)) everHotFirst = true;
        }
  check('KEY NUMBER: def (a) reproduces the effect 0 times across the parameter box',
    !everHotFirst, `${samples} scenarios swept, hot-first count = 0`);
  Th = 90; Tc = 25; k = 0.030; Tenv = -18;
}

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