#!/usr/bin/env node
// verify.mjs — Why isn't the sky violet?
//
// The claim the stratum settles, recomputed from first principles:
//
//   Rayleigh scattering goes as λ^-4, so the SHORTEST visible wavelengths
//   (violet) are scattered most strongly. Naively, the sky "should" be violet.
//   It is blue. The resolution is that a perceived COLOUR is not the brightest
//   wavelength — it is the integral of the whole spectrum against the eye's
//   three colour-matching functions. That integral, for the Rayleigh-scattered
//   solar spectrum, lands in the BLUE, not the violet.
//
// We recompute, in front of the reader:
//   (A) the Rayleigh-scattered solar spectrum is brightest at the violet end;
//   (B) its perceived colour (CIE 1931) is blue — dominant wavelength ~478 nm,
//       a long way from violet (~410 nm);
//   (C) the colour machinery itself is honest — feeding it an equal-energy
//       (flat) spectrum returns white at (1/3, 1/3) to 3 decimals, the known
//       invariant; feeding it a 6500 K blackbody returns ~D65. We validate the
//       instrument before we trust its verdict on the sky.
//
// HONESTY / SOURCES:
//   * Colour-matching functions: the published compact analytic fit of
//     Wyman, Sloan & Shirley, "Simple Analytic Approximations to the CIE XYZ
//     Colour Matching Functions," JCGT 2(2):1-11 (2013). This is an
//     APPROXIMATION to the true CIE 1931 2-deg tables (max error a few percent);
//     check (C) bounds its bias. The blue-not-violet conclusion is robust to
//     that error by a wide margin (the colour sits ~70 nm from violet).
//   * Solar source: a 5778 K Planck blackbody, the standard textbook
//     approximation to the solar spectrum. Real solar irradiance + atmospheric
//     ozone (Chappuis) absorption shift the result slightly but do not move it
//     out of the blue — see Smith, "Human color vision and the unsaturated blue
//     color of the daytime sky," Am. J. Phys. 73(7):590-597 (2005), whose
//     central finding is exactly that the unsaturated blue is a fact about human
//     colour vision, not just about scattering.
//   * Rayleigh single-scattering ∝ λ^-4 (optically thin clear sky); Strutt
//     (Lord Rayleigh) 1871.

const LAMBDA_MIN = 380, LAMBDA_MAX = 780, STEP = 1; // nm

// --- CIE 1931 2-deg colour-matching functions: Wyman-Sloan-Shirley 2013 fit ---
function gauss(x, mu, s1, s2) {
  const t = (x - mu) * (x < mu ? s1 : s2);
  return Math.exp(-0.5 * t * t);
}
function xbar(l) {
  return 0.362 * gauss(l, 442.0, 0.0624, 0.0374)
       + 1.056 * gauss(l, 599.8, 0.0264, 0.0323)
       - 0.065 * gauss(l, 501.1, 0.0490, 0.0382);
}
function ybar(l) {
  return 0.821 * gauss(l, 568.8, 0.0213, 0.0247)
       + 0.286 * gauss(l, 530.9, 0.0613, 0.0322);
}
function zbar(l) {
  return 1.217 * gauss(l, 437.0, 0.0845, 0.0278)
       + 0.681 * gauss(l, 459.0, 0.0385, 0.0725);
}

// --- Planck spectral radiance (per wavelength), arbitrary scale ---
const H = 6.62607015e-34, C = 2.99792458e8, KB = 1.380649e-23;
function planck(lambda_nm, T) {
  const l = lambda_nm * 1e-9;
  return (1.0 / (l ** 5)) / (Math.exp(H * C / (l * KB * T)) - 1.0);
}

// --- integrate an arbitrary spectral function S(λ) against the CMFs -> XYZ ---
function spectrumToXYZ(S) {
  let X = 0, Y = 0, Z = 0;
  for (let l = LAMBDA_MIN; l <= LAMBDA_MAX; l += STEP) {
    const s = S(l);
    X += s * xbar(l); Y += s * ybar(l); Z += s * zbar(l);
  }
  X *= STEP; Y *= STEP; Z *= STEP;
  return { X, Y, Z };
}
function xy(XYZ) {
  const sum = XYZ.X + XYZ.Y + XYZ.Z;
  return { x: XYZ.X / sum, y: XYZ.Y / sum };
}

