#!/usr/bin/env node
/*
 * verify-the-crossover-at-twenty-two-degrees.mjs
 *
 * Independent offline check of every load-bearing number on
 *   public/strata/the-crossover-at-twenty-two-degrees/index.html
 *
 * It shares no code with the page. It re-derives the photosynthesis model from
 * the published constants, re-reads the three datasets the page ships (by
 * parsing them out of the HTML, so the data being checked really is the data
 * being served), and re-runs every statistic the page computes in the browser.
 *
 * Node 22 built-ins only. Exit 0 = every assertion held.
 *
 * Usage:  node research/the-crossover-at-twenty-two-degrees/verify-the-crossover-at-twenty-two-degrees.mjs
 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PAGE = path.resolve(HERE, '../../public/strata/the-crossover-at-twenty-two-degrees/index.html');

let pass = 0;
const fails = [];
function ok(name, cond, detail) {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  (' + detail + ')' : ''}`); }
  else { fails.push(name + (detail ? '  (' + detail + ')' : '')); console.log(`  FAIL ${name}${detail ? '  (' + detail + ')' : ''}`); }
}
function near(name, got, want, tol, unit) {
  ok(name, Math.abs(got - want) <= tol,
    `got ${fmt(got)}${unit || ''}, want ${fmt(want)}${unit || ''} +/- ${fmt(tol)}`);
}
function fmt(x) { return (typeof x === 'number' && isFinite(x)) ? (Math.abs(x) >= 1e4 || (Math.abs(x) < 1e-3 && x !== 0) ? x.toExponential(3) : +x.toPrecision(8)) : String(x); }
function head(s) { console.log('\n' + s); }

/* ------------------------------------------------------------------ */
/* 0. published constants, transcribed here, not imported             */
/* ------------------------------------------------------------------ */
const R = 0.008314;                       // kJ / mol / K
// Bernacchi, Portis, Nakano, von Caemmerer & Long (2002) Plant Physiol 130:1992-1998,
// Table I: chloroplastic-CO2 basis, Arrhenius form  parameter = exp(c - dHa/(R Tk)).
const cG = 13.49, dG = 24.46;             // Gamma*  -> umol/mol
const cKc = 38.28, dKc = 80.99;           // Kc      -> umol/mol
const cKo = 14.68, dKo = 23.72;           // Ko      -> mmol/mol
const PRINTED_25 = { G: 37.43, Kc: 272.38, Ko: 165.82 };          // as printed in Table I
const SHARKEY_PA = { G: 3.743, Kc: 27.238, Ko: 16.582 };          // as usually quoted, in Pa / kPa
// Ehleringer & Bjorkman (1977) Plant Physiol 59:86-90, at 30 C
const EB = { c3_21: 0.0524, c3_21sd: 0.0014, c3_2: 0.0733, c3_2sd: 0.0008,
             c4_21: 0.0534, c4_21sd: 0.0009, c4_2: 0.0538, c4_2sd: 0.0011 };
const CI_CAL = 330;                       // the page's one free calibration choice

const arr = (c, d, T) => Math.exp(c - d / (R * (T + 273.15)));
const gstar = (T, o2 = 0.21) => arr(cG, dG, T) * (o2 / 0.21);
const kcT = (T) => arr(cKc, dKc, T);
const koT = (T) => arr(cKo, dKo, T) * 1000;
const fr = (T, Ci, o2) => { const g = gstar(T, o2); return (Ci - g) / (Ci + 2 * g); };
const PHIMAX = EB.c3_2 / fr(30, CI_CAL, 0.02);
const phi3 = (T, Ci, o2) => PHIMAX * fr(T, Ci, o2);

function bisect(f, lo, hi, iters = 200) {
  if (!(f(lo) > 0 && f(hi) < 0)) return null;
  for (let i = 0; i < iters; i++) { const m = (lo + hi) / 2; if (f(m) > 0) lo = m; else hi = m; }
  return (lo + hi) / 2;
}
const crossT = (Ci, o2, phi4) => bisect((T) => phi3(T, Ci, o2) - phi4, -60, 120);

/* ------------------------------------------------------------------ */
head('1. Arrhenius constants reproduce the printed 25 C column');
/* ------------------------------------------------------------------ */
near('Gamma*(25 C) from (c, dHa)', gstar(25), PRINTED_25.G, 0.01, ' umol/mol');
near('Kc(25 C) from (c, dHa)', kcT(25), PRINTED_25.Kc, 0.05, ' umol/mol');
near('Ko(25 C) from (c, dHa)', koT(25) / 1000, PRINTED_25.Ko, 0.02, ' mmol/mol');
// the mole-fraction table converts to the pascal-basis table at exactly 100 kPa
near('Gamma* in Pa at the 100 kPa reference', gstar(25) / 10, SHARKEY_PA.G, 0.002, ' Pa');
near('Kc in Pa', kcT(25) / 10, SHARKEY_PA.Kc, 0.005, ' Pa');
near('Ko in kPa', koT(25) / 10000, SHARKEY_PA.Ko, 0.002, ' kPa');
// and the log-offset between the two published c values is exactly ln(10)
near('c offset Gamma*, mole fraction vs Pa', cG - Math.log(10), 11.187, 0.001);
near('c offset Kc', cKc - Math.log(10), 35.9774, 0.001);
near('c offset Ko', cKo - Math.log(10), 12.3774, 0.001);

