#!/usr/bin/env node
// verify-does-concrete-dry.mjs
//
// Offline gate for /strata/does-concrete-dry/. Recomputes EVERY number the page
// shows, from the Powers hydration model, and checks self-consistency — where
// possible two independent ways. Exits 0 iff all checks pass.
//
//   Model (all sourced — see README.md):
//     non-evaporable (chemically bound) water   WN   = 0.23 g/g cement
//     gel water                                 WG   = 0.19 g/g cement
//     full-hydration water demand               WFULL= WN + WG = 0.42  (→ w/c ≈ 0.42)
//     water-limited ultimate hydration          α_max= min(1, w/c / 0.42)
//     Powers gel-space ratio                    r    = 0.68·α / (0.32·α + w/c)
//     Powers paste strength                     fc   = 234·r³  MPa   (34,000·r³ psi)
//     maturity degree of hydration              α(t) = α_max·exp(−(τ/t_eff)^β)
//       kept-wet:  t_eff = t
//       air-dried: t_eff = t for t≤TDRY, else TDRY + (t−TDRY)·SDRY   (hydration ~freezes)
//
// These constants and formulas mirror the inline <script> in index.html exactly.

const WN = 0.23, WG = 0.19, WFULL = WN + WG;   // 0.42
const STR_A = 234;                             // MPa
const TAU = 0.6, BETA = 0.42, TDRY = 3, SDRY = 0.05;

const alphaMax = wc => Math.min(1, wc / WFULL);
const shape = t => Math.exp(-Math.pow(TAU / t, BETA));
const tEffAir = t => (t <= TDRY ? t : TDRY + (t - TDRY) * SDRY);
const alphaWet = (wc, t) => alphaMax(wc) * shape(t);
const alphaAir = (wc, t) => alphaMax(wc) * shape(tEffAir(t));
const gelSpace = (wc, a) => 0.68 * a / (0.32 * a + wc);
const strength = (wc, a) => STR_A * Math.pow(gelSpace(wc, a), 3);
function waterFate(wc) {
  const a = alphaMax(wc);
  const bound = WN * a / wc, gel = WG * a / wc;
  return { alphaMax: a, bound, gel, free: Math.max(0, 1 - bound - gel) };
}

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('── Powers hydration model — does-concrete-dry ──\n');

// 1) Full-hydration water demand: WN + WG = 0.42 (two independent facts summed).
check('bound (0.23) + gel (0.19) = full-hydration w/c 0.42',
  approx(WFULL, 0.42), `WFULL = ${WFULL.toFixed(2)}`);

// 2) Chemically-bound water is ~0.23 g/g == ~23% by mass of cement.
check('chemically-bound water ≈ 0.23 g/g ≈ 23% by mass',
  approx(WN, 0.23) && approx(WN * 100, 23), `${(WN * 100).toFixed(0)}%`);

// 3) At w/c = 0.42 the system fully hydrates (α_max = 1) and NO free water remains
//    (bound + gel = 1 exactly). This is the "ideal" point.
{
  const w = waterFate(0.42);
  check('w/c = 0.42 → α_max = 1 and free water ≈ 0',
    approx(w.alphaMax, 1) && w.free < 5e-3,
    `α_max=${w.alphaMax.toFixed(3)}, free=${w.free.toFixed(4)}`);
}

// 4) Water bookkeeping sums to 1 for a spread of w/c (fractions of mix water).
{
  let ok = true, worst = 0;
  for (let wc = 0.30; wc <= 0.70 + 1e-9; wc += 0.01) {
    const w = waterFate(wc);
    const s = w.bound + w.gel + w.free;
    worst = Math.max(worst, Math.abs(s - 1));
    if (Math.abs(s - 1) > 1e-9) ok = false;
  }
  check('bound + gel + free = 1 for all w/c in [0.30, 0.70]', ok,
    `max |Σ−1| = ${worst.toExponential(1)}`);
}

// 5) Bound-water fraction, two independent ways, for a fully-hydrated mix (w/c ≥ 0.42):
//    (a) direct 0.23/(w/c);  (b) from waterFate().bound with α_max = 1.
{
  let ok = true;
  for (const wc of [0.42, 0.50, 0.60, 0.70]) {
    const direct = 0.23 / wc;             // method A
    const model = waterFate(wc).bound;    // method B
    if (!approx(direct, model)) ok = false;
  }
  check('bound fraction = 0.23/(w/c) matches waterFate() [two methods]', ok);
}