// --- dominant wavelength: ray from white point through the sample colour, ---
// --- intersected with the spectral locus (the pure-wavelength boundary) ---
function spectralLocus() {
  const pts = [];
  for (let l = LAMBDA_MIN; l <= LAMBDA_MAX; l += STEP) {
    const sum = xbar(l) + ybar(l) + zbar(l);
    if (sum > 0) pts.push({ l, x: xbar(l) / sum, y: ybar(l) / sum });
  }
  return pts;
}
function dominantWavelength(sample, white) {
  // direction from white toward the sample
  const dx = sample.x - white.x, dy = sample.y - white.y;
  const locus = spectralLocus();
  let best = null;
  for (let i = 0; i < locus.length - 1; i++) {
    const a = locus[i], b = locus[i + 1];
    // segment a->b ; ray: white + t*(d), t>=0 ; solve intersection
    const ex = b.x - a.x, ey = b.y - a.y;
    const denom = dx * ey - dy * ex;
    if (Math.abs(denom) < 1e-12) continue;
    const t = ((a.x - white.x) * ey - (a.y - white.y) * ex) / denom; // along ray
    const u = ((a.x - white.x) * dy - (a.y - white.y) * dx) / denom; // along segment
    if (t > 1e-9 && u >= -1e-9 && u <= 1 + 1e-9) {
      const lam = a.l + u * (b.l - a.l);
      if (!best || t < best.t) best = { lam, t };
    }
  }
  return best ? best.lam : null;
}

// --- XYZ -> linear sRGB -> gamma sRGB (for the rendered swatch the page uses) ---
function xyzToSRGB({ X, Y, Z }) {
  // normalise so the brightest channel is 1 (we only care about chromaticity/hue here)
  let r =  3.2406 * X - 1.5372 * Y - 0.4986 * Z;
  let g = -0.9689 * X + 1.8758 * Y + 0.0415 * Z;
  let b =  0.0557 * X - 0.2040 * Y + 1.0570 * Z;
  const mx = Math.max(r, g, b, 1e-9);
  r /= mx; g /= mx; b /= mx;
  const enc = (c) => {
    c = Math.max(0, Math.min(1, c));
    return c <= 0.0031308 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
  };
  const to255 = (c) => Math.round(enc(c) * 255);
  return { r: to255(r), g: to255(g), b: to255(b) };
}

// ---------------------------------------------------------------------------
const T_SUN = 5778, T_D65 = 6500;
const WHITE_E = { x: 1 / 3, y: 1 / 3 }; // equal-energy white point

const checks = [];
function check(name, pass, detail) { checks.push({ name, pass, detail }); }

// (C) VALIDATE THE INSTRUMENT FIRST -----------------------------------------
const flatXYZ = spectrumToXYZ(() => 1.0);
const flatxy = xy(flatXYZ);
check(
  'colour machinery is honest: equal-energy spectrum -> white (1/3,1/3)',
  Math.abs(flatxy.x - 1 / 3) < 0.005 && Math.abs(flatxy.y - 1 / 3) < 0.005,
  `flat spectrum -> (x=${flatxy.x.toFixed(4)}, y=${flatxy.y.toFixed(4)}); target (0.3333,0.3333)`
);

const d65xy = xy(spectrumToXYZ((l) => planck(l, T_D65)));
check(
  '6500 K blackbody -> near D65 (0.3127, 0.3290)',
  Math.abs(d65xy.x - 0.3127) < 0.02 && Math.abs(d65xy.y - 0.3290) < 0.02,
  `6500K -> (x=${d65xy.x.toFixed(4)}, y=${d65xy.y.toFixed(4)})`
);

// The sun on its own (no scattering) ----------------------------------------
const sunXYZ = spectrumToXYZ((l) => planck(l, T_SUN));
const sunxy = xy(sunXYZ);
const sunDom = dominantWavelength(sunxy, WHITE_E);

// (A) RAYLEIGH-SCATTERED SOLAR SPECTRUM IS BRIGHTEST AT THE VIOLET END -------
const scatter = (l) => planck(l, T_SUN) * Math.pow(l, -4);
// sample the scattered spectral power across the visible band
let peakL = LAMBDA_MIN, peakV = -1, monotoneFalling = true, prev = Infinity;
const band = [];
for (let l = 400; l <= 700; l += 10) {
  const v = scatter(l);
  band.push({ l, v });
  if (v > peakV) { peakV = v; peakL = l; }
  if (v > prev + 1e-30) monotoneFalling = false;
  prev = v;
}
check(
  'Rayleigh-scattered solar spectrum is brightest at the violet end (400 nm), falling toward red',
  peakL === 400 && monotoneFalling,
  `within 400-700 nm the scattered power peaks at ${peakL} nm and falls monotonically; ` +
  `power(400)/power(700) = ${(scatter(400) / scatter(700)).toFixed(1)}x`
);

