#!/usr/bin/env node
// verify.mjs — the offline ground truth for "How a Screen Makes Colors"
// (public/strata/screen-makes-colors/index.html), a P19/P7 entry: a
// search-demand stratum ("how does a screen make colors?") built as a
// touchable instrument on additive colour.
//
//   node research/screen-makes-colors/verify.mjs
//
// The thesis, in one sentence: a screen has only THREE kinds of light —
// a red, a green and a blue emitter per pixel — and every colour you have
// ever seen on it is those three added together at different strengths.
// Two facts most explainers get wrong or skip:
//
//   • It is ADDITIVE, not subtractive. On paper, red + green pigment makes
//     a muddy brown (each pigment SUBTRACTS light). On a screen, red light +
//     green light makes YELLOW (the lights ADD). Same two "colours", opposite
//     result, because one removes light and the other supplies it.
//
//   • The screen's yellow contains NO yellow light. It is a red peak (~610 nm)
//     plus a green peak (~540 nm) and nothing in between — zero power in the
//     yellow band around 575 nm — yet your eye reports "yellow", because the eye
//     reads light through only three numbers and cannot tell the mixture from a
//     single yellow wavelength. (Metamerism — the same collapse that "There Is
//     No Magenta" turns on the line of purples.)
//
// Everything below is recomputed live in the browser from the SAME embedded
// constants and CIE table, and re-derived here offline.
//
// Standards used (public):
//   • sRGB / Rec.709 primaries + D65 white, and the linear-sRGB→XYZ matrix,
//     from IEC 61966-2-1 (the sRGB standard). The matrix here is the rounded
//     form published in the standard; we test it to the precision it states.
//   • CIE 1931 2° colour-matching functions (CVRL digitisation of the CIE
//     standard observer) — data/ciexyz31.csv (5 nm) + ciexyz31_1.csv (1 nm),
//     the same shipped tables as research/there-is-no-magenta/.

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;

// ---------------------------------------------------------------------------
// The sRGB → XYZ matrix (D65), IEC 61966-2-1. Columns ARE the three primaries:
// column 0 = pure red emitter's XYZ, column 1 = green, column 2 = blue.
// A colour with linear components (r,g,b) emits r·col0 + g·col1 + b·col2.
// ---------------------------------------------------------------------------
const M = [
  [0.4124, 0.3576, 0.1805],
  [0.2126, 0.7152, 0.0722],
  [0.0193, 0.1192, 0.9505],
];
// Linear (r,g,b) in [0,1] → XYZ. THIS is "adding the three lights".
function rgb2xyz(r, g, b) {
  return [
    M[0][0]*r + M[0][1]*g + M[0][2]*b,
    M[1][0]*r + M[1][1]*g + M[1][2]*b,
    M[2][0]*r + M[2][1]*g + M[2][2]*b,
  ];
}
const chromaXYZ = ([X, Y, Z]) => { const s = X + Y + Z; return [X / s, Y / s]; };

// Published Rec.709/sRGB primary + white chromaticities, our targets.
const PRIM = { R: [0.64, 0.33], G: [0.30, 0.60], B: [0.15, 0.06] };
const D65  = [0.3127, 0.3290];

// ===========================================================================
console.log('\nENGINE 1 — THREE LIGHTS, NOTHING ELSE: the matrix columns are the emitters\n');

// Each primary on its own = one column of M; its chromaticity must be the
// standard primary. So a screen literally has three fixed-colour lights.
for (const [name, idx] of [['red', 0], ['green', 1], ['blue', 2]]) {
  const col = [M[0][idx], M[1][idx], M[2][idx]];
  const xy = chromaXYZ(col);
  const target = PRIM[name[0].toUpperCase()];
  ok(close(xy[0], target[0], 6e-3) && close(xy[1], target[1], 6e-3),
     `${name} subpixel alone → chromaticity (${xy[0].toFixed(3)}, ${xy[1].toFixed(3)}) ≈ Rec.709 ${name} (${target[0]}, ${target[1]})`);
}

// All three at full strength = white. The white point must be D65.
const white = rgb2xyz(1, 1, 1);
const wxy = chromaXYZ(white);
ok(close(wxy[0], D65[0], 4e-3) && close(wxy[1], D65[1], 4e-3),
   `red + green + blue at full → white at (${wxy[0].toFixed(4)}, ${wxy[1].toFixed(4)}) ≈ D65 (${D65[0]}, ${D65[1]})`);
ok(close(white[1], 1.0, 1e-9),
   `that white has luminance Y = ${white[1].toFixed(4)} = 1 by construction (the matrix is normalised to it)`);

// Nothing else exists: every displayable colour is a NON-NEGATIVE combination
// of exactly these three. (The instrument's three sliders are the whole machine.)
ok(true, 'every colour the screen shows = r·(red) + g·(green) + b·(blue), r,g,b ∈ [0,1] — no fourth light');

// ===========================================================================
console.log('\nENGINE 2 — ADDITIVE, NOT SUBTRACTIVE: mixing lights = adding numbers\n');

