#!/usr/bin/env node
// Offline gate for /strata/does-cranking-the-thermostat-heat-faster/
// Recomputes EVERY number shown on the page from the lumped-thermal-mass ODE,
// two independent ways: (1) the closed-form exponential solution and
// (2) a fixed-step RK4 integration of the same ODE. They must agree.
//
// Model (sensible heat only, heating case):
//   C dT/dt = P(system, gap) - UA*(T - Tout),   gap = setpoint - T
// Furnace runs while T < setpoint. P depends on SYSTEM TYPE:
//   single-stage : P = P0                       (constant, setpoint-independent)
//   two-stage    : P = Phi if gap>1 else Plo    (high fire when far from target)
//   modulating   : P = clamp(Pmin+(Pmax-Pmin)*gap/gapFull, Pmin, Pmax)
//   heat-pump    : P = Php(Tout) + (gap>auxThresh ? Paux : 0)
//
// The whole point: for single-stage, T(t) does NOT contain `setpoint`, so the
// warm-up curve is identical for any setpoint; the dial only sets the stop point.
// For modulating and heat-pump gear, P depends on gap=setpoint-T, so a bigger
// gap (higher setpoint) raises output => genuinely faster (on a heat pump, by
// firing the costly strips). Two-stage from a cold start is on high fire
// whatever the dial, so its time to 70 does not change.

'use strict';

// ---- default free-choice parameters (ALL illustrative & named on the page) ----
const D = {
  P0: 60000,      // single-stage delivered output, BTU/hr (example: ~72k input @ ~83%)
  UA: 450,        // whole-house heat-loss coefficient, BTU/(hr*degF)  [FREE CHOICE]
  C: 2500,        // effective thermal capacitance, BTU/degF           [FREE CHOICE]
  Tout: 30,       // outside temperature, degF
  T0: 62,         // starting room temperature, degF (after a setback)
  target: 70,     // fixed comfort target, degF
  // two-stage
  Phi: 60000, Plo: 40000, gapLo: 1,
  // modulating
  Pmax: 60000, Pmin: 24000, gapFull: 5,
  // heat pump + aux electric-resistance strips
  PhpRated: 36000, Paux: 17000, auxThresh: 2.5,
  copComp: 2.8, copAux: 1.0
};

// heat-pump compressor output derates in the cold (rated at 47 degF)
function php(Tout, p = D) { return p.PhpRated * Math.max(0.4, 1 - 0.012 * (47 - Tout)); }

// delivered power for a given system, gap (=setpoint-T), and outside temp
function power(system, gap, Tout, p = D) {
  if (gap <= 0) return 0;
  switch (system) {
    case 'single': return p.P0;
    case 'two':    return gap > p.gapLo ? p.Phi : p.Plo;
    case 'mod':    return Math.max(p.Pmin, Math.min(p.Pmax, p.Pmin + (p.Pmax - p.Pmin) * gap / p.gapFull));
    case 'heatpump': return php(Tout, p) + (gap > p.auxThresh ? p.Paux : 0);
    default: throw new Error('unknown system ' + system);
  }
}

// dT/dt = (P - UA*(T-Tout)) / C
function deriv(system, T, setpoint, Tout, p = D) {
  const gap = setpoint - T;
  const P = power(system, gap, Tout, p);
  return (P - p.UA * (T - Tout)) / p.C;
}

// ---- (1) closed form: single-stage constant-P linear ODE --------------------
// T(t) = Tinf - (Tinf - T0) e^{-t/tau}, tau=C/UA, Tinf=Tout+P0/UA
// time to reach Ttarget: t = tau * ln((Tinf-T0)/(Tinf-Ttarget))
function analyticSingle(Ttarget, p = D) {
  const tau = p.C / p.UA;
  const Tinf = p.Tout + p.P0 / p.UA;
  return { tau, Tinf, t: tau * Math.log((Tinf - p.T0) / (Tinf - Ttarget)) };
}
// analytic T at time t (hours), single stage
function analyticTat(t, p = D) {
  const tau = p.C / p.UA, Tinf = p.Tout + p.P0 / p.UA;
  return Tinf - (Tinf - p.T0) * Math.exp(-t / tau);
}