// the page's prose claim about how fast Gamma* rises
near('Gamma*(45 C)', gstar(45), 69.60, 0.01, ' umol/mol');
ok('Gamma* at 45 C is "nearly twice" its 25 C value', gstar(45) / gstar(25) > 1.8 && gstar(45) / gstar(25) < 2.0,
  `ratio ${fmt(gstar(45) / gstar(25))}`);

/* ------------------------------------------------------------------ */
head('2. the 1977 oxygen-switch cross-check');
/* ------------------------------------------------------------------ */
const ratio = (T, Ci) => fr(T, Ci, 0.21) / fr(T, Ci, 0.02);
const predicted = ratio(30, CI_CAL);
const measured = EB.c3_21 / EB.c3_2;
const measSD = measured * Math.hypot(EB.c3_21sd / EB.c3_21, EB.c3_2sd / EB.c3_2);
near('predicted phi(21%)/phi(2%) at 30 C, Ci = 330', predicted, 0.71039, 2e-5);
near('measured ratio 0.0524/0.0733', measured, 0.71487, 5e-5);
near('propagated SD of the measured ratio', measSD, 0.02063, 5e-5);
ok('prediction lies inside 2 SD of the measurement',
  Math.abs(predicted - measured) < 2 * measSD,
  `gap ${fmt(Math.abs(predicted - measured))} vs 2 SD = ${fmt(2 * measSD)}`);
const ciExact = bisect((C) => measured - ratio(30, C), 60, 3000);
near('Ci that makes the agreement exact', ciExact, 336.47, 0.05, ' ppm');
ok('that Ci is within 1% of the 1977 Mauna Loa annual mean (333.84 ppm)',
  Math.abs(ciExact - 333.84) / 333.84 < 0.01, `${fmt(100 * (ciExact - 333.84) / 333.84)} %`);
// the ratio is weakly sensitive to that free choice
const rlo = ratio(30, 320), rhi = ratio(30, 350);
ok('ratio moves less than 4% over Ci 320 to 350 ppm',
  Math.abs(rhi - rlo) / predicted < 0.04, `${fmt(100 * (rhi - rlo) / predicted)} %`);
// The falsification criterion the page states is bounded to the plausible 1970s laboratory range.
// It is NOT true at every Ci, and the page must not claim that it is: here is where it stops.
{
  const inside = (C) => Math.abs(ratio(30, C) - measured) < 2 * measSD;
  let allIn = true;
  for (let C = 320; C <= 350; C += 1) if (!inside(C)) allIn = false;
  ok('agreement holds within 2 SD across the whole 320 to 350 ppm range the page defends', allIn,
    `320 ppm ${fmt(Math.abs(ratio(30, 320) - measured) / measSD)} SD, 350 ppm ${fmt(Math.abs(ratio(30, 350) - measured) / measSD)} SD`);
  const bandLo = bisect((C) => ratio(30, C) - (measured - 2 * measSD), 3000, 60);
  const bandHi = bisect((C) => (measured + 2 * measSD) - ratio(30, C), 60, 3000);
  near('lower end of the Ci band where the 2 SD agreement survives', bandLo, 283.67, 0.05, ' ppm');
  near('the ratio at that lower end is exactly two SD below the measurement',
    (measured - ratio(30, bandLo)) / measSD, 2, 1e-6, ' SD');
  near('upper end of the same band', bandHi, 407.22, 0.05, ' ppm');
  ok('the 320 to 350 ppm range the page defends sits strictly inside that band', bandLo < 320 && bandHi > 350,
    `${fmt(bandLo)} to ${fmt(bandHi)} ppm`);
  ok('the agreement genuinely fails at both ends of the instrument-2 slider, as the page now says',
    !inside(250) && !inside(450),
    `250 ppm ${fmt(Math.abs(ratio(30, 250) - measured) / measSD)} SD, 450 ppm ${fmt(Math.abs(ratio(30, 450) - measured) / measSD)} SD`);
}
// the C4 pathway does not respond to the same switch
const c4chg = (EB.c4_2 - EB.c4_21) / EB.c4_21;
const c4sd = Math.hypot(EB.c4_21sd, EB.c4_2sd) / EB.c4_21;
near('C4 change on removing 19 points of O2', 100 * c4chg, 0.749, 0.01, ' %');
ok('that C4 change is smaller than its own propagated SD', Math.abs(c4chg) < c4sd,
  `${fmt(100 * c4chg)} % vs SD ${fmt(100 * c4sd)} %`);

