#!/usr/bin/env node
// verify.mjs — the offline ground truth for "There Is No Magenta"
// (public/strata/there-is-no-magenta/index.html), a P7 (Technical Honeypot)
// entry on colour science / human vision — the first on the ground.
//
//   node research/there-is-no-magenta/verify.mjs
//
// The central, checkable thesis: the human gamut of *hues* is an OPEN curve.
// Monochromatic light (a single wavelength) traces the "spectral locus" in the
// CIE 1931 xy chromaticity plane — the famous horseshoe. It does not close on
// itself. The straight segment that closes it, the "line of purples," contains
// NO wavelength at all: every magenta / purple / pink is necessarily a MIXTURE
// of long- and short-wavelength light. There is no spectral line you can point
// a prism at and get magenta. It is the one band of hue the eye manufactures to
// close a circle that physics leaves open.
//
// Four engines, each re-run live in the browser from the SAME embedded data:
//
//   1. THE SPECTRAL LOCUS.  From the CIE 1931 2-deg colour-matching functions
//      x̄,ȳ,z̄ (CVRL / the CIE standard), each wavelength λ maps to a chromaticity
//      (x,y). We rebuild the horseshoe and pin its two extreme tips.
//
//   2. THE LINE OF PURPLES IS EXTRA-SPECTRAL  (the thesis).  The convex hull of
//      the locus has exactly ONE long straight edge — violet tip to red tip —
//      that skips every wavelength between. We prove (a) that edge exists and is
//      unique, (b) no spectral point lies in its interior, and (c) sample
//      magentas on it sit a bounded distance away from EVERY monochromatic
//      colour. No single wavelength is magenta.
//
//   3. METAMERISM.  We build a "metameric black" M(λ) — a real spectral power
//      distribution orthogonal to all three CMFs (∫M·x̄ = ∫M·ȳ = ∫M·z̄ = 0) by
//      Gram–Schmidt. Then S+ = S0+αM and S- = S0-αM are two physically
//      DIFFERENT lights (large sup-norm gap) with byte-identical tristimulus
//      XYZ — they are the same colour. Different spectra, one colour.
//
//   4. THE GAMUT FRACTION.  The sRGB primaries (Rec.709) form a triangle inside
//      the horseshoe. We compute, exactly from the hull, the fraction of the
//      xy-chromaticity area a perfect sRGB screen can reach. (Honest caveat in
//      the page: xy area is not perceptually uniform; the number is an area
//      ratio in the 1931 plane, stated as exactly that.)
//
// Data: research/there-is-no-magenta/data/ciexyz31.csv  (5 nm, the shipped table)
//   cross-checked against ciexyz31_1.csv (1 nm).  Both: CVRL, the digitised CIE
//   1931 2° standard-observer CMFs (public standard data).

import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';

const __dir = dirname(fileURLToPath(import.meta.url));

let pass = 0, fail = 0;
const ok = (cond, msg) => { (cond ? pass++ : fail++); console.log(`  ${cond ? '✓' : '✗ FAIL'}  ${msg}`); if (!cond) process.exitCode = 1; };
const close = (a, b, tol) => Math.abs(a - b) <= tol;

// ---------------------------------------------------------------------------
// Load a CMF table: rows of [λ, x̄, ȳ, z̄].
// ---------------------------------------------------------------------------
function loadCMF(file) {
  const txt = readFileSync(join(__dir, 'data', file), 'utf8').trim();
  return txt.split('\n').map(line => line.split(',').map(Number))
    .map(([l, x, y, z]) => ({ l, x, y, z }));
}

// Chromaticity (x,y) of a single wavelength's CMF row.
const chroma = r => { const s = r.x + r.y + r.z; return [r.x / s, r.y / s]; };

// Tristimulus of a spectrum S (array aligned to a CMF table), with 1 nm/5 nm step dl.
function tristimulus(S, cmf, dl) {
  let X = 0, Y = 0, Z = 0;
  for (let i = 0; i < cmf.length; i++) { X += S[i] * cmf[i].x; Y += S[i] * cmf[i].y; Z += S[i] * cmf[i].z; }
  return [X * dl, Y * dl, Z * dl];
}

