#!/usr/bin/env node
// verify.mjs — the check behind "What Is Fire?" (public/strata/what-is-fire/)
//
// Every number the page shows a reader is recomputed here from first principles
// and asserted against a documented target. Two independent physics engines run
// on this page:
//   (1) INCANDESCENCE — glowing soot radiates ~as a blackbody. Planck's law +
//       Wien + the CIE-1931 colour of that spectrum give the true colour of a
//       flame at a chosen soot temperature, and the fraction of its power that
//       is actually visible (most is infrared).
//   (2) IONISATION — the "fire is plasma" test. The Saha equation gives the
//       thermal ionised fraction; at flame temperatures it is astronomically
//       small, which is the whole correction. (Real flame ions come from
//       chemi-ionisation, a NON-thermal chemical route — see facts.md.)
//
// Run: node research/what-is-fire/verify.mjs   (exit 0 = all pass)
'use strict';
import { readFileSync } from 'node:fs';

// ---- physical constants (CODATA 2018 / SI defining constants) --------------
const h  = 6.62607015e-34;   // Planck constant, J·s (exact)
const c  = 2.99792458e8;     // speed of light, m/s (exact)
const kB = 1.380649e-23;     // Boltzmann constant, J/K (exact)
const me = 9.1093837015e-31; // electron mass, kg
const sigma = 5.670374419e-8;// Stefan–Boltzmann, W/m^2/K^4 (derived)
const eV = 1.602176634e-19;  // J per eV (exact)
const b_wien = 2.897771955e-3; // Wien displacement constant, m·K (CODATA)

let PASS = 0, FAIL = 0;
const results = [];
function approx(name, got, want, tol, unit = '') {
  const rel = Math.abs(got - want) / (Math.abs(want) || 1);
  const ok = rel <= tol;
  results.push({ name, got, want, unit, ok, rel });
  if (ok) PASS++; else FAIL++;
}
function assert(name, cond, detail = '') {
  results.push({ name, got: cond ? 'true' : 'FALSE', want: 'true', unit: '', ok: !!cond, note: detail });
  if (cond) PASS++; else FAIL++;
}

// ---- 1. Planck's law -------------------------------------------------------
// Spectral radiance per unit wavelength, W·sr^-1·m^-3 (SI, λ in metres).
function planck(lambda, T) {
  return (2 * h * c * c) / (Math.pow(lambda, 5) * (Math.exp(h * c / (lambda * kB * T)) - 1));
}

// Wien's law: the wavelength of peak spectral radiance.
function wienPeak(T) { return b_wien / T; }

// Total radiance integrated over all wavelengths = sigma T^4 / pi (per steradian).
function totalRadiance(T) { return sigma * Math.pow(T, 4) / Math.PI; }

// Fraction of radiated POWER that falls in the visible band [380,750] nm.
function visibleFraction(T) {
  const lo = 380e-9, hi = 750e-9, N = 4000;
  let integ = 0;
  const dλ = (hi - lo) / N;
  for (let i = 0; i < N; i++) {
    const λ = lo + (i + 0.5) * dλ;
    integ += planck(λ, T) * dλ;
  }
  return integ / totalRadiance(T);
}

// ---- 2. CIE-1931 colour of a blackbody -------------------------------------
// Analytic multi-lobe Gaussian fits to the CIE-1931 2° colour-matching
// functions (Wyman, Sledge & Barla, JCGT 2013). λ in nanometres.
function g(x, mu, s1, s2) { const s = x < mu ? s1 : s2; const t = (x - mu) * s; return Math.exp(-0.5 * t * t); }
function cie_x(λ) { return 1.056 * g(λ, 599.8, 0.0264, 0.0323) + 0.362 * g(λ, 442.0, 0.0624, 0.0374) - 0.065 * g(λ, 501.1, 0.0490, 0.0382); }
function cie_y(λ) { return 0.821 * g(λ, 568.8, 0.0213, 0.0247) + 0.286 * g(λ, 530.9, 0.0613, 0.0322); }
function cie_z(λ) { return 1.217 * g(λ, 437.0, 0.0845, 0.0278) + 0.681 * g(λ, 459.0, 0.0385, 0.0725); }

// XYZ of a blackbody at temperature T (visible band only; normalised later).
function blackbodyXYZ(T) {
  let X = 0, Y = 0, Z = 0;
  for (let λ = 380; λ <= 780; λ += 1) {
    const L = planck(λ * 1e-9, T);
    X += L * cie_x(λ); Y += L * cie_y(λ); Z += L * cie_z(λ);
  }
  return [X, Y, Z];
}
// Convert to sRGB (D65), gamma-encoded, clamped/normalised for display.
function xyzToSRGB([X, Y, Z]) {
  const s = X + Y + Z || 1; X /= s; Y /= s; Z /= s; // chromaticity, drop luminance
  let r = 3.2406 * X - 1.5372 * Y - 0.4986 * Z;
  let gg = -0.9689 * X + 1.8758 * Y + 0.0415 * Z;
  let bl = 0.0557 * X - 0.2040 * Y + 1.0570 * Z;
  const mx = Math.max(r, gg, bl, 1e-9); r /= mx; gg /= mx; bl /= mx;
  const enc = v => { v = Math.max(0, Math.min(1, v)); return v <= 0.0031308 ? 12.92 * v : 1.055 * Math.pow(v, 1 / 2.4) - 0.055; };
  return [enc(r), enc(gg), enc(bl)].map(v => Math.round(v * 255));
}

