#!/usr/bin/env node
// verify-how-far-away-is-the-lightning.mjs
//
// Offline gate for /strata/how-far-away-is-the-lightning/. It recomputes EVERY number the
// page shows, from nothing but the speed of sound c(T) and unit conversions, and exits 0
// only if all checks pass. Where possible each fact is verified two independent ways.
//
// The physics:
//   speed of sound (linear)          c = 331.3 + 0.606*T                 (m/s, T in C)
//   speed of sound (Newton-Laplace)  c = 331.3*sqrt(1 + T/273.15)        (m/s, T in C)
//   the mental rule                  d = seconds / 5 (mi)  or  / 3 (km)
//   the exact physics                d = seconds * c(T),  / 1609.344 (mi) or / 1000 (km)
//   implied speed of the "/5" rule   c = 1609.344 / 5 = 321.9 m/s
//   light lag over 10 miles          16093.44 / 2.998e8 = 5.37e-5 s  (treated as instant)
//
// Run:  node research/how-far-away-is-the-lightning/verify-how-far-away-is-the-lightning.mjs

'use strict';

// ---- constants (identical to the page's inline JS) --------------------------------
const MI = 1609.344;      // m, exact international mile
const KM = 1000;          // m
const C_LIGHT = 2.998e8;  // m/s
const T0K = 273.15;       // 0 C in kelvin

const cLinear = (T) => 331.3 + 0.606 * T;
const cNL = (T) => 331.3 * Math.sqrt(1 + T / T0K);
const cOf = (T) => cNL(T);                       // primary exact physics: 343.2 at 20 C
const secPerMile = (T) => MI / cOf(T);
const secPerKm = (T) => KM / cOf(T);