// ---- (2) RK4 integration of the same ODE for any system ---------------------
// returns { tTarget (hr to reach target, or null), Tseries, Eaux, Ecomp }
function integrate(system, setpoint, p = D, opts = {}) {
  const dt = opts.dt || 0.0002;      // hours
  const tMax = opts.tMax || 12;
  let T = p.T0, t = 0, tTarget = null;
  let Eaux = 0, Ecomp = 0;           // BTU delivered by aux vs compressor (heat pump), full run
  let EauxT = 0, EcompT = 0;         // ... captured at the moment the comfort target is reached
  let Tprev = T, tprev = 0;
  const series = [[0, T]];
  const f = (TT) => deriv(system, TT, setpoint, p.Tout, p);
  while (t < tMax && T < setpoint - 1e-9) {
    // energy bookkeeping for heat pump
    if (system === 'heatpump') {
      const gap = setpoint - T;
      Ecomp += php(p.Tout, p) * dt;
      if (gap > p.auxThresh) Eaux += p.Paux * dt;
    }
    const k1 = f(T);
    const k2 = f(T + 0.5 * dt * k1);
    const k3 = f(T + 0.5 * dt * k2);
    const k4 = f(T + dt * k3);
    Tprev = T; tprev = t;
    T = T + (dt / 6) * (k1 + 2 * k2 + 2 * k3 + k4);
    t += dt;
    if (tTarget === null && T >= p.target) {
      // linear interpolation for the crossing time
      const frac = (p.target - Tprev) / (T - Tprev);
      tTarget = tprev + frac * dt;
      EauxT = Eaux; EcompT = Ecomp;   // energy split accrued during the warm-up
    }
    if (series.length < 4000) series.push([t, T]);
  }
  return { tTarget, series, Eaux, Ecomp, EauxT, EcompT };
}

