#!/usr/bin/env node
// Offline gate for /strata/can-a-fridge-cool-a-room/.
// Recomputes EVERY number the page shows, from first-law thermodynamics, two
// independent ways where possible. Exit 0 iff all checks pass.
//
// Physics (heat pump, first law):  Qh = Qc + W ,  COP = Qc / W.
//   FRIDGE (both coils in the room): net heat to room = Qh - Qc = W        (COP-independent)
//   AC     (hot coil out the window): net heat to room = -Qc = -COP*W
//   Sealed-room warming rate (idealised): dT/dt = net / (rho*V*c) , deg C/hr.

const RHO = 1.2, VOL = 40, CP = 1005;      // sealed-room air (kg/m3, m3, J/kgK), ~20 C
const CROOM = RHO * VOL * CP;              // J/K

const qc = (W, cop) => cop * W;
const qh = (W, cop) => qc(W, cop) + W;
const netFridge = (W /*, cop */) => W;                 // by the derivation below
const netAC = (W, cop) => -qc(W, cop);
const ratePerHour = (netW) => netW / CROOM * 3600;

let pass = 0, fail = 0;
const EPS = 1e-9;
function check(name, cond, detail = "") {
  const tag = cond ? "PASS" : "FAIL";
  if (cond) pass++; else fail++;
  console.log(`${tag}  ${name}${detail ? "  ·  " + detail : ""}`);
}
function near(a, b, eps = EPS) { return Math.abs(a - b) <= eps; }

console.log("=== can-a-fridge-cool-a-room · verifier ===\n");

// ── 1. First-law identity Qh - Qc = W, over a grid (two ways: define & derive)
{
  const Ws = [50, 100, 150, 250, 400];
  const cops = [1.0, 2.0, 2.5, 3.5, 5.0];
  let maxErr = 0;
  for (const W of Ws) for (const c of cops) {
    // way A: from the closed-form Qh, Qc
    const dA = qh(W, c) - qc(W, c);
    // way B: independent symbolic reconstruction Qh=(cop+1)W, Qc=cop*W
    const dB = (c + 1) * W - c * W;
    maxErr = Math.max(maxErr, Math.abs(dA - W), Math.abs(dB - W), Math.abs(dA - dB));
  }
  check("Qh - Qc = W  (25 (W,COP) pairs, two derivations agree)", maxErr < EPS,
        `max error ${maxErr.toExponential(2)} W`);
}

// ── 2. FRIDGE net is exactly +W and COP-INDEPENDENT (the subtle gem)
{
  const cops = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 5.0];
  const W = 150;
  let maxDrift = 0;
  for (const c of cops) {
    // net computed the honest way: (heat landing in room) - (heat leaving) with BOTH coils indoors
    // both Qc and Qh land in the room; the only export is... nothing. net = Qh - Qc.
    const netLedger = qh(W, c) - qc(W, c);
    maxDrift = Math.max(maxDrift, Math.abs(netLedger - W), Math.abs(netFridge(W, c) - W));
  }
  check("FRIDGE net(W=150) = +150 W for every COP 1.0..5.0 (no-op slider)", maxDrift < EPS,
        `max drift across 8 COPs = ${maxDrift.toExponential(2)} W`);
}

// ── 3. FRIDGE always WARMS: net > 0 for all positive W (no cooling operating point)
{
  let allWarm = true;
  for (let W = 1; W <= 800; W += 1) for (const c of [1.0, 2.5, 5.0]) {
    if (netFridge(W, c) <= 0) allWarm = false;
  }
  check("FRIDGE net > 0 for all W in 1..800 W (whole-room always warms)", allWarm);
}

// ── 4. AC net = -COP*W  (sign flips; COP now bites)
{
  const cases = [[150, 2.5, -375], [150, 3.0, -450], [250, 4.0, -1000], [100, 1.5, -150]];
  let ok = true, detail = [];
  for (const [W, c, expect] of cases) {
    const got = netAC(W, c);
    ok = ok && near(got, expect);
    detail.push(`W=${W},COP=${c}→${got}`);
  }
  check("AC net = -COP*W  (removes heat from room)", ok, detail.join("  "));
}

// ── 5. The exact on-page default ledger (W=150, COP=2.5, fridge): Qc, W, Qh, net
{
  const W = 150, c = 2.5;
  const Qc = qc(W, c), Qh = qh(W, c), net = netFridge(W, c);
  const ok = near(Qc, 375) && near(Qh, 525) && near(net, 150);
  check("default fridge ledger: Qc=375, W=150, Qh=525, net=+150 W", ok,
        `Qc=${Qc} Qh=${Qh} net=${net}`);
}

// ── 6. Sealed-room warming rate shown on load (fridge, W=150) ≈ +11.2 C/hr
{
  const W = 150;
  const rate = ratePerHour(netFridge(W)); // deg C / hr
  // independent recompute of the constant: 150 J/s / 48240 J/K = 3.109e-3 K/s * 3600
  const rate2 = (150 / (1.2 * 40 * 1005)) * 3600;
  const ok = near(rate, rate2) && Math.abs(rate - 11.2) < 0.05;
  check("sealed-room rate (fridge,150W) = +11.2 C/hr (two computations agree)",
        ok, `rate=${rate.toFixed(3)} C/hr, CROOM=${CROOM.toFixed(0)} J/K`);
}

// ── 7. AC sealed-room rate is negative (cools): W=150, COP=2.5 → -Qc rate
{
  const W = 150, c = 2.5;
  const rate = ratePerHour(netAC(W, c));
  check("sealed-room rate (AC,150W,COP2.5) < 0 (room cools)", rate < 0,
        `rate=${rate.toFixed(2)} C/hr`);
}

// ── 8. Sanity on cited running-wattage window: default 150 W sits within 100-250 W;
//       the slider range 50..400 brackets the honest household running-draw span.
{
  const lo = 100, hi = 250, dflt = 150, sMin = 50, sMax = 400;
  const ok = dflt >= lo && dflt <= hi && sMin <= lo && sMax >= hi;
  check("cited running draw ~100-250 W: default 150 W inside; slider 50-400 W brackets it", ok,
        `default=${dflt}W, band=[${lo},${hi}]W, slider=[${sMin},${sMax}]W`);
}

// ── 9. COP dependence ONLY in AC mode: dNet/dCOP = 0 (fridge) and = -W (AC)
{
  const W = 200, c1 = 2.0, c2 = 4.0;
  const dFridge = (netFridge(W, c2) - netFridge(W, c1)) / (c2 - c1); // must be 0
  const dAC = (netAC(W, c2) - netAC(W, c1)) / (c2 - c1);             // must be -W
  const ok = near(dFridge, 0) && near(dAC, -W);
  check("d(net)/d(COP): 0 in fridge mode, -W in AC mode", ok,
        `fridge=${dFridge}, AC=${dAC} (expect 0, ${-W})`);
}

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