// ---- test harness -----------------------------------------------------------------
let pass = 0, fail = 0;
const approx = (a, b, tol = 1e-6) => Math.abs(a - b) <= tol * Math.max(1, Math.abs(b));
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  PASS  ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${detail ? '  ' + detail : ''}`); }
}

console.log('how-far-away-is-the-lightning :: offline verifier');
console.log(`constants: 1 mile = ${MI} m ; c(20C) = ${cOf(20).toFixed(3)} m/s ; light = ${C_LIGHT} m/s`);
console.log('');

// [1] speed of sound at 20 C, two independent models
console.log('[1] speed of sound c(20 C), two models');
{
  check('linear 331.3 + 0.606*20 = 343.42 m/s', approx(cLinear(20), 343.42, 1e-4),
        `= ${cLinear(20).toFixed(4)} m/s`);
  check('Newton-Laplace 331.3*sqrt(1+20/273.15) = 343.21 m/s', approx(cNL(20), 343.2146, 1e-4),
        `= ${cNL(20).toFixed(4)} m/s`);
  check('both within 0.5 m/s of 343', Math.abs(cLinear(20) - 343) < 0.5 && Math.abs(cNL(20) - 343) < 0.5);
  // independent cross-check: 0.606 is the derivative of Newton-Laplace at 0 C
  const slope0 = 331.3 / (2 * T0K);
  check('the linear slope 0.606 = d/dT of Newton-Laplace at 0 C', approx(0.606, slope0, 2e-3),
        `NL slope at 0 C = ${slope0.toFixed(4)}`);
  // honest model-agreement tolerance (corrects the spec text "within 0.25 across 0-25 C")
  check('models agree to < 0.25 m/s at 20 C', Math.abs(cLinear(20) - cNL(20)) < 0.25,
        `diff = ${Math.abs(cLinear(20) - cNL(20)).toFixed(3)} m/s`);
  check('models agree to < 0.35 m/s at 25 C', Math.abs(cLinear(25) - cNL(25)) < 0.35,
        `diff = ${Math.abs(cLinear(25) - cNL(25)).toFixed(3)} m/s`);
  check('models diverge to < 1.0 m/s only by 40 C', Math.abs(cLinear(40) - cNL(40)) < 1.0,
        `diff = ${Math.abs(cLinear(40) - cNL(40)).toFixed(3)} m/s`);
}

// [2] seconds per unit at 20 C, two ways (via cOf(20) and via the 343.2 reference)
console.log('\n[2] seconds per unit at 20 C');
{
  check('seconds per mile = 1609.344 / 343.2 = 4.69', approx(secPerMile(20), 4.689, 1e-3),
        `= ${secPerMile(20).toFixed(3)} s/mi`);
  check('  same via the 343.2 reference', approx(MI / 343.2, 4.689, 1e-3),
        `= ${(MI / 343.2).toFixed(3)} s/mi`);
  check('seconds per km = 1000 / 343.2 = 2.91', approx(secPerKm(20), 2.914, 1e-3),
        `= ${secPerKm(20).toFixed(3)} s/km`);
  check('  same via the 343.2 reference', approx(KM / 343.2, 2.914, 1e-3),
        `= ${(KM / 343.2).toFixed(3)} s/km`);
}

// [3] the rounding: what fraction of the true distance each rule returns, and its direction
console.log('\n[3] rounding: fraction of true distance returned by each rule');
{
  const fMi = secPerMile(20) / 5;   // divide-by-5 vs the true seconds-per-mile
  const fKm = secPerKm(20) / 3;     // divide-by-3 vs the true seconds-per-km
  check('divide-by-5 returns 93.8% of true distance (~6.2% short)', approx(fMi, 0.938, 2e-3),
        `= ${(fMi * 100).toFixed(1)}%  (short ${((1 - fMi) * 100).toFixed(1)}%)`);
  check('divide-by-3 returns 97.1% of true distance (~2.9% short)', approx(fKm, 0.971, 2e-3),
        `= ${(fKm * 100).toFixed(1)}%  (short ${((1 - fKm) * 100).toFixed(1)}%)`);
  check('both read SHORT: rule < physics (real distance is larger)', fMi < 1 && fKm < 1);
  check('the km rule is the more faithful of the two', (1 - fKm) < (1 - fMi));
  // independent direction check: at 10 s the rule undercounts the physics distance
  const rulMi = 10 / 5, physMi = 10 * cOf(20) / MI;
  check('at 10 s: rule 2.00 mi < physics 2.13 mi', physMi > rulMi,
        `physics = ${physMi.toFixed(3)} mi`);
}

// [4] the temperature the "divide by 5" rule is secretly calibrated for
console.log('\n[4] implied speed and temperature of the divide-by-5 rule');
{
  const cImplied = MI / 5;
  check('divisor 5 implies c = 1609.344 / 5 = 321.9 m/s', approx(cImplied, 321.9, 1e-3),
        `= ${cImplied.toFixed(2)} m/s`);
  const Tlin = (cImplied - 331.3) / 0.606;
  const Tnl = (Math.pow(cImplied / 331.3, 2) - 1) * T0K;
  check('back-solve linear -> T ~ -15.5 C (within 0.5)', Math.abs(Tlin + 15.5) < 0.5,
        `T = ${Tlin.toFixed(2)} C`);
  check('back-solve Newton-Laplace -> T ~ -15.5 C (within 0.5)', Math.abs(Tnl + 15.5) < 0.5,
        `T = ${Tnl.toFixed(2)} C`);
  check('the two back-solves agree within 0.5 C', Math.abs(Tlin - Tnl) < 0.5,
        `${Tlin.toFixed(2)} vs ${Tnl.toFixed(2)} C`);
}

// [5] the reversal: the 0-30 C temperature swing is SMALLER than the rounding gap
console.log('\n[5] REVERSAL: temperature swing (0-30 C) < the rounding gap (5 - 4.69)');
{
  const s0 = secPerMile(0), s30 = secPerMile(30);
  check('seconds per mile at 0 C = 4.86', approx(s0, 4.858, 2e-3), `= ${s0.toFixed(3)} s/mi`);
  check('seconds per mile at 30 C = 4.61', approx(s30, 4.611, 2e-3), `= ${s30.toFixed(3)} s/mi`);
  const swing = s0 - s30;
  const gap = 5 - secPerMile(20);
  check('the 0-30 C swing is ~0.25 s', approx(swing, 0.247, 3e-2), `= ${swing.toFixed(3)} s`);
  check('the rounding gap 5 - 4.69 is ~0.31 s', approx(gap, 0.311, 3e-2), `= ${gap.toFixed(3)} s`);
  check('swing (temperature) STRICTLY SMALLER than gap (rounding)', swing < gap,
        `${swing.toFixed(3)} s < ${gap.toFixed(3)} s`);
  // independent framing: the swing is under 6% of the divisor, the gap is over 6%
  check('temperature effect < rounding error, as fractions of the divisor',
        (swing / 5) < (gap / 5) && (gap / 5) > 0.06);
}

// [6] the NWS worked example reproduced
console.log('\n[6] NWS worked example: 10 s -> 2 miles');
{
  check('10 s / 5 = 2.0 miles exactly', approx(10 / 5, 2, 1e-12));
  check('10 s * 343.2 m/s = 3.43 km (physics)', approx(10 * cOf(20) / 1000, 3.432, 3e-3),
        `= ${(10 * cOf(20) / 1000).toFixed(3)} km`);
  check('10 s / 3 = 3.33 km (the km rule)', approx(10 / 3, 3.333, 1e-3),
        `= ${(10 / 3).toFixed(3)} km`);
}

// [7] the legacy 30-30 numbers
console.log('\n[7] 30-30 legacy heuristic');
{
  check('30 s / 5 = 6.0 miles', approx(30 / 5, 6, 1e-12));
  check('30 s * 343.2 m/s = 10.3 km', approx(30 * cOf(20) / 1000, 10.296, 3e-3),
        `= ${(30 * cOf(20) / 1000).toFixed(3)} km`);
}

// [8] the flash is instantaneous to five significant figures
console.log('\n[8] light lag negligible: flash is effectively instantaneous');
{
  const lag = 10 * MI / C_LIGHT;
  check('light travel time for 10 miles = 5.37e-5 s', approx(lag, 5.368e-5, 1e-3),
        `= ${lag.toExponential(3)} s`);
  // any thunder lag over the same 10 miles is ~47 s; ratio is < 1e-6
  const soundLag = 10 * MI / cOf(20);
  check('light lag is < 1e-4 of the sound lag over the same distance', lag / soundLag < 1e-4,
        `ratio = ${(lag / soundLag).toExponential(2)}`);
}

// ---- [9] the SHIPPED PAGE, not a second copy of the physics ----------------------
//
// Everything above re-derives the physics independently, which establishes the facts and
// says nothing whatever about what the page ships. Added 2026-07-26 after the coupling
// census (research/verifier-independence/) found this check page-blind: it lifts the
// page's own speed-of-sound functions out of the shipped HTML and sweeps them against the
// ones above, so a defect in the page's copy now turns this file red.
console.log('\n[9] the shipped page, lifted and swept against this file');
{
  const { readFileSync } = await import('node:fs');
  const { fileURLToPath } = await import('node:url');
  const PAGE = fileURLToPath(new URL('../../public/strata/how-far-away-is-the-lightning/index.html',
    import.meta.url));
  const html = readFileSync(PAGE, 'utf8');

  const grab = (marker) => {
    const at = html.indexOf(marker);
    if (at < 0) return null;
    const open = html.indexOf('{', at + marker.length - 1);
    let depth = 0;
    for (let i = open; i < html.length; i++) {
      if (html[i] === '{') depth++;
      else if (html[i] === '}') { depth--; if (depth === 0) return html.slice(at, i + 1); }
    }
    return null;
  };
  const parts = ['var T0K', 'function cLinear(T)', 'function cNL(T)']
    .map((m) => (m.startsWith('var') ? (html.match(/var T0K\s*=\s*[\d.]+\s*;/) || [null])[0] : grab(m)));
  check('page declares T0K, cLinear and cNL', parts.every(Boolean));

  if (parts.every(Boolean)) {
    const pageCode = new Function(parts.join('\n') + '\n; return { cLinear, cNL };')();
    let worstLin = 0, worstNL = 0;
    for (let T = -40; T <= 50; T += 0.25) {
      worstLin = Math.max(worstLin, Math.abs(pageCode.cLinear(T) - cLinear(T)));
      worstNL = Math.max(worstNL, Math.abs(pageCode.cNL(T) - cNL(T)));
    }
    check('page cLinear matches this file over -40..50 C', worstLin < 1e-12,
          `worst gap ${worstLin.toExponential(2)} m/s`);
    check('page cNL matches this file over -40..50 C', worstNL < 1e-12,
          `worst gap ${worstNL.toExponential(2)} m/s`);
  }

  // And the numbers the page prints in prose, which no lifted function covers.
  check('page prints 343.2 m/s for cNL at 20 C', html.includes('343.2 m/s')
        && approx(cNL(20), 343.2, 1e-4));
  // The page prints these to two decimals, so the assertion is on the printed
  // form, not on a tolerance around it. 1000/343.2 is 2.9138, and demanding it
  // sit within 1e-3 of 2.91 fails for the honest reason that the page rounded.
  check('page prints 1609.344 / 343.2 = 4.69 s per mile', html.includes('1609.344 / 343.2 = 4.69 s')
        && (MI / 343.2).toFixed(2) === '4.69', `computed ${(MI / 343.2).toFixed(4)} s`);
  check('page prints 1000 / 343.2 = 2.91 s per kilometre', html.includes('1000 / 343.2 = 2.91 s')
        && (KM / 343.2).toFixed(2) === '2.91', `computed ${(KM / 343.2).toFixed(4)} s`);
}

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