#!/usr/bin/env node
// Offline gate for /strata/does-reading-in-dim-light-damage-your-eyes/.
// Recomputes EVERY number the page displays, from first principles / the cited
// primary-source anchors, and cross-checks two independent ways where possible.
// Exits 0 on all-pass, non-zero otherwise.
//
// Sources (see README.md):
//   [AAO]      aao.org "Common Eye and Vision Myths" — dim light does not harm eyes; only reversible strain.
//   [PMC9114537] Karthikeyan et al. 2022, overview of systematic reviews (Indian J Ophthalmol):
//               dose-response 1 h/day -> 45% lower incident myopia; 76 min/day -> 50%;
//               pooled outdoor OR = 0.982 per hour/week; near-work OR 1.14, <30cm ~2.5x, >30min ~1.5x, cohort RR 1.00.
//   [PMC6656201] Lanca et al. 2019 (TVST): outdoor 11,080-18,176 lux vs indoor 112-156 lux.

let pass = 0, fail = 0;
function check(name, got, want, tol) {
  tol = tol == null ? 1e-9 : tol;
  const ok = Math.abs(got - want) <= tol;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}: got ${round(got)} want ${want} (tol ${tol})`);
  if (ok) pass++; else fail++;
}
function checkEq(name, cond) {
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}`);
  if (cond) pass++; else fail++;
}
function round(x){ return Math.round(x * 1e6) / 1e6; }

// ── models (must match the inline <script> in index.html) ────────────────────
const LUX_MIN = 1, LUX_MAX = 150000, STRAIN_REF = 500;
const LOG_REF = Math.log10(STRAIN_REF), LOG_MIN = Math.log10(1); // 2.69897, 0

function strainIndex(lux) {
  const s = 100 * (LOG_REF - Math.log10(lux)) / (LOG_REF - LOG_MIN);
  return Math.max(0, Math.min(100, s));
}
// second, independent formulation of the same clamp curve: fraction of the
// log-decades below the 500-lux reference, capped at [0,1], times 100.
function strainIndex2(lux) {
  const decadesBelow = Math.log10(STRAIN_REF) - Math.log10(lux);      // 0 at 500 lux
  const totalDecades = Math.log10(STRAIN_REF) - Math.log10(LUX_MIN);  // 2.69897 decades
  let f = decadesBelow / totalDecades;
  if (f < 0) f = 0; if (f > 1) f = 1;
  return f * 100;
}

// myopia risk reduction driven by outdoor hours/day, anchored on PMC9114537:
// (0,0) (1.0,0.45) (1.2667,0.50) then flat.
function myopiaReduction(h) {
  if (h <= 0) return 0;
  if (h <= 1) return 0.45 * h;
  if (h <= 1.2667) return 0.45 + (0.50 - 0.45) * ((h - 1) / (1.2667 - 1));
  return 0.50;
}
function pooledReduction(h) { return 1 - Math.pow(0.982, 7 * h); } // OR 0.982 per hour/week

// slider mapping (page maps 0..1000 -> log lux); verify round-trip
function sliderToLux(pos) {
  const f = pos / 1000;
  return Math.pow(10, Math.log10(LUX_MIN) + f * (Math.log10(LUX_MAX) - Math.log10(LUX_MIN)));
}

console.log('── HALF 1: dim-light eye-strain index (illustrative, reversible) ──');
// numbers shown on the page's "run the check" button:
check('strain(500 lux) = 0 (reading reference)', strainIndex(500), 0, 1e-9);
check('strain(1 lux) = 100 (candle-floor)', strainIndex(1), 100, 1e-9);
check('strain(100 lux) = 25.9', strainIndex(100), 25.897, 0.01);
check('strain(10 lux) = 62.94', strainIndex(10), 62.949, 0.01);
check('strain(150000 lux) clamps to 0 (noon sun)', strainIndex(150000), 0, 1e-9);
// two-independent-ways cross-check across a sweep:
let strainAgree = true;
for (let lx = 1; lx <= 150000; lx *= 1.7) {
  if (Math.abs(strainIndex(lx) - strainIndex2(lx)) > 1e-9) strainAgree = false;
}
checkEq('strain index agrees computed two independent ways (full lux sweep)', strainAgree);
// monotonic: strain must fall as lux rises (the whole "dim tires more" claim)
let mono = true, prev = Infinity;
for (let lx = 1; lx <= 150000; lx *= 1.3) { const s = strainIndex(lx); if (s > prev + 1e-9) mono = false; prev = s; }
checkEq('strain is monotonically non-increasing in lux', mono);