// ===========================================================================
console.log('\nENGINE 1 — THE SPECTRAL LOCUS: every wavelength is one point on a horseshoe\n');

const cmf5 = loadCMF('ciexyz31.csv');   // 5 nm, 360..830 — the table the page ships
const cmf1 = loadCMF('ciexyz31_1.csv'); // 1 nm, the cross-check

ok(cmf5.length === 95, `5 nm table has 95 rows (360..830), got ${cmf5.length}`);
ok(cmf5[0].l === 360 && cmf5[cmf5.length - 1].l === 830, '5 nm table spans 360..830 nm');
ok(cmf1.length === 471, `1 nm table has 471 rows, got ${cmf1.length}`);

// The visible window we draw and reason over: 380..700 nm, where ȳ (luminance) is
// non-negligible and the locus is the textbook horseshoe. Outside it the points
// pile invisibly onto the two tips.
const VIS_LO = 380, VIS_HI = 700;
const visible = t => t.filter(r => r.l >= VIS_LO && r.l <= VIS_HI);
const locus5 = visible(cmf5).map(r => ({ l: r.l, xy: chroma(r) }));
const locus1 = visible(cmf1).map(r => ({ l: r.l, xy: chroma(r) }));

// Famous landmark chromaticities (CIE 1931), to a few digits — a sanity pin.
const at = (loc, l) => loc.find(p => p.l === l).xy;
const c520 = at(locus5, 520); // deep green, near the top of the horseshoe
ok(close(c520[0], 0.0743, 5e-4) && close(c520[1], 0.8338, 5e-4),
   `520 nm green ≈ (0.0743, 0.8338): got (${c520[0].toFixed(4)}, ${c520[1].toFixed(4)})`);
const c700 = at(locus5, 700); // the red tip
ok(close(c700[0], 0.7347, 5e-4) && close(c700[1], 0.2653, 5e-4),
   `700 nm red tip ≈ (0.7347, 0.2653): got (${c700[0].toFixed(4)}, ${c700[1].toFixed(4)})`);
const c380 = at(locus5, 380); // the violet tip
ok(close(c380[0], 0.1741, 5e-4) && close(c380[1], 0.0050, 5e-4),
   `380 nm violet tip ≈ (0.1741, 0.0050): got (${c380[0].toFixed(4)}, ${c380[1].toFixed(4)})`);

// The locus is a function of λ that turns a full corner — y rises from ~0 at the
// violet tip to its max near 520 and falls again toward the red tip. That turn is
// exactly why the curve is open (a horseshoe), not a closed loop.
const ys = locus5.map(p => p.xy[1]);
const ymaxIdx = ys.indexOf(Math.max(...ys));
ok(locus5[ymaxIdx].l >= 510 && locus5[ymaxIdx].l <= 530,
   `locus y peaks in the green (got λ=${locus5[ymaxIdx].l} nm) — the corner that opens the curve`);

// ===========================================================================
console.log('\nENGINE 2 — THE LINE OF PURPLES IS EXTRA-SPECTRAL: no wavelength is magenta\n');

// Convex hull (monotone chain) of the locus points. The locus is convex, so its
// hull boundary = the spectral curve PLUS one straight closing edge.
function convexHull(pts) {
  const P = pts.slice().sort((a, b) => a[0] - b[0] || a[1] - b[1]);
  const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  const lower = [];
  for (const p of P) { while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop(); lower.push(p); }
  const upper = [];
  for (let i = P.length - 1; i >= 0; i--) { const p = P[i]; while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop(); upper.push(p); }
  upper.pop(); lower.pop();
  return lower.concat(upper);
}

// Use the fine (1 nm) locus for the hull so "skips a wavelength" is sharp.
const pts1 = locus1.map(p => p.xy);
const wl1 = locus1.map(p => p.l);
const hull = convexHull(pts1);