// 6) Below w/c = 0.42 the cement CANNOT fully hydrate: α_max = w/c/0.42 < 1,
//    independent of curing (self-desiccation). Check the water-limit two ways.
{
  const wc = 0.35;
  const direct = wc / 0.42;
  check('w/c = 0.35 caps hydration at w/c/0.42 < 1',
    approx(alphaMax(wc), direct) && alphaMax(wc) < 1,
    `α_max=${alphaMax(wc).toFixed(3)}`);
}

// 7) Powers strength law reproduces a textbook point: r = 0.657 → fc ≈ 234·0.657³.
//    (Independent hand-computation of the cube.)
{
  const r = 0.657;
  const fc = STR_A * r * r * r;
  const hand = 234 * 0.283593; // 0.657^3 computed offline
  check('Powers fc = 234·r³ reproduces textbook r=0.657 point',
    Math.abs(fc - hand) < 0.5, `fc=${fc.toFixed(1)} MPa`);
}

// 8) THE REVERSAL: kept-wet ≥ air-dried at EVERY age (strength is monotone in α,
//    and α_wet ≥ α_air always). "Reaction beats drying."
{
  let ok = true;
  for (let t = T_MIN(); t <= 365; t *= 1.25) {
    if (strength(0.45, alphaWet(0.45, t)) < strength(0.45, alphaAir(0.45, t)) - 1e-9) ok = false;
  }
  function _(){} // (keep lint calm)
  check('kept-wet ≥ air-dried at all ages (the opposite of "drying")', ok);
}
function T_MIN(){ return 1; }

// 9) The overtake is strict by 1 year, across the whole w/c range.
{
  let ok = true, egW = 0, egA = 0;
  for (let wc = 0.30; wc <= 0.70 + 1e-9; wc += 0.05) {
    const fW = strength(wc, alphaWet(wc, 365));
    const fA = strength(wc, alphaAir(wc, 365));
    if (!(fW > fA + 1e-6)) ok = false;
    if (Math.abs(wc - 0.45) < 1e-9) { egW = fW; egA = fA; }
  }
  check('kept-wet strictly stronger than air-dried by 1 yr (all w/c)', ok,
    `@w/c 0.45: ${egW.toFixed(1)} > ${egA.toFixed(1)} MPa`);
}

// 10) 28 days is NOT the endpoint: kept-wet strength keeps rising 28 d → 1 yr.
{
  let ok = true;
  for (let wc = 0.30; wc <= 0.70 + 1e-9; wc += 0.05) {
    if (!(strength(wc, alphaWet(wc, 365)) > strength(wc, alphaWet(wc, 28)) + 1e-6)) ok = false;
  }
  const f28 = strength(0.45, alphaWet(0.45, 28)), f365 = strength(0.45, alphaWet(0.45, 365));
  check('kept-wet keeps gaining strength after 28 days', ok,
    `@0.45: 28d ${f28.toFixed(1)} → 1yr ${f365.toFixed(1)} MPa`);
}

// 11) More water is NOT better: at full hydration, higher w/c gives LOWER strength
//     (monotone decreasing in w/c for α = 1).
{
  let ok = true, prev = Infinity;
  for (let wc = 0.42; wc <= 0.70 + 1e-9; wc += 0.02) {
    const f = strength(wc, 1);
    if (f > prev + 1e-9) ok = false;
    prev = f;
  }
  check('higher w/c ⇒ weaker (fully hydrated fc decreasing in w/c)', ok,
    `fc(0.42)=${strength(0.42,1).toFixed(0)} > fc(0.70)=${strength(0.70,1).toFixed(0)} MPa`);
}

// 12) Cross-check the 28-day readout numbers the page prints for the default w/c=0.45.
{
  const wc = 0.45;
  const aW = alphaWet(wc, 28), aA = alphaAir(wc, 28);
  const fW = strength(wc, aW), fA = strength(wc, aA);
  const gap = (1 - fA / fW) * 100;
  console.log(`      [default w/c=0.45] kept-wet 28d: α=${aW.toFixed(2)} fc=${fW.toFixed(1)} MPa;` +
              ` air-dried 28d: α=${aA.toFixed(2)} fc=${fA.toFixed(1)} MPa; penalty −${gap.toFixed(0)}%`);
  check('default-mix readouts are finite, positive, and wet > air',
    fW > 0 && fA > 0 && fW > fA && gap > 0);
}

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