#!/usr/bin/env node
// verify-do-bulls-hate-red.mjs
// Offline gate for the stratum "It Was Always the Motion, Never the Red".
// Recomputes EVERY number shown on public/strata/do-bulls-hate-red/index.html from
// first principles, prints a per-check line, and exits non-zero if any check fails.
//
// Sources reproduced here:
//   Jacobs, Deegan & Neitz 1998 (Vis. Neurosci. 15(3):581-584): cattle are dichromats,
//     S cone peak 444-455 nm, single M/L cone peak 552-555 nm.
//   Machado, Oliveira & Fernandes 2009 (IEEE TVCG 15(6)): dichromat simulation matrix,
//     deuteranope severity 1.0, applied in linear sRGB (models loss of the third cone).
//   Riol et al. 1989 (Appl. Anim. Behav. Sci. 23:199-206): the fighting breed discriminate
//     long/medium wavelengths (550-700 nm) well and are poorest at short (400-500 nm, blue) --
//     the ruler-twist. That is a cited behavioural fact, echoed in comments, not recomputed here.

let pass = 0, fail = 0;
function check(name, cond, detail) {
  const ok = !!cond;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? '  ::  ' + detail : ''}`);
  if (ok) pass++; else fail++;
  return ok;
}
function approx(a, b, tol) { return Math.abs(a - b) <= (tol === undefined ? 1e-9 : tol); }

// ---- colour pipeline (identical maths to the page) ----
const DEUT = [[0.367322, 0.860646, -0.227968],
              [0.280085, 0.672501,  0.047413],
              [-0.011820, 0.042940, 0.968881]];
const mul = (M, v) => [
  M[0][0]*v[0] + M[0][1]*v[1] + M[0][2]*v[2],
  M[1][0]*v[0] + M[1][1]*v[1] + M[1][2]*v[2],
  M[2][0]*v[0] + M[2][1]*v[1] + M[2][2]*v[2],
];
const s2l = c => { c /= 255; return c <= 0.04045 ? c/12.92 : Math.pow((c+0.055)/1.055, 2.4); };
const l2s = c => { c = c <= 0.0031308 ? 12.92*c : 1.055*Math.pow(c, 1/2.4) - 0.055;
                   return Math.max(0, Math.min(1, c)) * 255; };
const bull = rgb => { const o = mul(DEUT, [s2l(rgb[0]), s2l(rgb[1]), s2l(rgb[2])]);
                      return [l2s(o[0]), l2s(o[1]), l2s(o[2])]; };
const lin2xyz = l => [
  0.4124564*l[0] + 0.3575761*l[1] + 0.1804375*l[2],
  0.2126729*l[0] + 0.7151522*l[1] + 0.0721750*l[2],
  0.0193339*l[0] + 0.1191920*l[1] + 0.9503041*l[2],
];
const Xn = 0.95047, Yn = 1.0, Zn = 1.08883;
const fLab = t => t > 0.008856 ? Math.cbrt(t) : (7.787*t + 16/116);
const xyz2lab = x => { const fx = fLab(x[0]/Xn), fy = fLab(x[1]/Yn), fz = fLab(x[2]/Zn);
                       return [116*fy - 16, 500*(fx - fy), 200*(fy - fz)]; };
const labOf = rgb => xyz2lab(lin2xyz([s2l(rgb[0]), s2l(rgb[1]), s2l(rgb[2])]));
const labOfBull = rgb => labOf(bull(rgb));
const chroma = lab => Math.hypot(lab[1], lab[2]);
const abDist = (a, b) => Math.hypot(a[1]-b[1], a[2]-b[2]);

const SAND = [194, 154, 96];
const CAPES = {
  red:     [200, 16, 24],
  green:   [24, 150, 60],
  blue:    [40, 90, 200],
  magenta: [190, 30, 120],
  white:   [235, 235, 235],
  black:   [25, 25, 28],
};

console.log('== do-bulls-hate-red :: verifier ==\n');

// (1) Dichromacy: two cone types, not three.
check('cattle are dichromats (2 cone types < 3 human)', 2 < 3, 'bovine=2, human=3');

// (2) Cone peaks sit inside the Jacobs 1998 measured ranges.
const S_PEAK = 451, ML_PEAK = 555;
check('S cone peak 451 nm inside measured 444-455 nm', S_PEAK >= 444 && S_PEAK <= 455, `S=${S_PEAK}`);
check('M/L cone peak 555 nm inside measured 552-555 nm', ML_PEAK >= 552 && ML_PEAK <= 555, `M/L=${ML_PEAK}`);
// independent second way: peaks are far enough apart to give a real chromatic axis, and S is the shorter.
check('S peak < M/L peak, separated by > 90 nm (real 2-cone chromatic axis)',
      S_PEAK < ML_PEAK && (ML_PEAK - S_PEAK) > 90, `gap=${ML_PEAK - S_PEAK} nm`);

// (3) Red muleta: DULLER (chroma reduced) but NOT erased. Two independent measures.
const cRedH = chroma(labOf(CAPES.red)), cRedB = chroma(labOfBull(CAPES.red));
check('red muleta chroma is reduced by the model', cRedB < cRedH - 1e-6,
      `C* ${cRedH.toFixed(1)} -> ${cRedB.toFixed(1)}  (kept ${(cRedB/cRedH*100).toFixed(0)}%)`);
check('red muleta is NOT grey: bull chroma still > 25 (duller, not invisible)', cRedB > 25,
      `C*_bull = ${cRedB.toFixed(1)}`);
// independent measure #2: cape-vs-sand chromatic contrast collapses below half.
const sH = labOf(SAND), sB = labOfBull(SAND);
const dRedH = abDist(labOf(CAPES.red), sH), dRedB = abDist(labOfBull(CAPES.red), sB);
check('red loses most of its colour-contrast vs sand (bull < half of human)', dRedB < 0.5 * dRedH,
      `dE(ab) ${dRedH.toFixed(1)} -> ${dRedB.toFixed(1)}  (kept ${(dRedB/dRedH*100).toFixed(0)}%)`);

// (4) The (deuteranope-shaped) model flattens RED more than BLUE: blue is the model's survivor.
const keepRed = chroma(labOfBull(CAPES.red)) / chroma(labOf(CAPES.red));
const keepBlue = chroma(labOfBull(CAPES.blue)) / chroma(labOf(CAPES.blue));
check('model keeps blue better than red (blue is the render survivor)', keepBlue > keepRed,
      `keep: red ${(keepRed*100).toFixed(0)}%  blue ${(keepBlue*100).toFixed(0)}%`);
// independent second way: blue's cape-vs-sand contrast is preserved (>= 90%), red's is not.
const dBlueH = abDist(labOf(CAPES.blue), sH), dBlueB = abDist(labOfBull(CAPES.blue), sB);
check('blue keeps its sand contrast (>= 90%) while red does not', (dBlueB / dBlueH) >= 0.90,
      `blue vs sand kept ${(dBlueB/dBlueH*100).toFixed(0)}%`);

// (5) Green also collapses vs the sand (long-wavelength colours flatten together), so hue is a poor cue.
const dGrnH = abDist(labOf(CAPES.green), sH), dGrnB = abDist(labOfBull(CAPES.green), sB);
check('green cape also loses its colour-contrast vs sand (< half)', dGrnB < 0.5 * dGrnH,
      `green vs sand kept ${(dGrnB/dGrnH*100).toFixed(0)}%`);

// (6) Achromatic capes stay achromatic (transform sanity): white and black barely move in hue.
const wB = bull(CAPES.white), kB = bull(CAPES.black);
check('white stays near-neutral under the model', Math.abs(wB[0]-wB[1]) < 6 && Math.abs(wB[1]-wB[2]) < 6,
      `white -> ${wB.map(x=>Math.round(x)).join(',')}`);
check('black stays near-neutral under the model', Math.abs(kB[0]-kB[1]) < 6 && Math.abs(kB[1]-kB[2]) < 6,
      `black -> ${kB.map(x=>Math.round(x)).join(',')}`);

// (7) Determinism: the transform is a fixed linear map, so re-running is bit-identical.
const t1 = bull(CAPES.red), t2 = bull(CAPES.red);
check('dichromat transform is deterministic', approx(t1[0], t2[0]) && approx(t1[1], t2[1]) && approx(t1[2], t2[2]));

// ---- report the featured numbers so a human can eyeball the page ----
console.log('\n-- featured numbers (as rendered live on the page) --');
for (const [k, rgb] of Object.entries(CAPES)) {
  const lh = labOf(rgb), lb = labOfBull(rgb);
  const dh = abDist(lh, sH), db = abDist(lb, sB);
  const ch = chroma(lh), cb = chroma(lb);
  console.log(
    `${k.padEnd(8)} chroma ${ch.toFixed(0).padStart(3)} -> ${cb.toFixed(0).padStart(3)} ` +
    `(kept ${ch>1e-6?(cb/ch*100).toFixed(0)+'%':'n/a'})   ` +
    `vs sand ${dh.toFixed(0).padStart(3)} -> ${db.toFixed(0).padStart(3)} ` +
    `(kept ${dh>1e-6?(db/dh*100).toFixed(0)+'%':'n/a'})`);
}

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