// Map each hull vertex back to its wavelength, then walk the hull and find the
// edges that SKIP wavelengths (consecutive hull vertices that are not adjacent on
// the locus). For a convex open curve closed by one chord there is exactly one
// such long edge: the line of purples.
const idxOf = xy => pts1.findIndex(p => p[0] === xy[0] && p[1] === xy[1]);
const hullWL = hull.map(v => wl1[idxOf(v)]).filter(w => w !== undefined && !Number.isNaN(w));
const hullWLsorted = hull.map(v => idxOf(v));
// Edge "wavelength gaps" around the hull cycle:
let gaps = [];
for (let i = 0; i < hullWLsorted.length; i++) {
  const a = wl1[hullWLsorted[i]], b = wl1[hullWLsorted[(i + 1) % hullWLsorted.length]];
  gaps.push({ from: a, to: b, gap: Math.abs(b - a) });
}
gaps.sort((p, q) => q.gap - p.gap);
const purpleEdge = gaps[0];
const secondGap = gaps[1].gap;
// One dominant closing chord. (The next-largest gap, ~43 nm, is the near-STRAIGHT
// red edge of the locus, where the curve is so linear that a mix of two reds is
// *almost* a single red — an honest cousin of the purple line, but the purple
// chord dwarfs it: it skips the entire middle of the visible spectrum.)
ok(purpleEdge.gap > 250 && purpleEdge.gap > 6 * secondGap,
   `ONE dominant hull edge closes the horseshoe: ${Math.min(purpleEdge.from, purpleEdge.to)}↔${Math.max(purpleEdge.from, purpleEdge.to)} nm ` +
   `skips ${purpleEdge.gap} nm of spectrum — more than 6× the next-largest gap (${secondGap} nm, the near-straight red edge)`);

// The closing chord runs violet-tip ↔ red-tip. Pin its endpoints.
const violetTip = chroma(cmf1.find(r => r.l === Math.min(purpleEdge.from, purpleEdge.to)));
const redTip    = chroma(cmf1.find(r => r.l === Math.max(purpleEdge.from, purpleEdge.to)));
ok(Math.min(purpleEdge.from, purpleEdge.to) <= 410 && Math.max(purpleEdge.from, purpleEdge.to) >= 690,
   `the chord joins the violet tip (${Math.min(purpleEdge.from, purpleEdge.to)} nm) to the red tip (${Math.max(purpleEdge.from, purpleEdge.to)} nm)`);

// Distance from a point to the polyline of the spectral locus (the nearest
// monochromatic colour). For magentas sampled strictly inside the purple line,
// this must be bounded WELL above zero: no wavelength comes near.
function distToLocus(p, loc) {
  let best = Infinity;
  for (let i = 0; i < loc.length - 1; i++) {
    const a = loc[i].xy, b = loc[i + 1].xy;
    const dx = b[0] - a[0], dy = b[1] - a[1];
    const L2 = dx * dx + dy * dy;
    let t = L2 ? ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / L2 : 0;
    t = Math.max(0, Math.min(1, t));
    const qx = a[0] + t * dx, qy = a[1] + t * dy;
    best = Math.min(best, Math.hypot(p[0] - qx, p[1] - qy));
  }
  return best;
}
// March along the purple chord and measure the distance to the nearest
// wavelength. Honest structure: at the very ends a faint purple is ALMOST a pure
// violet/red, so the distance tapers to zero at the tips (which are themselves
// spectral); across the central 70% of the line it is bounded well above zero —
// those magentas match NO wavelength. We report both.
let minCentralDist = Infinity;
for (let k = 0; k <= 100; k++) {
  const t = k / 100;
  const p = [violetTip[0] + t * (redTip[0] - violetTip[0]), violetTip[1] + t * (redTip[1] - violetTip[1])];
  if (t >= 0.15 && t <= 0.85) minCentralDist = Math.min(minCentralDist, distToLocus(p, locus1));
}
ok(minCentralDist > 0.05,
   `across the central 70% of the line of purples, every magenta is ≥ ${minCentralDist.toFixed(4)} xy-units from the NEAREST wavelength — none is spectral`);

// The deepest magenta: the chord midpoint, and how far it is from any pure light.
const mid = [(violetTip[0] + redTip[0]) / 2, (violetTip[1] + redTip[1]) / 2];
ok(distToLocus(mid, locus1) > 0.18,
   `the deepest magenta (chord midpoint) is ${distToLocus(mid, locus1).toFixed(3)} from any wavelength — fully invented by the eye`);

