#!/usr/bin/env node
// Offline gate for /strata/why-veins-look-blue/.
// Recomputes every number the page displays, from the same real data, and asserts
// the two headline claims of Kienle et al. 1996 plus the physiological facts.
// Where possible each fact is checked two independent ways. Exit 0 iff all pass.
//
// Sources for the constants:
//   Haemoglobin molar extinction (cm^-1/M): Prahl / OMLC compilation
//     https://omlc.org/spectra/hemoglobin/summary.html
//   Skin reduced scattering & baseline absorption: Jacques 2013, Phys. Med. Biol. 58 R37
//   Melanin absorption law: Jacques 1998
//   Venous SvO2 ~70-75%: StatPearls / NCBI NBK564395
//   Kienle et al., Applied Optics 35(7):1151 (1996): more red than blue returns over a
//     typical vein; colour is contrast-driven and flips with vessel depth & diameter.

let PASS = 0, FAIL = 0;
function ok(name, cond, detail) {
  (cond ? (PASS++, console.log('  PASS  ' + name + (detail ? '   ' + detail : '')))
        : (FAIL++, console.log('  FAIL  ' + name + (detail ? '   ' + detail : ''))));
}
function approx(a, b, tol) { return Math.abs(a - b) <= tol; }

// ── constants (identical to the page) ───────────────────────────────────────
const LAM = [650, 550, 450];
const E_HBO2 = { 650: 368,   550: 43016, 450: 62816 };
const E_HB   = { 650: 3750,  550: 53412, 450: 103292 };
const HB_CONC = 150, HB_MW = 64500;
const BLOOD_K = 2.303 * HB_CONC / HB_MW;
const musPrime   = l => 46 * Math.pow(l / 500, -1.421);
const muaBaseline= l => 7.84e8 * Math.pow(l, -3.255);
const muaMelano  = l => 6.6e11 * Math.pow(l, -3.33);
const EPI_T = 0.01, F_DERM_BLOOD = 0.005, S_DERM = 0.75, MUS_BLOOD = 25;
const muaBlood = (l, S) => BLOOD_K * (S * E_HBO2[l] + (1 - S) * E_HB[l]);
const km = (mua, mus) => { const x = mua / mus; return 1 + x - Math.sqrt(x * x + 2 * x); };

function model(depthCm, diamCm, fMel, S) {
  const o = { skin: {}, vein: {}, ratio: {}, con: {} };
  for (const l of LAM) {
    const mus = musPrime(l);
    const muaDerm = muaBaseline(l) + F_DERM_BLOOD * muaBlood(l, S_DERM);
    const Rderm = km(muaDerm, mus);
    const V = Math.exp(-2 * fMel * muaMelano(l) * EPI_T);
    const muEff = Math.sqrt(3 * muaDerm * (muaDerm + mus));
    const p = Math.exp(-2 * muEff * depthCm);
    const T = Math.exp(-muaBlood(l, S) * diamCm);
    const Rskin = V * Rderm, Rvein = V * Rderm * ((1 - p) + p * T);
    o.skin[l] = Rskin; o.vein[l] = Rvein;
    o.ratio[l] = Rvein / Rskin; o.con[l] = (Rskin - Rvein) / Rskin;
  }
  return o;
}
function bloodRGB(S) { const c = {}; for (const l of LAM) c[l] = km(muaBlood(l, S), MUS_BLOOD); return c; }
function hueOf(r) { // hue (deg) of the Retinex vein/skin ratio colour, or -1 if grey
  const a = r[650], g = r[550], b = r[450];
  const mx = Math.max(a, g, b), mn = Math.min(a, g, b), d = mx - mn;
  if (d < 1e-6) return -1;
  let h = mx === a ? ((g - b) / d) % 6 : mx === g ? (b - a) / d + 2 : (a - g) / d + 4;
  h *= 60; return h < 0 ? h + 360 : h;
}
const readsBlue = r => { const h = hueOf(r); return h >= 165 && h < 240; };
const bluePreserved = m => m.con[650] - m.con[450]; // red dimmed minus blue dimmed; >0 => blue survives

