#!/usr/bin/env node
// verify.mjs — the checkable spine of "The Carrot and the Cat's Eyes"
// (/strata/do-carrots-improve-eyesight/).
//
//   node research/carrots-eyesight/verify.mjs
//
// Two jobs: (1) recompute every NUMBER the page asserts and confirm it against
// the cited authorities' figures; (2) recompute the dose–response MODEL the
// instrument draws and confirm its three load-bearing properties (impaired
// below adequacy, ~100% at the RDA, and a HARD saturation above it — the myth
// line, by contrast, never stops climbing). Then read the shipped page and
// assert it carries the same figures, so the drawing and the numbers cannot
// silently disagree.
//
// SOURCES for the asserted numbers (see the page's Sources block):
//  - NIH Office of Dietary Supplements, Vitamin A (Health Professional):
//    RDA 900 µg RAE/day (men) / 700 (women); dietary β-carotene→RAE = 12:1;
//    ½ cup raw carrots = 459 µg RAE (~51% male RDA); UL preformed retinol 3000 µg/day.
//  - IOM/National Academies DRIs for Vitamin A (2001): the 12:1 factor (was 6:1).
//  - WHO: vitamin A deficiency = leading preventable cause of childhood blindness.
//  - RAF Museum (B. Legate) / Smithsonian: the radar history + the contested "intent".

let pass = 0, fail = 0;
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
const ok = (name, cond) => { if (cond) { pass++; } else { fail++; console.error('  FAIL:', name); } };

console.log('THE CARROT AND THE CAT\'S EYES — verifier\n');

// ── the cited facts (must match FACTS in the page) ───────────────────────────
const FACTS = {
  rdaMenRAE: 900, rdaWomenRAE: 700, convFood: 12, carrotRAE: 459,
  ulRetinol: 3000, adequacyRAE: 900
};

// ── 1. the conversion arithmetic ─────────────────────────────────────────────
{
  // ½ cup carrots = 459 µg RAE; back-compute its dietary β-carotene mass at 12:1.
  const betaCarotene = FACTS.carrotRAE * FACTS.convFood;
  ok('½ cup carrots back-computes to ~5,508 µg β-carotene (459×12)', approx(betaCarotene, 5508));
  ok('…which the page rounds to ~5,500 µg', Math.round(betaCarotene / 100) * 100 === 5500);
  // that half-cup as a fraction of the male RDA (the "~51%" claim)
  const frac = FACTS.carrotRAE / FACTS.rdaMenRAE;
  ok('½ cup ≈ 51% of the 900 µg male RDA', Math.round(frac * 100) === 51);
  ok('…and ~66% of the 700 µg female RDA', Math.round((FACTS.carrotRAE / FACTS.rdaWomenRAE) * 100) === 66);
  // the old vs new conversion factor
  ok('the IOM 2001 factor (12) is double the old retinol-equivalent factor (6)', FACTS.convFood === 2 * 6);
  // preformed-retinol UL is above the RDA but a real ceiling; β-carotene has none
  ok('UL for preformed retinol (3000) exceeds the RDA (900)', FACTS.ulRetinol > FACTS.rdaMenRAE);
}

// ── 2. the dose–response MODEL (ported verbatim from the page) ────────────────
// night-vision capability as a fraction of a healthy eye.
function realCapability(rae) {
  const a = FACTS.adequacyRAE, half = a * 0.16;
  const v = rae / (rae + half);
  const vAdeq = a / (a + half);
  return Math.min(1, v / vAdeq);
}
function mythCapability(rae) { return rae / FACTS.adequacyRAE; }

{
  // property A: impaired when deficient (deep deficiency ≪ a healthy eye)
  ok('deep deficiency (100 µg RAE) is well below normal (<70%)', realCapability(100) < 0.70);
  ok('severe deficiency (40 µg RAE) is badly impaired (<45%)', realCapability(40) < 0.45);
  // property B: reaches ~100% by the RDA
  ok('capability at the RDA is ~100% (≥0.99)', realCapability(FACTS.adequacyRAE) >= 0.99);
  // property C: HARD saturation — no gain above adequacy
  ok('capability never exceeds 1.0', realCapability(FACTS.adequacyRAE * 10) <= 1 + 1e-12);
  ok('4× RDA gives no more night vision than the RDA', approx(realCapability(FACTS.adequacyRAE * 4), realCapability(FACTS.adequacyRAE), 1e-9) || realCapability(FACTS.adequacyRAE * 4) === 1);
  // property D: monotone non-decreasing across the whole sweep
  {
    let mono = true, prev = -1;
    for (let rae = 0; rae <= FACTS.adequacyRAE * 10; rae += 25) {
      const c = realCapability(rae);
      if (c < prev - 1e-12) { mono = false; break; }
      prev = c;
    }
    ok('the real curve is monotone non-decreasing (rise then flat, never dips)', mono);
  }
  // property E: the MYTH line keeps climbing past 1.0 forever (the lie)
  ok('the myth line hits 1.0 exactly at the RDA', approx(mythCapability(FACTS.adequacyRAE), 1));
  ok('the myth line promises 2.0 (200%) at twice the RDA — impossible', approx(mythCapability(FACTS.adequacyRAE * 2), 2));
  ok('the gap (myth − real) is ~0 while deficient, and grows only past adequacy',
     mythCapability(200) - realCapability(200) < realCapability(200) && // small while low
     (mythCapability(FACTS.adequacyRAE * 4) - realCapability(FACTS.adequacyRAE * 4)) > 2.5); // large when high
}

// ── 3. cross-check: the shipped page carries these exact figures ─────────────
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
const pagePath = path.resolve(here, '../../public/strata/do-carrots-improve-eyesight/index.html');
if (fs.existsSync(pagePath)) {
  const html = fs.readFileSync(pagePath, 'utf8');
  const norm = html.replace(/&nbsp;/g, ' ').replace(/&micro;/g, 'µ').replace(/&frac12;/g, '½');
  const has = (re, label) => ok(`page states ${label}`, re.test(norm));
  has(/900\s*µg\s*RAE/i, 'the 900 µg RAE male RDA');
  has(/700/, 'the 700 µg female RDA');
  has(/12\s*:\s*1/, 'the 12:1 conversion');
  has(/459\s*µg\s*RAE/i, 'the 459 µg RAE half-cup figure');
  has(/5,?500/, 'the ~5,500 µg β-carotene back-computation');
  has(/3,?000\s*µg\/day/i, 'the 3,000 µg/day retinol UL');
  has(/11-cis-retinal/i, 'the 11-cis-retinal chromophore (not "retinol")');
  has(/rhodopsin/i, 'rhodopsin');
  has(/19\/20\s*Nov\s*1940/i, 'the 19/20 Nov 1940 first AI Mk IV kill');
  has(/Dec\s*1939/i, 'Freya operational Dec 1939 (radar predated the myth)');
  has(/never set out to use it to fool the Germans/i, 'the RAF Museum curator\'s load-bearing quote');
  // the FACTS block in the page must match this file
  has(/carrotRAE:\s*459/, 'the page FACTS.carrotRAE = 459');
  has(/convFood:\s*12/, 'the page FACTS.convFood = 12');
  has(/rdaMenRAE:\s*900/, 'the page FACTS.rdaMenRAE = 900');
} else {
  console.log('  (page not found — skipping HTML cross-check)');
}

console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass}/${pass + fail} checks`);
process.exit(fail === 0 ? 0 : 1);