/* ------------------------------------------------------------------ */
head('3. the quanta ledger');
/* ------------------------------------------------------------------ */
near('phi_max (the single calibrated constant)', PHIMAX, 0.076131, 1e-6);
near('photorespiration-free C3 ceiling', 1 / PHIMAX, 13.1352, 1e-3, ' quanta/CO2');
near('C4 cost', 1 / EB.c4_21, 18.7266, 1e-3, ' quanta/CO2');
near('C4 pump surcharge', 1 / EB.c4_21 - 1 / PHIMAX, 5.5913, 1e-3, ' quanta/CO2');

/* ------------------------------------------------------------------ */
head('4. crossover temperatures, and the same crossing found two ways');
/* ------------------------------------------------------------------ */
const CROSS = [[150, 5.326], [180, 10.216], [200, 13.121], [280, 22.811], [330, 27.785],
               [340, 28.707], [350, 29.607], [415, 35.009], [427.35, 35.959], [560, 44.995], [1000, 66.277]];
let prev = -Infinity, mono = true;
for (const [ca, want] of CROSS) {
  const got = crossT(ca, 0.21, EB.c4_21);
  near(`crossover at ${ca} ppm`, got, want, 0.01, ' C');
  if (got <= prev) mono = false;
  prev = got;
}
ok('crossover is strictly increasing in atmospheric CO2', mono);
// route two: the temperature at which the photorespiratory tax equals the fixed surcharge
const base = 1 / PHIMAX, surch = 1 / EB.c4_21 - base;
for (const ca of [180, 280, 340, 415]) {
  const taxAt = (T) => { const v = phi3(T, ca, 0.21); return v > 0 ? 1 / v - base : Infinity; };
  const root = bisect((T) => surch - taxAt(T), -60, 120);
  const direct = crossT(ca, 0.21, EB.c4_21);
  ok(`two routes agree at ${ca} ppm`, Math.abs(root - direct) < 1e-9,
    `difference ${fmt(Math.abs(root - direct))} C`);
}
// what it takes to reach the published 22 C at Collatz's 35 Pa (350 ppm at 100 kPa)
const cica22 = bisect((r) => 22 - (crossT(350 * r, 0.21, EB.c4_21) ?? -1e9), 0.2, 1.0);
near('Ci/Ca needed to put the crossing at 22 C, 350 ppm', cica22, 0.7784, 0.001);
const phi4_22 = PHIMAX * fr(22, 350, 0.21);
near('phi_C4 needed instead, same target', phi4_22, 0.05758, 1e-4);
ok('that phi_C4 is above the measured C4 mean of 0.0534', phi4_22 > EB.c4_21);
near('gap between this model at 350 ppm and Collatz 22 C', crossT(350, 0.21, EB.c4_21) - 22, 7.607, 0.01, ' C');
// total pressure cancels out of the crossover (Ci and Gamma* scale together)
{
  const withP = (P) => {
    const g = (T) => (arr(cG - Math.log(10), dG, T)) * (0.21 * P * 1000 / 21000);   // Pa
    const Ci = 340e-6 * P * 1000;                                                    // Pa
    const ph = (T) => PHIMAX * (Ci - g(T)) / (Ci + 2 * g(T));
    return bisect((T) => ph(T) - EB.c4_21, -60, 120);
  };
  ok('crossover independent of total pressure', Math.abs(withP(100) - withP(70)) < 1e-9,
    `100 kPa ${fmt(withP(100))} C vs 70 kPa ${fmt(withP(70))} C`);
}

/* ------------------------------------------------------------------ */
head('4b. the other parameter basis, which the page exposes as a selector');
/* ------------------------------------------------------------------ */
// Bernacchi et al. (2001), intercellular basis. SECOND-HAND constants: the 2001 paper's full
// text was not obtained. Reproduced here to check the page's own comparison rows, and because
// the independent blinded re-derivation in BLIND-REDERIVATION.md used this basis as its primary.
const gCi = (T, o2 = 0.21) => 42.75 * Math.exp((37.83 / R) * (1 / 298.15 - 1 / (T + 273.15))) * (o2 / 0.21);
const frCi = (T, Ci, o2) => { const g = gCi(T, o2); return (Ci - g) / (Ci + 2 * g); };
near('Ci-basis Gamma*(30 C, 21% O2)', gCi(30), 54.9861, 0.001, ' umol/mol');
near('Ci-basis O2 ratio at 30 C, Ci = 330', frCi(30, 330, 0.21) / frCi(30, 330, 0.02), 0.655308, 1e-5);
{
  const pm = EB.c3_2 / frCi(30, CI_CAL, 0.02);
  const xc = bisect((T) => pm * frCi(T, 340, 0.21) - EB.c4_21, -60, 120);
  near('Ci-basis crossover at 340 ppm', xc, 25.2984, 0.001, ' C');
  near('the two bases differ at 340 ppm by', crossT(340, 0.21, EB.c4_21) - xc, 3.408, 0.01, ' C');
  ok('the Cc basis fits the measured 1977 O2 ratio better than the Ci basis does',
    Math.abs(predicted - measured) < Math.abs(frCi(30, 330, 0.21) / frCi(30, 330, 0.02) - measured),
    `Cc gap ${fmt(Math.abs(predicted - measured))} vs Ci gap ${fmt(Math.abs(frCi(30, 330, 0.21) / frCi(30, 330, 0.02) - measured))}`);
  // Not a tautology: this reads the blinded worker's own record off disk and checks that the
  // three numbers asserted just above are the numbers it actually reported. If BLIND-REDERIVATION.md
  // ever says something else, this fails.
  const blindPath = path.resolve(HERE, 'BLIND-REDERIVATION.md');
  const blind = fs.existsSync(blindPath) ? fs.readFileSync(blindPath, 'utf8') : '';
  const blindWants = ['0.655308', '25.2984', '54.9861'];
  ok('the blinded re-derivation on disk reports these same three values',
    blind.length > 0 && blindWants.every((s) => blind.includes(s)),
    blindWants.map((s) => s + (blind.includes(s) ? ' found' : ' MISSING')).join(', '));
}
// the pressure-convention fork the blinded worker flagged
near('3.743 Pa as a mole fraction at a 100 kPa reference', 3.743 * 10, 37.43, 0.001, ' umol/mol');
near('3.743 Pa as a mole fraction at 101.325 kPa', 3.743 / 101.325 * 1000, 36.94, 0.01, ' umol/mol');