// And the positive half: a magenta IS reachable as a MIXTURE. The chord midpoint
// is by construction (violetTip+redTip)/2 — an equal additive mix of the two tip
// wavelengths. Additive mixing lands on the straight segment between two
// chromaticities, so the whole purple line is exactly "violet + red," nothing else.
const mixHalf = [(violetTip[0] + redTip[0]) / 2, (violetTip[1] + redTip[1]) / 2];
ok(close(mixHalf[0], mid[0], 1e-12) && close(mixHalf[1], mid[1], 1e-12),
   'magenta = equal mix of the violet tip + red tip (the chord midpoint is literally their average) — a mixture, never a wavelength');

// ===========================================================================
console.log('\nENGINE 3 — METAMERISM: two different spectra, one identical colour\n');

// Work on the 5 nm table over the visible 380..700 window (the page's data).
const win = cmf5.filter(r => r.l >= VIS_LO && r.l <= VIS_HI);
const N = win.length, dl = 5;
const xbar = win.map(r => r.x), ybar = win.map(r => r.y), zbar = win.map(r => r.z);

// Inner product (Riemann sum). Build a metameric black by Gram–Schmidt: take a
// seed bump and project out its components along x̄, ȳ, z̄.
const dot = (a, b) => { let s = 0; for (let i = 0; i < N; i++) s += a[i] * b[i]; return s * dl; };
const axpy = (a, x, y) => x.map((v, i) => v + a * y[i]); // x + a*y
// Orthonormalise the CMF triplet (Gram–Schmidt) for clean projection.
function gramSchmidt(vs) {
  const us = [];
  for (const v of vs) {
    let w = v.slice();
    for (const u of us) w = axpy(-dot(v, u), w, u);
    const n = Math.sqrt(dot(w, w));
    us.push(w.map(x => x / n));
  }
  return us;
}
const [ux, uy, uz] = gramSchmidt([xbar, ybar, zbar]);
// Seed: a smooth oscillation across the band; project out all three CMF directions.
let M = win.map((r, i) => Math.sin(2 * Math.PI * 3 * i / (N - 1)) + 0.3 * Math.cos(2 * Math.PI * 7 * i / (N - 1)));
for (const u of [ux, uy, uz]) M = axpy(-dot(M, u), M, u);
// Normalise M to a convenient amplitude.
{ const mx = Math.max(...M.map(Math.abs)); M = M.map(v => v / mx); }

ok(Math.abs(dot(M, xbar)) < 1e-9 && Math.abs(dot(M, ybar)) < 1e-9 && Math.abs(dot(M, zbar)) < 1e-9,
   `metameric black M is orthogonal to x̄,ȳ,z̄  (∫M·x̄,∫M·ȳ,∫M·z̄ = ${dot(M, xbar).toExponential(1)}, ${dot(M, ybar).toExponential(1)}, ${dot(M, zbar).toExponential(1)})`);

// Base light S0: a smooth, strictly positive illuminant-ish curve. Choose α so
// that S± = S0 ± αM are both >= 0 across the band (real, emittable spectra).
const S0 = win.map((r, i) => 0.6 + 0.35 * Math.sin(Math.PI * i / (N - 1)));
let alpha = 0.5;
const nonneg = S => S.every(v => v >= 0);
while (!(nonneg(axpy(alpha, S0, M)) && nonneg(axpy(-alpha, S0, M))) && alpha > 1e-4) alpha *= 0.9;
const Splus = axpy(alpha, S0, M), Sminus = axpy(-alpha, S0, M);