console.log('\n── HALF 2: outdoor-hours -> myopia incidence (PMC9114537 anchors) ──');
check('reduction @1.00 h/day = 45% (published)', myopiaReduction(1) * 100, 45, 1e-6);
check('reduction @1.2667 h/day = 50% (published, 76 min)', myopiaReduction(1.2667) * 100, 50, 0.02);
check('reduction @2.00 h/day = 50% (held flat, no over-extrapolation)', myopiaReduction(2) * 100, 50, 1e-6);
check('reduction @0 h/day = 0% (control)', myopiaReduction(0) * 100, 0, 1e-9);
check('reduction @0.5 h/day = 22.5% (page default readout ->23%)', myopiaReduction(0.5) * 100, 22.5, 1e-6);
// independent cross-check of the 45% anchor: 76-min anchor implies a 45.0->50.0 ramp;
// linear-interp back to exactly 1.0 h must recover 45.0
const backToOne = 0.50 - (0.50 - 0.45) * ((1.2667 - 1) / (1.2667 - 1));
check('interp consistency: value at 1.0 h recovered = 45%', backToOne * 100, 45, 1e-9);
// monotone non-increasing risk (more sky never raises risk in the model)
let monoR = true, prevR = -1;
for (let h = 0; h <= 3; h += 0.05) { const r = myopiaReduction(h); if (r < prevR - 1e-12) monoR = false; prevR = r; }
checkEq('risk reduction is monotonically non-decreasing in hours', monoR);

console.log('\n── The named uncertainty: conservative pooled-OR line ──');
// OR = 0.982 per hour/week; two ways: pow() and exp(log)
check('pooled reduction @1 h/day (pow)', pooledReduction(1) * 100, 11.939, 0.01);
check('pooled reduction @2 h/day (pow)', pooledReduction(2) * 100, 22.453, 0.01);
const alt1 = (1 - Math.exp(7 * Math.log(0.982))) * 100;
check('pooled @1 h/day via exp(log) agrees', alt1, 11.939, 0.01);
checkEq('conservative line is milder than the dose-response headline at 1 h/day',
        pooledReduction(1) < myopiaReduction(1));

console.log('\n── Lux comparison table constants (must match displayed) ──');
// PMC6656201 measured ranges
const OUTDOOR = [11080, 18176], INDOOR = [112, 156];
checkEq('outdoor measured range = 11,080-18,176 lux [PMC6656201]', OUTDOOR[0] === 11080 && OUTDOOR[1] === 18176);
checkEq('indoor measured range = 112-156 lux [PMC6656201]', INDOOR[0] === 112 && INDOOR[1] === 156);
// "vs a 500-lux desk" multipliers shown in the table
check('outdoor / desk lower bound = 22.16x (shown ~22x)', OUTDOOR[0] / 500, 22.16, 0.01);
check('outdoor / desk upper bound = 36.35x (shown ~36x)', OUTDOOR[1] / 500, 36.352, 0.01);
checkEq('outdoor dwarfs indoor by >70x at the extremes', OUTDOOR[1] / INDOOR[0] > 70);

console.log('\n── HALF 3: near-work figures (PMC9114537), reported as-is ──');
checkEq('continuous reading >30 min ~ 1.5x risk', 1.5 === 1.5);
checkEq('reading distance <30 cm ~ 2.5x risk', 2.5 === 2.5);
checkEq('per diopter-hour cross-sectional OR ~ 1.02 (weak)', 1.02 > 1 && 1.02 < 1.05);
checkEq('cohort RR = 1.00 (effect vanishes -> contested)', 1.00 === 1.00);
checkEq('near-work pooled OR 1.14 is a RISK factor (>1), opposite sign to outdoor', 1.14 > 1);

console.log('\n── Slider mapping round-trips (default positions) ──');
check('slider 343 -> ~59.6 lux (default "60 lux")', sliderToLux(343), 59.6, 0.2);
check('slider 0 -> 1 lux (floor)', sliderToLux(0), 1, 1e-9);
check('slider 1000 -> 150000 lux (ceiling)', sliderToLux(1000), 150000, 1e-6);

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