/* ------------------------------------------------------------------ */
head('5. the Zhu, Long & Ort (2010) Figure 2 cascade');
/* ------------------------------------------------------------------ */
const CASC = [
  ['outside PAR', 100, 51.3, 48.7], ['reflected/transmitted', 48.7, 4.9, 43.8],
  ['photochemical inefficiency', 43.8, 6.6, 37.2], ['thermodynamic limit', 37.2, 13.8, 26.0],
  ['C3 carbohydrate biosynthesis', 26.0, 13.4, 12.6], ['C3 photorespiration', 12.6, 6.1, 6.5],
  ['C3 respiration', 6.5, 1.9, 4.6], ['C4 carbohydrate biosynthesis', 26.0, 17.5, 8.5],
  ['C4 photorespiration', 8.5, 0, 8.5], ['C4 respiration', 8.5, 2.5, 6.0]
];
let closed = 0, open = [];
for (const [n, from, loss, next] of CASC) {
  if (Math.abs(from - loss - next) < 0.05) closed++; else open.push(n);
}
ok('exactly nine of the ten published cascade steps close', closed === 9, `${closed} closed`);
ok('the one that does not is the thermodynamic-limit step', open.length === 1 && open[0] === 'thermodynamic limit',
  open.join(', ') || 'none');
near('C3 ceiling on a PAR-only basis', 100 * 4.6 / 48.7, 9.4, 0.06, ' %');
near('C4 ceiling on a PAR-only basis', 100 * 6.0 / 48.7, 12.3, 0.06, ' %');
{
  const k = 13 / 8, g25 = gstar(25), Cc = g25 * (2 + k) / (k - 1);
  near('Cc implied by the review "8 to 13 photons" sentence', Cc / 387, 0.5610, 0.001);
  ok('that implied Cc/Ca is below the 0.7 quoted elsewhere in the same paper', Cc / 387 < 0.7);
}