// (B) ITS PERCEIVED COLOUR IS BLUE, NOT VIOLET ------------------------------
const skyXYZ = spectrumToXYZ(scatter);
const skyxy = xy(skyXYZ);
const skyDom = dominantWavelength(skyxy, WHITE_E);
const skyRGB = xyzToSRGB(skyXYZ);

// The naive "colour = brightest wavelength" answer: a pure 400 nm violet line.
const violetXYZ = spectrumToXYZ((l) => (Math.abs(l - 400) < 0.5 ? 1 : 0));
const violetxy = xy(violetXYZ);
const violetRGB = xyzToSRGB(violetXYZ);

check(
  'perceived colour of the scattered sky is BLUE: dominant wavelength in 460-490 nm',
  skyDom !== null && skyDom >= 460 && skyDom <= 490,
  `sky colour (x=${skyxy.x.toFixed(4)}, y=${skyxy.y.toFixed(4)}) -> dominant wavelength ` +
  `${skyDom ? skyDom.toFixed(1) : 'n/a'} nm  [sRGB ${skyRGB.r},${skyRGB.g},${skyRGB.b}]`
);
check(
  'the colour is a long way from violet: dominant wavelength exceeds the violet band (<430 nm) by >40 nm',
  skyDom !== null && skyDom - 430 > 40,
  `sky dominant ${skyDom ? skyDom.toFixed(1) : 'n/a'} nm vs the violet band edge 430 nm ` +
  `(gap ${skyDom ? (skyDom - 430).toFixed(1) : 'n/a'} nm)`
);

// ---------------------------------------------------------------------------
console.log('\n  WHY ISN\'T THE SKY VIOLET? — recomputed\n');
console.log('  Colour machinery (validated against known invariants):');
console.log(`    equal-energy white  -> x=${flatxy.x.toFixed(4)} y=${flatxy.y.toFixed(4)}  (target 0.3333, 0.3333)`);
console.log(`    6500 K blackbody    -> x=${d65xy.x.toFixed(4)} y=${d65xy.y.toFixed(4)}  (D65 ~ 0.3127, 0.3290)`);
console.log('');
console.log('  The sun, then the scattering:');
console.log(`    5778 K sun, no scatter  -> x=${sunxy.x.toFixed(4)} y=${sunxy.y.toFixed(4)}  dom ${sunDom ? sunDom.toFixed(1) : 'n/a'} nm (warm white)`);
console.log(`    x lambda^-4 (Rayleigh)  -> x=${skyxy.x.toFixed(4)} y=${skyxy.y.toFixed(4)}  dom ${skyDom ? skyDom.toFixed(1) : 'n/a'} nm  sRGB(${skyRGB.r},${skyRGB.g},${skyRGB.b})  <-- the sky`);
console.log('');
console.log('  The naive "colour = brightest wavelength":');
console.log(`    pure 400 nm line        -> x=${violetxy.x.toFixed(4)} y=${violetxy.y.toFixed(4)}  sRGB(${violetRGB.r},${violetRGB.g},${violetRGB.b})  (violet)`);
console.log(`    scattered power 400 nm is ${(scatter(400) / scatter(700)).toFixed(1)}x the power at 700 nm`);
console.log('');

let allPass = true;
for (const c of checks) {
  console.log(`  [${c.pass ? ' OK ' : 'FAIL'}] ${c.name}`);
  console.log(`         ${c.detail}`);
  if (!c.pass) allPass = false;
}
console.log(`\n  ${checks.filter(c => c.pass).length}/${checks.length} checks green\n`);

// Emit the figures the page quotes, as a JSON block, so the HTML and the
// verifier can never silently drift.
const figures = {
  sky_xy: [Number(skyxy.x.toFixed(4)), Number(skyxy.y.toFixed(4))],
  sky_dominant_nm: Number(skyDom.toFixed(1)),
  sky_srgb: [skyRGB.r, skyRGB.g, skyRGB.b],
  sun_xy: [Number(sunxy.x.toFixed(4)), Number(sunxy.y.toFixed(4))],
  sun_dominant_nm: Number(sunDom.toFixed(1)),
  violet_line_srgb: [violetRGB.r, violetRGB.g, violetRGB.b],
  scatter_ratio_400_over_700: Number((scatter(400) / scatter(700)).toFixed(1)),
  equal_energy_white_xy: [Number(flatxy.x.toFixed(4)), Number(flatxy.y.toFixed(4))],
  d65_xy: [Number(d65xy.x.toFixed(4)), Number(d65xy.y.toFixed(4))],
};
console.log('  FIGURES = ' + JSON.stringify(figures));
process.exit(allPass ? 0 : 1);