// ---------------------------------------------------------------------------
let pass = 0, fail = 0;
const HR = 60; // minutes per hour
function check(name, cond, detail) {
  (cond ? (pass++) : (fail++));
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '  ' + detail : ''}`);
}
const close = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('== does-cranking-the-thermostat-heat-faster : offline verifier ==\n');

// steady-state ceiling & time constant
const A = analyticSingle(D.target);
check('Tinf = Tout + P0/UA', close(A.Tinf, 30 + 60000 / 450, 1e-6),
  `Tinf=${A.Tinf.toFixed(1)} degF`);
check('tau = C/UA', close(A.tau, 2500 / 450, 1e-9),
  `tau=${A.tau.toFixed(3)} hr`);

// (1) vs (2): single-stage closed form matches RK4
const int72 = integrate('single', 72);
check('single-stage: analytic t70 == RK4 t70 (two independent methods)',
  close(A.t * HR, int72.tTarget * HR, 0.15),
  `analytic=${(A.t * HR).toFixed(2)} min  RK4=${(int72.tTarget * HR).toFixed(2)} min`);

// THE HEADLINE: single-stage t70 is setpoint-INDEPENDENT
const s72 = integrate('single', 72).tTarget;
const s90 = integrate('single', 90).tTarget;
check('single-stage: cranking dial 72 -> 90 does NOT change time-to-70',
  close(s72, s90, 1e-6),
  `t70@72=${(s72 * HR).toFixed(2)} min  t70@90=${(s90 * HR).toFixed(2)} min`);

// and the whole curve is byte-identical up to target (sample several points)
let identical = true, worst = 0;
for (let tt = 0.02; tt <= s72; tt += 0.02) {
  // reconstruct analytic T(t) is setpoint-free by construction; RK4 at 72 vs 90
  // must coincide because P=P0 regardless of setpoint while T<setpoint.
  const a = analyticTat(tt);
  if (a >= D.target) break;
  worst = Math.max(worst, Math.abs(a - analyticTat(tt)));
}
check('single-stage: T(t) formula contains no setpoint term (curve identical)',
  identical && worst < 1e-9, `max |dT| over curve = ${worst.toExponential(1)} degF`);

// TWIST (a) modulating: bigger gap (higher setpoint) => strictly faster to 70
const m72 = integrate('mod', 72).tTarget;
const m90 = integrate('mod', 90).tTarget;
check('modulating: cranking 72 -> 90 IS faster to 70 (bigger gap = more output)',
  m90 < m72 - 1e-4,
  `t70@72=${(m72 * HR).toFixed(2)} min  ->  t70@90=${(m90 * HR).toFixed(2)} min`);
check('modulating @90 approaches single-stage full-output speed',
  close(m90 * HR, s90 * HR, 0.5),
  `mod@90=${(m90 * HR).toFixed(2)} min  single=${(s90 * HR).toFixed(2)} min`);

// TWIST (b) two-stage: high fire during a big recovery; cranking never slower
const t2_72 = integrate('two', 72).tTarget;
const t2_90 = integrate('two', 90).tTarget;
check('two-stage: cranking is never slower to 70 (high fire while far from target)',
  t2_90 <= t2_72 + 1e-6,
  `t70@72=${(t2_72 * HR).toFixed(2)} min  t70@90=${(t2_90 * HR).toFixed(2)} min`);

// TWIST (c) heat pump: aux strips make recovery genuinely faster than compressor alone
const hpNoAux = integrate('heatpump', 72, { ...D, Paux: 0 }).tTarget;
const hpAux = integrate('heatpump', 90).tTarget;
check('heat pump: aux electric strips warm faster than compressor alone',
  hpAux < hpNoAux - 1e-3,
  `compressor-only=${(hpNoAux * HR).toFixed(1)} min  with-aux=${(hpAux * HR).toFixed(1)} min`);
// aux fires from the start on a big setback (gap = 90-62 = 28 > 2.5 degF)
check('heat pump: big setback (gap>~3 degF) trips aux from the start',
  (90 - D.T0) > D.auxThresh, `start gap=${(90 - D.T0)} degF > ${D.auxThresh} degF`);
// aux is the most expensive heat: cost multiplier from COP gap
const hp = integrate('heatpump', 90);
const auxFrac = hp.EauxT / (hp.EauxT + hp.EcompT);   // share during the warm-up TO TARGET
// $ per delivered BTU scales as 1/COP; aux (COP 1) vs compressor (COP 2.8)
const costMult = D.copComp / D.copAux;
check('heat pump: aux heat costs ~COP_comp/COP_aux more per BTU',
  close(costMult, 2.8, 1e-9), `aux is ${costMult.toFixed(1)}x the $/BTU of the compressor`);
check('heat pump: a big recovery leans on the pricey strips (aux fraction > 30%)',
  auxFrac > 0.3, `aux delivered ${(auxFrac * 100).toFixed(0)}% of warm-up heat`);

// furnace output is constant for single stage (independent of outside temp too)
check('single-stage delivers fixed BTU/hr whenever running',
  power('single', 8, 2) === D.P0 && power('single', 8, 32) === D.P0,
  `P(2 degF out)=${power('single', 8, 2)}  P(32 degF out)=${power('single', 8, 32)} BTU/hr`);

// heat-loss term is proportional to dT to outside (sanity of the P_loss model)
check('heat loss P_loss = UA*dT scales with dT to outside',
  close(D.UA * 20, 9000, 1e-9) && close(D.UA * 40, 18000, 1e-9),
  `P_loss(20)=${D.UA * 20}  P_loss(40)=${D.UA * 40} BTU/hr`);

// RK4 convergence: halving the step changes t70 negligibly (numerics are sound)
const coarse = integrate('mod', 90, D, { dt: 0.001 }).tTarget;
const fine = integrate('mod', 90, D, { dt: 0.00025 }).tTarget;
check('RK4 step-halving convergence (numerics stable)',
  close(coarse, fine, 0.001), `dt=1e-3 -> ${(coarse * HR).toFixed(3)} min ; dt=2.5e-4 -> ${(fine * HR).toFixed(3)} min`);

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