/* ------------------------------------------------------------------ */
head('6. the datasets the page actually ships');
/* ------------------------------------------------------------------ */
const html = fs.readFileSync(PAGE, 'utf8');
ok('page ends with the load-bearing closing tags', /<\/script>\s*<\/body>\s*<\/html>/.test(html));
{
  // The 22-25 C species-pair crossover is real and is in the abstract of Monson, Littlejohn &
  // Williams (1982), retrieved verbatim 2026-08-07. It was previously attributed on this page to
  // Ehleringer (1978), whose abstract does not contain it, and was therefore listed as
  // unverifiable. The page must now carry the correct attribution and must NOT still carry the
  // withdrawn "not made anywhere on this page" disclaimer.
  const ag = (html.match(/Agropyron/gi) || []).length;
  const bo = (html.match(/Bouteloua/gi) || []).length;
  ok('the species-pair crossover is stated and attributed to Monson et al. 1982',
    ag >= 2 && bo >= 2 &&
    html.includes('10.1007/BF00040713') &&
    html.includes('Monson, Littlejohn &amp; Williams 1982') &&
    !html.includes('The claim is therefore not made anywhere on this page'),
    `Agropyron x${ag}, Bouteloua x${bo}`);
  // The load-bearing false claim this page used to make: that the gap between its own leaf
  // temperature and Collatz's air temperature IS a leaf-minus-air offset. Monson measures a LEAF
  // crossing at this model's own 340 ppm, so that reading is refuted and must stay gone.
  ok('the withdrawn leaf-minus-air reconciliation is not reasserted',
    !/roughly the amount by\s+which a sunlit tropical leaf exceeds the monthly mean air/.test(html) &&
    !html.includes('implied sunlit-leaf-minus-monthly-mean-air offset'));
  // and the arithmetic that replaces it: the phi_C4 window that lands this model inside Monson's
  // measured 22-25 C at 340 ppm, Ci/Ca = 1. Asserted as a two-sided bracket, not a tolerance.
  {
    const lo = PHIMAX * fr(25, 340, 0.21);   // low end of phi4 -> high end of T
    const hi = PHIMAX * fr(22, 340, 0.21);
    near('phi_C4 that puts the crossing at Monson 25 C, 340 ppm', lo, 0.05553, 1e-4);
    near('phi_C4 that puts the crossing at Monson 22 C, 340 ppm', hi, 0.05717, 1e-4);
    ok('that window sits strictly above the 0.0534 the page ships',
      lo > EB.c4_21, `${fmt(lo)} > ${EB.c4_21}`);
    // Ehleringer & Pearcy (1983) C4 GRASS subtype means, 330 uL/L, 21% O2, 30 C.
    const EP83_C4_GRASS = { nadme: 0.060, pck: 0.064, nadpme: 0.065 };
    ok('and strictly below every C4 grass subtype mean in Ehleringer & Pearcy 1983',
      hi < Math.min(EP83_C4_GRASS.nadme, EP83_C4_GRASS.pck, EP83_C4_GRASS.nadpme),
      `${fmt(hi)} < ${EP83_C4_GRASS.nadme}`);
    // the phi_C4 slider must be able to reach those published grass values
    const smax = Number((html.match(/id="s1p4"[^>]*max="([\d.]+)"/) || [])[1]);
    ok('the phi_C4 slider reaches the published C4 grass range',
      smax >= EP83_C4_GRASS.nadpme, `slider max ${smax} against 0.065`);
  }
}
{
  // the dek's claim about where the crossing leaves instrument 1's axis
  const tmax = Number((html.match(/TMIN\s*=\s*0,\s*TMAX\s*=\s*(\d+)/) || [])[1]);
  ok('instrument 1 axis top read from the page', tmax === 45, String(tmax));
  ok('at 560 ppm the crossing is still on the chart, just barely',
    crossT(560, 0.21, EB.c4_21) < tmax && tmax - crossT(560, 0.21, EB.c4_21) < 0.02,
    `${fmt(crossT(560, 0.21, EB.c4_21))} C against a ${tmax} C axis`);
  ok('it genuinely leaves the axis just above that', crossT(561, 0.21, EB.c4_21) > tmax,
    `561 ppm -> ${fmt(crossT(561, 0.21, EB.c4_21))} C`);
}
ok('page exposes the parameter-basis free choice as a control, not a footnote',
  html.includes('id="s1basis"') && html.includes('Bernacchi et al. 2001, intercellular'));
ok('page carries the published quantum yields verbatim',
  html.includes('0.0524') && html.includes('0.0733') && html.includes('0.0534') && html.includes('0.0538'));
{
  // citations corrected in the fix pass, each confirmed against a primary record on 2026-07-24
  ok('Henry\'s-law values cite Sander (2023) v5.0.0, not the superseded 2015 edition',
    html.includes('10.5194/acp-23-10901-2023') && !html.includes('10.5194/acp-15-4399-2015'));
  ok('the Ehleringer & Bjorkman title carries its subtitle as printed',
    html.includes('Dependence on Temperature, CO'));
  ok('the Bond et al. fire quotation is the complete source sentence, not a truncation',
    /"Without fire, closed forests would double from 27% to 56% of\s+vegetated grid cells, mostly at the expense of C<sub>4<\/sub> plants but also of C<sub>3<\/sub>\s+shrubs and grasses in cooler climates\."/.test(html));
  ok('the Pearcy & Troughton C4-tree source is cited where C4 trees are mentioned',
    html.includes('10.1104/pp.55.6.1054') && html.includes('essentially every tree'));
}
{
  // the live-region design the check panel commits to: six headline tiles plus six prose
  // paragraphs, and nothing else announcing. If someone adds a stray aria-live, this fails.
  const live = (html.match(/role="status" aria-live="polite"/g) || []).length;
  const alts = (html.match(/id="alt[1-6]" role="status" aria-live="polite"/g) || []).length;
  ok('exactly twelve live regions: six instrument summaries and six headline tiles',
    live === 12 && alts === 6, `${live} live regions, ${alts} of them prose summaries`);
  ok('the check panel states that design rather than leaving it to be discovered',
    html.includes('How the changing numbers are announced'));
}