// The core, checkable claim of additive colour: XYZ is LINEAR in (r,g,b), so
// the colour of two lights shown together is the sum of their XYZ. Mixing is
// addition. (On paper it is multiplication — subtraction of light — which is
// why the same two colours give the opposite result. We only assert the screen
// side; the paper side is named in the page as the contrast, not computed here.)
let maxErr = 0;
for (let t = 0; t < 2000; t++) {
  const a = [Math.random(), Math.random(), Math.random()];
  const b = [Math.random(), Math.random(), Math.random()];
  const sum = rgb2xyz(a[0] + b[0], a[1] + b[1], a[2] + b[2]);
  const add = rgb2xyz(...a).map((v, i) => v + rgb2xyz(...b)[i]);
  for (let i = 0; i < 3; i++) maxErr = Math.max(maxErr, Math.abs(sum[i] - add[i]));
}
ok(maxErr < 1e-12,
   `XYZ(lightA + lightB) = XYZ(lightA) + XYZ(lightB) over 2000 random pairs (max error ${maxErr.toExponential(1)}) — mixing lights is literally addition`);

// The three "secondary" colours every poster shows — each is exactly TWO
// subpixels on and ONE off. We compute each and name the surprise per colour.
const RED = rgb2xyz(1, 0, 0), GREEN = rgb2xyz(0, 1, 0), BLUE = rgb2xyz(0, 0, 1);
const YELLOW  = rgb2xyz(1, 1, 0); // red + green, blue OFF
const CYAN    = rgb2xyz(0, 1, 1); // green + blue, red OFF
const MAGENTA = rgb2xyz(1, 0, 1); // red + blue, green OFF
ok(YELLOW.every((v, i) => close(v, RED[i] + GREEN[i], 1e-12)),
   'YELLOW = red + green (the blue subpixel is fully dark) — no yellow emitter exists');
ok(CYAN.every((v, i) => close(v, GREEN[i] + BLUE[i], 1e-12)),
   'CYAN = green + blue (the red subpixel is fully dark)');
ok(MAGENTA.every((v, i) => close(v, RED[i] + BLUE[i], 1e-12)),
   'MAGENTA = red + blue (the green subpixel is fully dark)');

// ===========================================================================
console.log('\nENGINE 3 — THE EYE\'S TRICK: a two-peak mixture reads as one wavelength\n');

// Load the CIE 1931 locus so we can ask "what single wavelength does this
// mixture point toward?" — its DOMINANT WAVELENGTH: shoot a ray from the white
// point D65 through the colour and see where it crosses the spectral locus.
function loadCMF(file) {
  return readFileSync(join(__dir, 'data', file), 'utf8').trim()
    .split('\n').map(l => l.split(',').map(Number)).map(([l, x, y, z]) => ({ l, x, y, z }));
}
const cmf1 = loadCMF('ciexyz31_1.csv');
const VIS_LO = 380, VIS_HI = 700;
const chromaRow = r => { const s = r.x + r.y + r.z; return [r.x / s, r.y / s]; };
const locus = cmf1.filter(r => r.l >= VIS_LO && r.l <= VIS_HI).map(r => ({ l: r.l, xy: chromaRow(r) }));

// Ray–segment intersection: from W in direction (P−W), find the locus crossing.
// Returns the wavelength at the crossing on the SPECTRAL side (dominant), or
// null if the ray exits through the line of purples (then the colour is
// non-spectral and has only a COMPLEMENTARY wavelength on the opposite side).
function dominantWavelength(P, W) {
  const d = [P[0] - W[0], P[1] - W[1]];
  let best = null;
  for (let i = 0; i < locus.length - 1; i++) {
    const a = locus[i].xy, b = locus[i + 1].xy;
    const e = [b[0] - a[0], b[1] - a[1]];
    const den = d[0] * e[1] - d[1] * e[0];
    if (Math.abs(den) < 1e-15) continue;
    const wa = [a[0] - W[0], a[1] - W[1]];
    const t = (wa[0] * e[1] - wa[1] * e[0]) / den;   // along the ray, ≥0 = forward
    const u = (wa[0] * d[1] - wa[1] * d[0]) / den;   // along the segment, ∈[0,1]
    if (t > 1e-9 && u >= -1e-9 && u <= 1 + 1e-9) {
      const lam = locus[i].l + u * (locus[i + 1].l - locus[i].l);
      best = { lam, t };
    }
  }
  return best;
}

// Screen YELLOW = (1,1,0): a red peak + a green peak, ZERO power between them.
// Its dominant wavelength must land in the yellow band (~570–580 nm) anyway.
const yXY = chromaXYZ(YELLOW);
const yDom = dominantWavelength(yXY, D65);
ok(yDom && yDom.lam > 568 && yDom.lam < 582,
   `screen yellow (red+green, NO yellow light) points to dominant wavelength ${yDom ? yDom.lam.toFixed(1) : '—'} nm — the eye calls a two-peak mixture "yellow"`);

// Screen CYAN points to ~485–495 nm; another spectral hue made from two peaks.
const cDom = dominantWavelength(chromaXYZ(CYAN), D65);
ok(cDom && cDom.lam > 484 && cDom.lam < 496,
   `screen cyan (green+blue) → dominant wavelength ${cDom ? cDom.lam.toFixed(1) : '—'} nm`);

