#!/usr/bin/env node
// What makes fireworks different colours — offline verifier.
//
// THE CLAIM UNDER TEST. A firework's colour is atomic/molecular EMISSION: heat a
// metal salt and its electrons fall back down fixed energy steps, emitting light
// at fixed wavelengths. The colour you see is what the human eye makes of that
// specific set of wavelengths. So the colour is not a free choice — it is
// DETERMINED by the emission spectrum and the CIE standard observer.
//
// We check this without hand-waving:
//   1. The CMF approximation (Wyman 2013) behaves: each colour-matching function peaks where it
//      should, and pure monochromatic light sweeps hue red->...->violet in order.
//   2. Every emitter's colour, COMPUTED from its real emission wavelengths, lands
//      in the qualitative colour bin the chemistry predicts (Na yellow, Sr red,
//      Ba green, Cu blue, ...). The colour is derived, never declared.
//   3. The illustrative temperature model: copper's intensity factor and Y fall,
//      its normalised RGB stays fixed, and strontium is held constant. This is a
//      model check, not evidence of a real decomposition temperature.
//   4. The cited wavelengths are internally consistent with their named colours
//      (each feature's own hue matches the family it's filed under, lines vs bands).
//
// The page imports the SAME spectra.mjs, so this proves the on-screen colour too.
//   node research/fireworks-colors/verify.mjs

import {
  cieX, cieY, cieZ, xyzToSRGB, spectrumToXYZ,
  EMITTERS, emitterColor, survivalFraction, hueName,
} from '../../public/strata/fireworks-colors/spectra.mjs';

let pass = 0, fail = 0;
const ok = (name, cond, extra = '') => {
  if (cond) { pass++; console.log(`  ok    ${name}${extra ? '   ' + extra : ''}`); }
  else { fail++; console.log(`FAIL    ${name}${extra ? '   ' + extra : ''}`); }
};

console.log('\n— 1. the CIE colour-matching functions behave —');
// y-bar peaks near 555 nm (peak photopic sensitivity), z-bar in the blue (~445),
// x-bar has its main lobe in the red (~600). Find each peak by a coarse sweep.
function peak(fn) {
  let best = -Infinity, at = 0;
  for (let l = 380; l <= 720; l += 0.5) { const v = fn(l); if (v > best) { best = v; at = l; } }
  return at;
}
ok('y-bar (luminous efficiency) peaks ~555 nm', Math.abs(peak(cieY) - 555) < 12, `${peak(cieY)} nm`);
ok('z-bar (XYZ Z function) peaks ~445 nm',           Math.abs(peak(cieZ) - 445) < 12, `${peak(cieZ)} nm`);
ok('x-bar main lobe in the red ~595 nm',        Math.abs(peak(cieX) - 595) < 15, `${peak(cieX)} nm`);

// A pure-wavelength sweep should walk hue in spectral order.
const sweep = [450, 490, 530, 580, 605, 660].map((nm) => hueName(xyzToSRGB(spectrumToXYZ([{ nm, w: 1 }]))));
console.log('    monochromatic sweep 450->660 nm ->', sweep.join(' '));
ok('450 nm reads blue/violet', ['blue', 'violet'].includes(sweep[0]), sweep[0]);
ok('530 nm reads green',       sweep[2] === 'green', sweep[2]);
ok('580 nm reads yellow',      ['yellow', 'orange'].includes(sweep[3]), sweep[3]);
ok('660 nm reads red',         sweep[5] === 'red', sweep[5]);

console.log('\n— 2. every emitter colour is DERIVED and lands in its predicted bin —');
const expect = {
  sodium: ['yellow', 'orange'], lithium: ['red'], strontium: ['red', 'orange'],
  calcium: ['orange', 'red'], barium: ['green'], copper: ['blue', 'cyan', 'violet'],
  potassium: ['violet', 'blue', 'magenta'],
};
for (const e of EMITTERS) {
  // Evaluate at the model reference temperature of 1000 °C.
  const { rgb } = emitterColor(e, 1000);
  const h = hueName(rgb);
  ok(`${e.name.padEnd(10)} -> rgb(${rgb.join(',')}) reads ${h}`,
     expect[e.id].includes(h), `expected ${expect[e.id].join('/')}`);
}

console.log('\n3. illustrative copper fall-off; strontium held constant');
const cu = EMITTERS.find((e) => e.id === 'copper');
const sr = EMITTERS.find((e) => e.id === 'strontium');
const survCold = survivalFraction(cu, 1000);
const survHot  = survivalFraction(cu, 1800);   // Chosen hot model sample
ok('copper model intensity factor is 1 at 1000 °C', survCold > 0.99, survCold.toFixed(3));
ok('copper model intensity factor falls below 0.02 at 1800 °C',           survHot  < 0.02, survHot.toFixed(3));
// Model luminance Y falls for copper; strontium is held constant.
const lum = (e, T) => spectrumToXYZ(e.features.map((f) => ({ nm: f.nm, w: f.w * survivalFraction(e, T) }))).Y;
const cuDrop = lum(cu, 1800) / lum(cu, 1000);
const srHold = lum(sr, 1800) / lum(sr, 1000);   // No strontium temperature response is modelled.
ok('copper model luminance falls below 3% at 1800 °C', cuDrop < 0.03, `${(cuDrop * 100).toFixed(1)}%`);
ok('strontium model luminance unchanged at 1800 °C',     Math.abs(srHold - 1) < 1e-9, `${(srHold * 100).toFixed(0)}%`);
// Compare both temperatures: normalisation preserves RGB as intensity falls.
const coldCuRGB = emitterColor(cu, 1000).rgb;
const hotCuRGB = emitterColor(cu, 1800).rgb;
ok('copper RGB stays unchanged from 1000 to 1800 °C',
   coldCuRGB.every((v, i) => v === hotCuRGB[i]),
   `cold ${coldCuRGB.join(',')} (${hueName(coldCuRGB)}); hot ${hotCuRGB.join(',')} (${hueName(hotCuRGB)})`);

console.log('\n— 4. cited wavelengths are internally consistent —');
const visBands = { red: [600, 700], orange: [585, 625], green: [495, 570], blue: [420, 470], yellow: [570, 600], violet: [380, 450] };
for (const e of EMITTERS) {
  const vis = e.features.filter((f) => f.w > 0 && !f.omitted);
  // each visible feature's wavelength should sit inside the band named for the family
  const target = e.named;
  const inBand = vis.every((f) => f.nm >= visBands[target][0] - 25 && f.nm <= visBands[target][1] + 25);
  ok(`${e.name.padEnd(10)} features all near its "${target}" region`, inBand,
     vis.map((f) => f.nm).join(', ') + ' nm');
}
// the sodium D-line is the canonical 588.995 / 589.592 nm doublet
const na = EMITTERS.find((e) => e.id === 'sodium');
ok('sodium D-line doublet within 0.1 nm of NIST 588.995/589.592',
   Math.abs(na.features[0].nm - 588.995) < 0.1 && Math.abs(na.features[1].nm - 589.592) < 0.1);
// The simplified potassium model explicitly omits the far-red contribution.
const k = EMITTERS.find((e) => e.id === 'potassium');
ok('potassium far-red lines are explicitly omitted model inputs',
   k.features.filter((f) => f.nm > 700).length === 2 &&
   k.features.filter((f) => f.nm > 700).every((f) => f.w === 0 && f.omitted === true));

console.log(`\n${fail === 0 ? 'ALL PASS' : 'FAILURES'} — ${pass} ok, ${fail} fail\n`);
process.exit(fail === 0 ? 0 : 1);