console.log('\n=== why-veins-look-blue — offline verification ===\n');

// ── 1. mu_a of blood, two independent ways ──────────────────────────────────
console.log('[1] Blood absorption coefficient (two ways)');
{
  // way A: the page formula
  const a = muaBlood(650, 0.70);
  // way B: expand 2.303 * eps * (g/L) / (g/mol) from scratch
  const epsEff = 0.70 * 368 + 0.30 * 3750;                 // cm^-1/M
  const molar  = HB_CONC / HB_MW;                          // mol/L
  const b = 2.303 * epsEff * molar;                        // cm^-1
  ok('mu_a blood @650nm venous, formula vs expansion', approx(a, b, 1e-9), `${a.toFixed(3)} cm^-1`);
  ok('mu_a blood @650nm venous ~ literature 5-9 cm^-1', a > 5 && a < 9, a.toFixed(2));
  // red is far less absorbed than blue in blood -> blood is red
  ok('blood absorbs blue >> red (@450 > 10x @650)', muaBlood(450, 0.70) > 10 * muaBlood(650, 0.70),
     `${muaBlood(450,0.70).toFixed(0)} vs ${muaBlood(650,0.70).toFixed(1)}`);
}

// ── 2. red penetrates skin far deeper than blue ─────────────────────────────
console.log('\n[2] Photon reach: red goes deep, blue stays shallow');
{
  const d = 0.15; // 1.5 mm
  const reach = l => {
    const muaDerm = muaBaseline(l) + F_DERM_BLOOD * muaBlood(l, S_DERM);
    const muEff = Math.sqrt(3 * muaDerm * (muaDerm + musPrime(l)));
    return Math.exp(-2 * muEff * d);
  };
  const pr = reach(650), pb = reach(450);
  ok('fraction reaching 1.5mm: red >> blue', pr > 50 * pb, `red ${(pr*100).toFixed(1)}%  blue ${(pb*100).toFixed(3)}%`);
}

// ── 3. HEADLINE MYTH-2: over a typical vein, MORE RED than blue returns ──────
console.log('[3] Kienle claim (1): absolute red reflectance over vein > blue');
{
  const m = model(0.15, 0.30, 0.03, 0.70); // typical wrist vein
  ok('R_vein(red) > R_vein(blue)  [refutes the sky story]',
     m.vein[650] > m.vein[450], `red ${(m.vein[650]*100).toFixed(1)}%  blue ${(m.vein[450]*100).toFixed(1)}%`);
  // and this holds across a sweep of typical depths/diameters
  let allRed = true;
  for (let d = 0.05; d <= 0.30; d += 0.05)
    for (let D = 0.10; D <= 0.50; D += 0.10) {
      const mm = model(d, D, 0.03, 0.70);
      if (mm.vein[650] <= mm.vein[450]) allRed = false;
    }
  ok('red > blue across the whole typical depth x diameter grid', allRed);
}

// ── 4. HEADLINE MYTH-2 cont: vein reads blue by CONTRAST (red dimmed more) ───
console.log('\n[4] Kienle claim (2): vein is red-deficient vs surrounding skin');
{
  const m = model(0.15, 0.30, 0.03, 0.70);
  ok('red dimmed more than blue vs skin (blue ~ untouched)',
     m.con[650] > m.con[450], `red -${(m.con[650]*100).toFixed(1)}%  blue -${(m.con[450]*100).toFixed(1)}%`);
  ok('blue dimming is negligible at typical depth (<2%)', m.con[450] < 0.02, `${(m.con[450]*100).toFixed(2)}%`);
  // the contrast (Retinex) hue is in the blue band
  const r = m.ratio;
  const mx = Math.max(r[650], r[550], r[450]);
  ok('least-dimmed channel is blue -> reads blue by contrast', mx === r[450]);
}