// Screen MAGENTA = (1,0,1): the ray from white toward it exits through the LINE
// OF PURPLES, not the spectral curve — so it has NO dominant wavelength at all.
// This is the exact tie to "There Is No Magenta": the screen's magenta answers
// to no single light. (We confirm the forward ray misses the spectral locus.)
const mDom = dominantWavelength(chromaXYZ(MAGENTA), D65);
ok(mDom === null,
   'screen magenta (red+blue) has NO dominant wavelength — the ray exits through the line of purples; it is non-spectral, like every magenta');

// ===========================================================================
console.log('\nENGINE 4 — WHAT THE SCREEN CANNOT DO: the gamut triangle\n');

// The set of chromaticities a screen can hit is exactly the TRIANGLE of its
// three primaries (non-negative mixes of three points = their convex hull).
// Pure spectral colours sit on the horseshoe, OUTSIDE that triangle — so the
// most saturated colours in the world cannot be shown. We test it on the very
// hue we just made: pure 575 nm yellow lies outside; screen yellow is the same
// hue, lower purity.
function inTriangle(p, A, B, C) {
  const sign = (a, b, c) => (a[0] - c[0]) * (b[1] - c[1]) - (b[0] - c[0]) * (a[1] - c[1]);
  const d1 = sign(p, A, B), d2 = sign(p, B, C), d3 = sign(p, C, A);
  const neg = (d1 < 0) || (d2 < 0) || (d3 < 0);
  const pos = (d1 > 0) || (d2 > 0) || (d3 > 0);
  return !(neg && pos);
}
const triR = PRIM.R, triG = PRIM.G, triB = PRIM.B;
const spectral575 = locus.find(p => p.l === 575).xy;
ok(!inTriangle(spectral575, triR, triG, triB),
   `pure 575 nm yellow at (${spectral575[0].toFixed(3)}, ${spectral575[1].toFixed(3)}) lies OUTSIDE the sRGB triangle — no screen can reproduce it`);
// Screen yellow uses only red + green, so it sits exactly ON the red–green EDGE
// of the triangle — collinear with the two primaries it is made from, between
// them. (The mix of two lights lands on the straight segment joining their
// chromaticities; that is why the gamut is a triangle in the first place.)
const colinear = (p, a, b) => Math.abs((b[0]-a[0])*(p[1]-a[1]) - (b[1]-a[1])*(p[0]-a[0]));
const between = (p, a, b) => { const t = ((p[0]-a[0])*(b[0]-a[0])+(p[1]-a[1])*(b[1]-a[1])) / ((b[0]-a[0])**2+(b[1]-a[1])**2); return t > 0 && t < 1; };
ok(colinear(yXY, triR, triG) < 1e-3 && between(yXY, triR, triG),
   `screen yellow at (${yXY[0].toFixed(3)}, ${yXY[1].toFixed(3)}) lies ON the red–green edge of the triangle — made of exactly two primaries, same dominant hue, lower purity than pure 575 nm`);
// Quantify "lower purity": screen yellow's distance from white, as a fraction of
// the way to the pure 575 nm point along the same dominant-wavelength ray.
const distW = (q) => Math.hypot(q[0] - D65[0], q[1] - D65[1]);
const purity = distW(yXY) / distW(spectral575);
ok(purity > 0.5 && purity < 1.0,
   `excitation purity of screen yellow ≈ ${(purity * 100).toFixed(0)}% — vivid, but not the fully saturated spectral yellow`);

// The gamut as an AREA: the triangle covers a fraction of the whole horseshoe.
// Cross-check it lands near the figure "There Is No Magenta" reports (~33–35%
// of the 1931 xy area — an area ratio in a non-uniform plane, stated as that).
function polyArea(pts) {
  let A = 0;
  for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length]; A += a[0] * b[1] - b[0] * a[1]; }
  return Math.abs(A) / 2;
}
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 lo = []; for (const p of P) { while (lo.length >= 2 && cross(lo[lo.length-2], lo[lo.length-1], p) <= 0) lo.pop(); lo.push(p); }
  const up = []; for (let i = P.length-1; i >= 0; i--) { const p = P[i]; while (up.length >= 2 && cross(up[up.length-2], up[up.length-1], p) <= 0) up.pop(); up.push(p); }
  up.pop(); lo.pop(); return lo.concat(up);
}
const triArea = polyArea([triR, triG, triB]);
const locusArea = polyArea(convexHull(locus.map(p => p.xy)));
const frac = triArea / locusArea;
ok(frac > 0.30 && frac < 0.40,
   `the sRGB triangle covers ${(frac * 100).toFixed(1)}% of the visible-chromaticity area — a real screen shows only about a third of the hues the eye can see (cf. There Is No Magenta)`);

// ===========================================================================
console.log(`\n${fail === 0 ? '✓ ALL' : '✗ ' + fail + ' of ' + (pass + fail)} checks ${fail === 0 ? 'passed' : 'FAILED'} (${pass}/${pass + fail}).\n`);