const XYZp = tristimulus(Splus, win, dl), XYZm = tristimulus(Sminus, win, dl);
const supGap = Math.max(...Splus.map((v, i) => Math.abs(v - Sminus[i])));
ok(supGap > 0.3, `S+ and S- differ physically: max |S+(λ)-S-(λ)| = ${supGap.toFixed(3)} (a real spectral gap)`);
ok(close(XYZp[0], XYZm[0], 1e-12) && close(XYZp[1], XYZm[1], 1e-12) && close(XYZp[2], XYZm[2], 1e-12),
   `yet XYZ is identical to 1e-12: ΔX,ΔY,ΔZ = ${Math.abs(XYZp[0]-XYZm[0]).toExponential(1)}, ${Math.abs(XYZp[1]-XYZm[1]).toExponential(1)}, ${Math.abs(XYZp[2]-XYZm[2]).toExponential(1)} — same colour`);

// ===========================================================================
console.log('\nENGINE 4 — THE GAMUT FRACTION: how much of the horseshoe a screen can show\n');

// Polygon area (shoelace).
const area = poly => { let a = 0; for (let i = 0; i < poly.length; i++) { const [x1, y1] = poly[i], [x2, y2] = poly[(i + 1) % poly.length]; a += x1 * y2 - x2 * y1; } return Math.abs(a) / 2; };

// The full chromaticity gamut = area enclosed by spectral locus + line of purples
// = area of the locus's convex hull. (1 nm, the sharper boundary.)
const locusArea = area(hull);

// sRGB / Rec.709 primary chromaticities.
const sRGB = { R: [0.640, 0.330], G: [0.300, 0.600], B: [0.150, 0.060], W: [0.3127, 0.3290] };
const sRGBtri = [sRGB.R, sRGB.G, sRGB.B];
const sRGBarea = area(sRGBtri);

// Point-in-convex-polygon test (hull is CCW from monotone-chain? ensure sign).
function inHull(p, hull) {
  let sign = 0;
  for (let i = 0; i < hull.length; i++) {
    const a = hull[i], b = hull[(i + 1) % hull.length];
    const cr = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
    if (cr !== 0) { if (sign === 0) sign = Math.sign(cr); else if (Math.sign(cr) !== sign) return false; }
  }
  return true;
}
ok([sRGB.R, sRGB.G, sRGB.B, sRGB.W].every(p => inHull(p, hull)),
   'all three sRGB primaries + the D65 white point lie inside the horseshoe (they are realisable chromaticities)');

const frac = sRGBarea / locusArea;
ok(frac > 0.30 && frac < 0.40,
   `sRGB covers ${(frac * 100).toFixed(1)}% of the 1931 xy-chromaticity area — a screen physically cannot reach the other ~${(100 - frac * 100).toFixed(0)}%`);

// Cross-check the area fraction against the 5 nm hull (looser boundary) — should
// agree to ~1%.
const hull5 = convexHull(locus5.map(p => p.xy));
const frac5 = sRGBarea / area(hull5);
ok(close(frac, frac5, 0.01), `area fraction is stable across 1 nm vs 5 nm sampling: ${(frac*100).toFixed(1)}% vs ${(frac5*100).toFixed(1)}%`);

// ---------------------------------------------------------------------------
console.log(`\n${pass}/${pass + fail} checks passed${fail ? ` — ${fail} FAILED` : ''}.\n`);

// Emit the headline numbers the page should match, for the record.
console.log('Headline values (the page recomputes these live from the same table):');
console.log(`  violet tip   λ=${Math.min(purpleEdge.from, purpleEdge.to)} nm   xy=(${violetTip[0].toFixed(4)}, ${violetTip[1].toFixed(4)})`);
console.log(`  red tip      λ=${Math.max(purpleEdge.from, purpleEdge.to)} nm   xy=(${redTip[0].toFixed(4)}, ${redTip[1].toFixed(4)})`);
console.log(`  line of purples: ${gaps[0].gap} nm of spectrum skipped; central-70% magentas ≥ ${minCentralDist.toFixed(4)} xy-units from any wavelength (midpoint ${distToLocus(mid, locus1).toFixed(3)})`);
console.log(`  sRGB area fraction: ${(frac * 100).toFixed(1)}%  (locus area ${locusArea.toFixed(4)}, sRGB ${sRGBarea.toFixed(4)})`);
console.log(`  metamer gap: max|S+ - S-| = ${supGap.toFixed(3)} at identical XYZ (Δ < 1e-12)`);