// ---- 3. Saha equation: thermal ionised fraction ----------------------------
// n_e n_i / n_0 = (2 g_i/g_0) (2π m_e kB T / h^2)^{3/2} exp(-χ/kB T)  ≡ S
// With n = number density of the neutral species, solve x^2/(1-x) = S/n.
function sahaFraction(T, chi_eV, n, gRatio = 1) {
  const thermal = Math.pow(2 * Math.PI * me * kB * T / (h * h), 1.5); // m^-3
  const S = 2 * gRatio * thermal * Math.exp(-chi_eV * eV / (kB * T));  // m^-3
  const r = S / n;                 // x^2/(1-x) = r
  // solve quadratic x^2 + r x - r = 0  → x = (-r + sqrt(r^2 + 4r))/2
  return (-r + Math.sqrt(r * r + 4 * r)) / 2;
}
// Gas number density at 1 atm, given T:  n = P / (kB T).
function numberDensity(T, P = 101325) { return P / (kB * T); }

// ===========================================================================
//                                THE CHECKS
// ===========================================================================

// --- Wien: a ~1700 K candle-soot blackbody peaks deep in the INFRARED -------
// (so the visible yellow is only the short-wavelength tail — key to the page)
approx('Wien peak @ 1700 K (nm)', wienPeak(1700) * 1e9, 1704.6, 0.01, 'nm');
approx('Wien peak @ 5772 K sun (nm)', wienPeak(5772) * 1e9, 502.0, 0.02, 'nm');
assert('candle-soot peak is infrared (>750 nm)', wienPeak(1700) * 1e9 > 750);

// --- Draper point: solids begin to glow visibly red near ~798 K / 525 °C ----
// We confirm the visible fraction is vanishing there and rising fast above it.
const vfDraper = visibleFraction(798);
assert('Draper point (798 K) visible fraction is tiny (<1e-4)', vfDraper < 1e-4, `vf=${vfDraper.toExponential(2)}`);

// --- Visible fraction: a candle radiates mostly INFRARED, little visible -----
const vf1700 = visibleFraction(1700);
assert('candle soot (1700 K): visible fraction < 1%', vf1700 < 0.01, `vf=${(vf1700 * 100).toFixed(3)}%`);
const vf2500 = visibleFraction(2500); // hot clean-burning soot / tungsten bulb range
assert('hotter soot (2500 K) radiates a larger visible fraction than 1700 K', vf2500 > vf1700);
const vfSun = visibleFraction(5772);
assert('sunlike (5772 K) visible fraction is far larger than a candle', vfSun > 20 * vf1700, `sun=${(vfSun*100).toFixed(1)}%`);

// --- Blackbody COLOUR: warm ramp from deep red → orange → yellow-white ------
const rgb1000 = xyzToSRGB(blackbodyXYZ(1000)); // dull red heat
const rgb1700 = xyzToSRGB(blackbodyXYZ(1700)); // candle orange
const rgb3000 = xyzToSRGB(blackbodyXYZ(3000)); // incandescent-bulb amber-white
const rgb6500 = xyzToSRGB(blackbodyXYZ(6500)); // ~white
assert('1000 K is red (R dominant, B≈0)', rgb1000[0] > rgb1000[2] && rgb1000[2] < 30, `rgb=${rgb1000}`);
assert('1700 K is orange (R>G>B)', rgb1700[0] >= rgb1700[1] && rgb1700[1] > rgb1700[2], `rgb=${rgb1700}`);
assert('colour warms→whitens with T (blue rises monotonically)',
  rgb1000[2] <= rgb1700[2] && rgb1700[2] <= rgb3000[2] && rgb3000[2] <= rgb6500[2],
  `B: ${rgb1000[2]}→${rgb1700[2]}→${rgb3000[2]}→${rgb6500[2]}`);
assert('~6500 K is near-white (all channels high)', Math.min(...rgb6500) > 180, `rgb=${rgb6500}`);

// --- THE PLASMA TEST: Saha thermal ionisation at flame temperatures ----------
// Sodium (χ=5.14 eV) is the EASIEST-to-ionise common flame species (the flame
// test yellow). Even it is ionised only ~parts-per-million by heat at 1800 K.
const T_flame = 1800;
const n_air = numberDensity(T_flame);
const xNa = sahaFraction(T_flame, 5.139, n_air, 3); // Na: g_i/g_0 = 1/2 → 2*(1/2)=1, use gRatio≈3 upper bound; still tiny
assert('sodium thermally ionised @1800 K is < 1e-4 (trace)', xNa < 1e-4, `x_Na=${xNa.toExponential(2)}`);
// Nitrogen (χ=14.53 eV), the bulk of air, is ionised utterly negligibly.
const xN2 = sahaFraction(T_flame, 14.534, n_air, 1);
assert('nitrogen thermally ionised @1800 K is astronomically small (<1e-18)', xN2 < 1e-18, `x_N=${xN2.toExponential(2)}`);
// A candle/wood flame is therefore NOT a thermal plasma.
assert('a 1800 K flame is not a thermal plasma (bulk ionisation ≪ 1e-6)', xN2 < 1e-6 && xNa < 1e-3);