function grab(re, what) {
  const m = html.match(re);
  if (!m) { throw new Error('could not find ' + what + ' in the page'); }
  return m[1];
}
const WC = {
  H: +grab(/var WC=\{H:(\d+)/, 'WC.H'),
  W: +grab(/var WC=\{H:\d+,W:(\d+)/, 'WC.W'),
  n: +grab(/var WC=\{H:\d+,W:\d+,n:(\d+)/, 'WC.n'),
  mask: grab(/mask:'([A-Za-z0-9+/=]+)'/, 'WC.mask'),
  t: grab(/,t:'([A-Za-z0-9+/=]+)'/, 'WC.t'),
  p: grab(/,p:'([A-Za-z0-9+/=]+)'/, 'WC.p'),
  lf: grab(/,lf:'([A-Za-z0-9+/=]+)'/, 'WC.lf')
};
const CEN = JSON.parse(grab(/var CEN=(\[[^\]]*\]);/, 'CEN'));
const RUB = JSON.parse(grab(/var RUB=(\[\[[\s\S]*?\]\]);/, 'RUB'));

ok('WorldClim grid is 180 x 90 two-degree cells', WC.H === 90 && WC.W === 180);
ok('WorldClim grid carries 7156 land cells', WC.n === 7156, String(WC.n));
const tB = Buffer.from(WC.t, 'base64'), pB = Buffer.from(WC.p, 'base64'),
      fB = Buffer.from(WC.lf, 'base64'), mB = Buffer.from(WC.mask, 'base64');
ok('temperature blob is 12 bytes per land cell', tB.length === WC.n * 12, String(tB.length));
ok('precipitation blob is 12 bytes per land cell', pB.length === WC.n * 12, String(pB.length));
ok('land-fraction blob is 1 byte per land cell', fB.length === WC.n, String(fB.length));
let maskCount = 0;
for (let i = 0; i < WC.H * WC.W; i++) if ((mB[i >> 3] >> (i & 7)) & 1) maskCount++;
ok('land mask bit count matches the land-cell count', maskCount === WC.n, String(maskCount));
ok('CenCO2PIP block holds 4726 estimates', CEN.length === 4726 * 3, String(CEN.length / 3));
ok('Rubisco block holds 256 enzymes', RUB.length === 256, String(RUB.length));

/* ------------------------------------------------------------------ */
head('7. the map, recomputed from the shipped grid');
/* ------------------------------------------------------------------ */
// cos(latitude) x land-fraction weights, exactly as the page builds them
const idx = new Int32Array(WC.H * WC.W).fill(-1);
{
  let k = 0;
  for (let i = 0; i < WC.H * WC.W; i++) if ((mB[i >> 3] >> (i & 7)) & 1) idx[i] = k++;
}
const wgt = new Float64Array(WC.n);
let totW = 0;
for (let i = 0; i < WC.H * WC.W; i++) {
  const j = idx[i]; if (j < 0) continue;
  const row = Math.floor(i / WC.W);
  const lat = 90 - (row + 0.5) * (180 / WC.H);
  wgt[j] = Math.cos(lat * Math.PI / 180) * (fB[j] / 255);
  totW += wgt[j];
}
function landFrac(Tc, pth, nmon) {
  let w = 0;
  for (let j = 0; j < WC.n; j++) {
    let c = 0;
    for (let m = 0; m < 12; m++) {
      const t8 = tB[j * 12 + m], t = (t8 < 128 ? t8 : t8 - 256) * 0.5;
      if (t >= Tc && pB[j * 12 + m] >= pth) c++;
    }
    if (c >= nmon) w += wgt[j];
  }
  return w / totW;
}
// Reference values PRECOMPUTED OFFLINE from the full-resolution 10-arcmin WorldClim
// rasters (2160 x 1080 x 12, 808,053 land pixels), not from the shipped grid.
// They are here so the coarse grid can be held to the fine answer.
const FULLRES = {
  '14_1': 0.66629, '18_1': 0.53249, '20_1': 0.47743, '22_1': 0.42411, '24_1': 0.36086,
  '26_1': 0.27140, '28_1': 0.13930, '30_1': 0.07288, '32_1': 0.02510,
  '20_3': 0.39102, '22_3': 0.34899, '26_3': 0.19694, '28_3': 0.06171, '30_3': 0.01669,
  '22_6': 0.23191, '26_6': 0.09227
};
let worst = 0, worstKey = '';
for (const key of Object.keys(FULLRES)) {
  const [Tc, nm] = key.split('_').map(Number);
  const got = landFrac(Tc, 25, nm);
  const d = Math.abs(got - FULLRES[key]);
  if (d > worst) { worst = d; worstKey = key; }
  ok(`2 deg grid within 1.5 points of full resolution at Tc=${Tc}, n>=${nm}`, d <= 0.015,
    `coarse ${fmt(100 * got)} % vs fine ${fmt(100 * FULLRES[key])} %`);
}
console.log(`  ..   largest coarse-vs-fine gap: ${fmt(100 * worst)} points, at ${worstKey}`);
// the headline the page shows on load
near('land fraction at the default 340 ppm crossover (28.707 C, 25 mm, 1 month)',
  100 * landFrac(crossT(340, 0.21, EB.c4_21), 25, 1), 9.92, 0.05, ' %');
ok('the criterion spans a wide range across defensible knobs, so it constrains little',
  landFrac(20, 25, 1) > 0.4 && landFrac(35, 25, 1) < 0.01,
  `${fmt(100 * landFrac(20, 25, 1))} % at 20 C down to ${fmt(100 * landFrac(35, 25, 1))} % at 35 C`);

/* ------------------------------------------------------------------ */
head('8. the Cenozoic CO2 record, recomputed from the shipped points');
/* ------------------------------------------------------------------ */
function cenMedian(lo, hi, maxCat) {
  const v = [];
  for (let i = 0; i < CEN.length / 3; i++) {
    const ma = CEN[3 * i] / 100, co2 = CEN[3 * i + 1], cat = CEN[3 * i + 2];
    if (cat <= maxCat && ma >= lo && ma <= hi) v.push(co2);
  }
  v.sort((a, b) => a - b);
  if (!v.length) return null;
  const h = v.length >> 1;
  return v.length % 2 ? v[h] : (v[h - 1] + v[h]) / 2;
}
near('category-1 median CO2, 30 to 34 Ma', cenMedian(30, 34, 1), 539, 1, ' ppm');
near('category-1 median CO2, 14 to 16 Ma (the middle-Miocene rise)', cenMedian(14, 16, 1), 454, 1, ' ppm');
near('category-1 median CO2, 9 to 11 Ma', cenMedian(9, 11, 1), 232.5, 1, ' ppm');
near('category-1 median CO2, 5 to 7 Ma', cenMedian(5, 7, 1), 308.5, 1, ' ppm');
near('category-1 median CO2, 0 to 1 Ma', cenMedian(0, 1, 1), 224, 1, ' ppm');
ok('the record does not fall through the Miocene: 14-16 Ma sits above 9-11 Ma',
  cenMedian(14, 16, 1) > cenMedian(9, 11, 1),
  `${fmt(cenMedian(14, 16, 1))} vs ${fmt(cenMedian(9, 11, 1))} ppm`);
ok('and 5-7 Ma is not below 9-11 Ma either, so no late-Miocene fall is visible',
  cenMedian(5, 7, 1) >= cenMedian(9, 11, 1),
  `${fmt(cenMedian(5, 7, 1))} vs ${fmt(cenMedian(9, 11, 1))} ppm`);
// the model's own clock, with the page's defaults (categories 1+2, 2 Myr window, 30 C tropics)
function runningMedian(centre, win, maxCat) { return cenMedian(centre - win / 2, centre + win / 2, maxCat); }
let firstMa = null;
for (let t = 40; t >= 0; t -= 0.25) {
  const m = runningMedian(t, 2, 2);
  if (m === null) continue;
  const xc = crossT(m, 0.21, EB.c4_21);
  if (xc !== null && xc <= 30) { firstMa = t; break; }
}
near('model first favours C4 at 30 C tropics (cat 1+2, 2 Myr window)', firstMa, 24.25, 0.001, ' Ma');
ok('that is more than 15 Myr before the 8 to 6 Ma tooth-enamel shift', firstMa - 7 > 15,
  `${fmt(firstMa - 7)} Myr early`);
const needCa = bisect((C) => { const t = crossT(C, 0.21, EB.c4_21); return t === null ? -1e9 : 30 - t; }, 20, 1000);
near('CO2 at which the crossing falls to 30 C', needCa, 354.4, 0.2, ' ppm');
ok('the proxy median at 7 Ma is already below that threshold',
  runningMedian(7, 2, 2) < needCa, `${fmt(runningMedian(7, 2, 2))} ppm vs ${fmt(needCa)} ppm`);

/* ------------------------------------------------------------------ */
head('9. the Rubisco dataset, refit from the shipped rows');
/* ------------------------------------------------------------------ */
const rows = RUB.map(r => ({ sp: r[0], grp: r[1], f1: r[2] === 1, kc: r[3], S: r[4], KC: r[5], vO: r[6], KO: r[7] }));
function median(a) { a = a.slice().sort((x, y) => x - y); const h = a.length >> 1; return a.length % 2 ? a[h] : (a[h - 1] + a[h]) / 2; }
function groupMed(g) {
  const s = rows.filter(r => r.grp === g && r.kc !== null && r.S !== null);
  return { n: s.length, k: median(s.map(r => r.kc)), S: median(s.map(r => r.S)) };
}
for (const [g, n, k, S] of [['C3 plants', 156, 3.155, 99.9], ['C4 plants', 33, 4.14, 79.4],
                            ['Cyanobacteria', 14, 9.79, 45.1], ['Red algae', 7, 1.40, 167.0]]) {
  const m = groupMed(g);
  ok(`${g}: n = ${n}`, m.n === n, String(m.n));
  near(`${g}: median kcat,C`, m.k, k, 0.005, ' /s');
  near(`${g}: median S_C/O`, m.S, S, 0.05);
}
function pearson(xs, ys) {
  const n = xs.length; const mx = xs.reduce((a, b) => a + b, 0) / n, my = ys.reduce((a, b) => a + b, 0) / n;
  let sxy = 0, sxx = 0, syy = 0;
  for (let i = 0; i < n; i++) { const a = xs[i] - mx, b = ys[i] - my; sxy += a * b; sxx += a * a; syy += b * b; }
  return sxy / Math.sqrt(sxx * syy);
}
function ols(xs, ys) {
  const n = xs.length; const mx = xs.reduce((a, b) => a + b, 0) / n, my = ys.reduce((a, b) => a + b, 0) / n;
  let sxy = 0, sxx = 0;
  for (let i = 0; i < n; i++) { sxy += (xs[i] - mx) * (ys[i] - my); sxx += (xs[i] - mx) ** 2; }
  const b = sxy / sxx, a = my - b * mx;
  let ss = 0, rs = 0;
  for (let i = 0; i < n; i++) { ss += (ys[i] - my) ** 2; rs += (ys[i] - (a + b * xs[i])) ** 2; }
  return { slope: b, inter: a, r2: 1 - rs / ss, n };
}
{
  const s = rows.filter(r => r.f1 && r.kc !== null && r.S !== null);
  const r = pearson(s.map(x => Math.log10(x.kc)), s.map(x => Math.log10(x.S)));
  ok('Form I kcat vs S: 246 enzymes', s.length === 246, String(s.length));
  near('Form I kcat vs S Pearson R', r, -0.604, 0.002);
  ok('the classical near-perfect inverse relation does not survive', Math.abs(r) < 0.75, `|R| = ${fmt(Math.abs(r))}`);
  // the spread the page's instrument-6 text now prints live, instead of the old "barely one
  // order of magnitude and specificity less than that", which was wrong on the second half
  const kLo = Math.min(...s.map(x => x.kc)), kHi = Math.max(...s.map(x => x.kc));
  const sLo = Math.min(...s.map(x => x.S)), sHi = Math.max(...s.map(x => x.S));
  near('Form I kcat,C minimum', kLo, 0.78, 0.005, ' /s');
  near('Form I kcat,C maximum', kHi, 14.4, 0.005, ' /s');
  near('Form I kcat,C span as a factor', kHi / kLo, 18.46, 0.02);
  near('Form I S_C/O minimum', sLo, 41, 0.05);
  near('Form I S_C/O maximum', sHi, 238, 0.05);
  near('Form I S_C/O span as a factor', sHi / sLo, 5.805, 0.02);
  ok('specificity is the narrower of the two spreads, which is what the page says',
    sHi / sLo < kHi / kLo, `S x${fmt(sHi / sLo)} vs kcat x${fmt(kHi / kLo)}`);
  ok('turnover spans a little over one order of magnitude, not "barely" one',
    Math.log10(kHi / kLo) > 1 && Math.log10(kHi / kLo) < 1.5, `${fmt(Math.log10(kHi / kLo))} decades`);
}
{
  const s = rows.filter(r => r.f1 && r.kc !== null && r.KC !== null && r.vO !== null && r.KO !== null);
  const f = ols(s.map(x => Math.log10(x.vO / x.KO)), s.map(x => Math.log10(x.kc / x.KC)));
  ok('Form I efficiency pairs: 201 enzymes', f.n === 201, String(f.n));
  near('efficiency relation exponent (our OLS)', f.slope, 1.004, 0.002);
  near('efficiency relation prefactor (our OLS)', Math.pow(10, f.inter), 94.1, 0.2);
  near('efficiency relation R^2 (our OLS)', f.r2, 0.858, 0.002);
  ok('our exponent falls inside the 0.94 to 1.13 interval usually quoted for this relation',
    f.slope > 0.94 && f.slope < 1.13, fmt(f.slope));
}
{
  // the in-vitro to in-vivo bridge, and its honest slack
  const pO2 = 0.21 * 100000;
  const gPa = gstar(25) / 10;
  const S = (hco2, ho2) => 0.5 * ho2 * pO2 / (gPa * hco2);
  const med = groupMed('C3 plants').S;
  near('S implied by Gamma*, CO2 3.4e-4 / O2 1.3e-5', S(3.4e-4, 1.3e-5), 107.27, 0.02);
  near('S implied, CO2 3.3e-4 / O2 1.2e-5', S(3.3e-4, 1.2e-5), 102.02, 0.02);
  near('S implied, CO2 3.4e-4 / O2 1.2e-5', S(3.4e-4, 1.2e-5), 99.02, 0.02);
  near('S implied, CO2 3.3e-4 / O2 1.3e-5', S(3.3e-4, 1.3e-5), 110.52, 0.02);
  ok('the four published solubility combinations bracket the measured C3 median',
    Math.min(S(3.4e-4, 1.2e-5), S(3.3e-4, 1.2e-5)) < med && Math.max(S(3.3e-4, 1.3e-5), S(3.4e-4, 1.3e-5)) > med,
    `range ${fmt(S(3.4e-4, 1.2e-5))} to ${fmt(S(3.3e-4, 1.3e-5))} around ${fmt(med)}`);
  ok('the bridge is good to about 7%, not to a fraction of a per cent, on the page default',
    Math.abs(S(3.4e-4, 1.3e-5) - med) / med > 0.02 && Math.abs(S(3.4e-4, 1.3e-5) - med) / med < 0.12,
    `${fmt(100 * (S(3.4e-4, 1.3e-5) - med) / med)} %`);
}

/* ------------------------------------------------------------------ */
head(`RESULT: ${pass} assertions passed, ${fails.length} failed`);
if (fails.length) {
  console.error('\nFAILURES:');
  for (const f of fails) console.error('  - ' + f);
  process.exit(1);
}
console.log('All checks passed.');
process.exit(0);