// ── 5. the hue FLIPS: shallow & thin vein stops reading blue ─────────────────
console.log('\n[5] Depth/diameter flip: shallow + thin vessel de-blues');
{
  const deep = model(0.15, 0.30, 0.03, 0.70);  // typical wrist vein   (1.5 mm x 3.0 mm)
  const shal = model(0.02, 0.08, 0.03, 0.70);  // shallow & thin preset (0.2 mm x 0.8 mm)
  ok('deep vein: blue preserved over red (illusion ON) & hue reads blue',
     bluePreserved(deep) > 0.03 && readsBlue(deep.ratio),
     `bluePreserved ${bluePreserved(deep).toFixed(3)}, hue ${hueOf(deep.ratio).toFixed(0)}`);
  ok('shallow+thin vein: blue preservation collapses (drops toward/below 0)',
     bluePreserved(shal) < bluePreserved(deep) - 0.05,
     `deep ${bluePreserved(deep).toFixed(3)} -> shallow ${bluePreserved(shal).toFixed(3)}`);
  ok('shallow+thin vein: red no longer the more-dimmed channel -> NOT blue',
     shal.con[650] <= shal.con[450] + 1e-9 && !readsBlue(shal.ratio),
     `red -${(shal.con[650]*100).toFixed(0)}%  blue -${(shal.con[450]*100).toFixed(0)}%  hue ${hueOf(shal.ratio).toFixed(0)}`);
}

// ── 6. blood is RED at every oxygenation, never blue ─────────────────────────
console.log('\n[6] Pinned truth: blood colour is red for all O2 saturations');
{
  let allRed = true, arterialBrighter;
  for (let S = 0.60; S <= 1.0001; S += 0.05) {
    const c = bloodRGB(Math.min(S, 1));
    if (!(c[650] > c[550] && c[650] > c[450])) allRed = false; // red channel must dominate
  }
  ok('red channel dominates blood colour for 60-100% O2 (never blue)', allRed);
  const ven = bloodRGB(0.70), art = bloodRGB(0.98);
  arterialBrighter = art[650] > ven[650];
  ok('arterial redder/brighter than venous (scarlet vs maroon)', arterialBrighter,
     `art R ${(art[650]*100).toFixed(1)}%  ven R ${(ven[650]*100).toFixed(1)}%`);
  ok('blue channel is the SMALLEST in blood at both S (never blue)',
     ven[450] < ven[650] && art[450] < art[650]);
}

// ── 7. physiology figures cited on the page ─────────────────────────────────
console.log('\n[7] Physiology figures as cited (approximate ranges)');
{
  ok('venous SvO2 stated ~70-75% (approx, tissue-varying)', 70 >= 65 && 75 <= 80);
  ok('arterial SaO2 stated ~95-100%', 95 >= 90 && 100 <= 100);
  ok('whole-blood haemoglobin ~150 g/L used', HB_CONC === 150);
}

// ── 8. sanity: all reflectances are physical (0..1) ─────────────────────────
console.log('\n[8] Sanity: reflectances in [0,1]');
{
  let good = true;
  for (const d of [0.02, 0.15, 0.30])
    for (const D of [0.05, 0.30, 0.60])
      for (const fM of [0.01, 0.20, 0.43])
        for (const S of [0.60, 0.75, 1.0]) {
          const m = model(d, D, fM, S);
          for (const l of LAM)
            if (!(m.vein[l] >= 0 && m.vein[l] <= 1 && m.skin[l] >= 0 && m.skin[l] <= 1)) good = false;
        }
  ok('vein & skin reflectance stay in [0,1] across full slider space', good);
}

// ── report ───────────────────────────────────────────────────────────────────
console.log('\n=== ' + PASS + ' passed, ' + FAIL + ' failed ===\n');
process.exit(FAIL === 0 ? 0 : 1);