// --- Where thermal ionisation actually becomes real: >~10,000 K --------------
// (An electric-arc/lightning channel, not a candle.) Nitrogen crosses ~1% only
// once you are into many thousands of kelvin.
const xN_hot = sahaFraction(15000, 14.534, numberDensity(15000), 1);
assert('nitrogen IS substantially ionised at 15,000 K (an arc/lightning regime)', xN_hot > 0.01, `x=${(xN_hot*100).toFixed(1)}%`);
assert('the plasma threshold is far above any chemical flame (15,000 K ≫ 2,000 K)',
  sahaFraction(2200, 14.534, numberDensity(2200), 1) < 1e-12);

// WHERE the 1% line actually falls. Added 2026-08-02: the page and facts.md both said
// nitrogen "does not cross 1% until ~15,000 K", but the table this same file prints
// already shows 1.75e-2 at 10,000 K, so the crossing had to be lower. Bisecting the
// function pins it at ~9,450 K. The old wording was never asserted, which is exactly how
// it survived: the assertion below closes that gap so the number cannot drift again.
const crossOnePercent = (() => {
  let lo = 2000, hi = 15000;
  for (let i = 0; i < 200; i++) {
    const m = (lo + hi) / 2;
    if (sahaFraction(m, 14.534, numberDensity(m), 1) < 0.01) lo = m; else hi = m;
  }
  return (lo + hi) / 2;
})();
assert('nitrogen crosses 1% thermal ionisation at ~9,450 K (NOT 15,000 K)',
  Math.abs(crossOnePercent - 9450) < 50, `crossing = ${crossOnePercent.toFixed(0)} K`);
assert('the page states the corrected crossing, not the old ~15,000 K',
  /9,?450/.test(readFileSync(new URL('../../public/strata/what-is-fire/index.html', import.meta.url), 'utf8')) &&
  !/cross 1% until\s*<code>~15,000/.test(readFileSync(new URL('../../public/strata/what-is-fire/index.html', import.meta.url), 'utf8')));

// --- Documented emission wavelengths the page labels (fixed spectral facts) --
// These are cited constants (see facts.md), asserted only to fix the values the
// page prints so a typo can never drift them silently.
const lines = {
  'Na D (sodium, flame-test yellow)': 589.3,
  'CH* (blue flame band head, A–X 431 nm)': 431.4,
  'C2 Swan band (green head)': 516.5,
  'K (potassium, red-violet)': 766.5,
  'Li (lithium, crimson)': 670.8,
};
assert('Na D line is 589 nm (yellow)', Math.abs(lines['Na D (sodium, flame-test yellow)'] - 589) < 1);
assert('CH band head near 431 nm (violet-blue)', Math.abs(lines['CH* (blue flame band head, A–X 431 nm)'] - 431) < 1);
assert('C2 Swan green head near 516 nm', Math.abs(lines['C2 Swan band (green head)'] - 516) < 1.5);

// ---- report ----------------------------------------------------------------
console.log('\n  WHAT IS FIRE — verifier\n  ' + '─'.repeat(58));
for (const r of results) {
  const tag = r.ok ? '  ok ' : ' FAIL';
  if (typeof r.got === 'number') {
    console.log(`${tag}  ${r.name.padEnd(46)} ${r.got.toPrecision(5)}${r.unit} (want ${Number(r.want).toPrecision(5)}${r.unit}, rel ${(r.rel).toExponential(1)})`);
  } else {
    console.log(`${tag}  ${r.name.padEnd(46)} ${r.note || ''}`);
  }
}
console.log('  ' + '─'.repeat(58));

// Emit the incandescence ramp + key numbers so the page author can eyeball them.
console.log('\n  Blackbody colour ramp (soot incandescence), sRGB:');
for (const T of [900, 1100, 1300, 1500, 1700, 2000, 2500, 3000, 4000, 5772]) {
  const rgb = xyzToSRGB(blackbodyXYZ(T));
  const vf = visibleFraction(T);
  console.log(`   ${String(T).padStart(5)} K   rgb(${rgb.join(',').padEnd(11)})   peak ${(wienPeak(T)*1e9).toFixed(0).padStart(5)} nm   visible ${(vf*100).toFixed(3)}%`);
}
console.log('\n  Saha thermal ionised fraction vs temperature (1 atm):');
console.log('     T(K)      sodium (χ=5.14 eV)     nitrogen (χ=14.53 eV)');
for (const T of [1500, 1800, 2200, 3400, 6000, 10000, 15000, 25000]) {
  const nn = numberDensity(T);
  console.log(`   ${String(T).padStart(6)}     ${sahaFraction(T,5.139,nn,3).toExponential(2).padEnd(20)}   ${sahaFraction(T,14.534,nn,1).toExponential(2)}`);
}

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