#!/usr/bin/env node

/*
  Independent numerical verifier for /strata/rubisco-crossover/.

  The page implementation is read from index.html and evaluated in an isolated
  context. A separate set of equations, including an analytic crossover rather
  than the page's bisection, reproduces every model number in the initial
  rendered display. Source-transcribed observations are checked against the
  actual HTML as provenance fixtures, not compared with themselves.
*/

import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import vm from "node:vm";

const PAGE_PATH = fileURLToPath(
  new URL("../../public/strata/rubisco-crossover/index.html", import.meta.url)
);
const html = readFileSync(PAGE_PATH, "utf8");

const cited = Object.freeze({
  R: 8.314462618,
  TREF: 298.15,
  GAMMA25: 42.75,
  HA_GAMMA: 37830,
  O2_PPM: 210000,
  INTRINSIC: 0.08
});

const declared = Object.freeze({
  REF_TEMP: 22,
  REF_CO2: 340,
  LAPSE: 6.5,
  SEA_LEVEL_WARM_MONTH: 28
});

const observedFixtures = Object.freeze({
  "C3, 10 °C, 21% O2": "about 0.070",
  "C3, 30 °C, 21% O2": "0.0524 ± 0.0014",
  "C3, 40 °C, 21% O2": "about 0.040",
  "C4, 30 °C, 21% O2": "0.0534 ± 0.0009",
  // Ehleringer & Pearcy (1983) Plant Physiol 73(3):555-559, doi:10.1104/pp.73.3.555,
  // 330 uL/L, 21% O2, 30 C leaf. The C4 GRASS subtype means, all above E&B 1977's 0.0534.
  "C4 grasses by subtype, 30 °C, 21% O2": "0.060 NAD-ME, 0.064 PCK, 0.065 NADP-ME",
  "C3, 30 °C, 2% O2": "0.0733 ± 0.0008",
  "C4, 30 °C, 2% O2": "0.0538 ± 0.0011"
});

let checks = 0;
let failures = 0;

function close(label, actual, expected, tolerance) {
  checks += 1;
  const ok = Number.isFinite(actual) &&
    Number.isFinite(expected) &&
    Math.abs(actual - expected) <= tolerance;
  if (!ok) failures += 1;
  console.log(
    `${ok ? "PASS" : "FAIL"}  ${label}: ${actual.toFixed(9)} ` +
    `(expected ${expected.toFixed(9)} ± ${tolerance})`
  );
}

function trueCheck(label, condition, detail) {
  checks += 1;
  if (!condition) failures += 1;
  console.log(`${condition ? "PASS" : "FAIL"}  ${label}: ${detail}`);
}

function textCheck(label, actual, expected) {
  checks += 1;
  const ok = actual === expected;
  if (!ok) failures += 1;
  console.log(
    `${ok ? "PASS" : "FAIL"}  ${label}: ${JSON.stringify(actual)} ` +
    `(expected ${JSON.stringify(expected)})`
  );
}

function independentGammaStar(tempC) {
  const kelvin = tempC + 273.15;
  return cited.GAMMA25 * Math.exp(
    (cited.HA_GAMMA / cited.R) * ((1 / cited.TREF) - (1 / kelvin))
  );
}

function independentSpecificity(tempC) {
  return cited.O2_PPM / (2 * independentGammaStar(tempC));
}

function independentPhi(tempC, co2ppm) {
  return 2 * independentGammaStar(tempC) / co2ppm;
}

function independentC3Yield(tempC, co2ppm) {
  const ratio = independentPhi(tempC, co2ppm);
  return cited.INTRINSIC * (1 - ratio / 2) / (1 + ratio);
}

const independentC4Yield = independentC3Yield(
  declared.REF_TEMP,
  declared.REF_CO2
);

function analyticCrossover(co2ppm) {
  const normalizedYield = independentC4Yield / cited.INTRINSIC;
  const targetRatio = (1 - normalizedYield) / (normalizedYield + 0.5);
  const targetGamma = targetRatio * co2ppm / 2;
  const inverseKelvin = (1 / cited.TREF) -
    Math.log(targetGamma / cited.GAMMA25) / (cited.HA_GAMMA / cited.R);
  return (1 / inverseKelvin) - 273.15;
}

function inlineScripts(source) {
  return Array.from(
    source.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi),
    (match) => ({ attributes: match[1], source: match[2] })
  );
}

const scripts = inlineScripts(html);
const executable = scripts.find(({ attributes }) =>
  !/\bsrc\s*=/.test(attributes) &&
  !/\btype\s*=\s*["']application\/ld\+json["']/.test(attributes)
);

if (!executable) {
  console.error("FAIL  page executable inline script was not found");
  process.exit(1);
}

const modelStart = executable.source.indexOf("    var R =");
const modelEnd = executable.source.indexOf("    var temp =");
if (modelStart < 0 || modelEnd < 0 || modelEnd <= modelStart) {
  console.error("FAIL  page model block could not be isolated");
  process.exit(1);
}

const pageModel = { Math };
vm.createContext(pageModel);
vm.runInContext(executable.source.slice(modelStart, modelEnd), pageModel, {
  filename: "rubisco-crossover-page-model.js"
});

function tagWithId(id) {
  const match = html.match(new RegExp(`<[^>]+\\bid="${id}"[^>]*>`, "i"));
  if (!match) throw new Error(`HTML element #${id} was not found`);
  return match[0];
}

function attribute(id, name) {
  const tag = tagWithId(id);
  const match = tag.match(new RegExp(`\\b${name}="([^"]+)"`, "i"));
  if (!match) throw new Error(`Attribute ${name} on #${id} was not found`);
  return match[1];
}

function tableObserved(label) {
  const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  const row = html.match(
    new RegExp(`<tr><td>${escaped}</td><td>([^<]+)</td>`, "i")
  );
  return row ? row[1].trim() : "";
}

function createPageHarness() {
  const drawnText = [];
  const context2d = {
    beginPath() {},
    clearRect() {},
    fill() {},
    fillRect() {},
    fillText(value) { drawnText.push(String(value)); },
    lineTo() {},
    moveTo() {},
    setLineDash() {},
    setTransform() {},
    stroke() {},
    arc() {}
  };
  const elements = new Map();

  function element(id) {
    if (!elements.has(id)) {
      elements.set(id, {
        id,
        textContent: "",
        innerHTML: "",
        value: "",
        clientWidth: 800,
        clientHeight: 350,
        addEventListener() {},
        getContext: id === "plot" ? () => context2d : undefined
      });
    }
    return elements.get(id);
  }

  element("temp").value = attribute("temp", "value");
  element("co2").value = attribute("co2", "value");
  element("plot");

  const document = {
    hidden: false,
    addEventListener() {},
    getElementById: element
  };
  const window = {
    devicePixelRatio: 1,
    addEventListener() {},
    cancelAnimationFrame() {},
    matchMedia() { return { matches: true }; },
    requestAnimationFrame() { return 1; }
  };

  const context = {
    Math,
    Number,
    document,
    window
  };
  vm.createContext(context);
  vm.runInContext(executable.source, context, {
    filename: "rubisco-crossover-inline.js"
  });
  return { elements, drawnText };
}

console.log("Rubisco crossover, page-linked independent reproduction\n");

for (const [name, expected] of Object.entries(cited)) {
  close(`implemented cited parameter ${name}`, pageModel[name], expected, 0);
}
for (const [name, expected] of Object.entries(declared)) {
  close(`implemented declared choice ${name}`, pageModel[name], expected, 0);
}

trueCheck(
  "displayed equation matches implemented parameters",
  html.includes("Γ*(T) = 42.75") &&
    html.includes("(37,830 / R)") &&
    html.includes("(1 / 298.15") &&
    html.includes("210,000 / [2Γ*(T)]") &&
    html.includes("Φ<sub>C3</sub> = 0.08"),
  "Gamma*, activation energy, reference temperature, O2 and intrinsic yield are shown"
);

for (const [label, expected] of Object.entries(observedFixtures)) {
  textCheck(`source-transcribed observation ${label}`, tableObserved(label), expected);
}

let maximumCurveDifference = 0;
for (const ppm of [180, 340, 560, 800]) {
  for (let tempC = 0; tempC <= 45; tempC += 0.25) {
    maximumCurveDifference = Math.max(
      maximumCurveDifference,
      Math.abs(
        pageModel.c3Yield(tempC, ppm) -
        independentC3Yield(tempC, ppm)
      )
    );
  }
}
trueCheck(
  "implemented C3 quantum-yield curves reproduce the independent equations",
  maximumCurveDifference <= 1e-14,
  `maximum difference across 724 plotted samples is ${maximumCurveDifference}`
);
close(
  "implemented C4 calibration from the independent C3 equation",
  pageModel.C4_YIELD,
  independentC4Yield,
  1e-14
);
trueCheck(
  "page plots C4 as the declared temperature-independent calibration",
  /line\(function \(\) \{ return C4_YIELD; \}, c4Color/.test(executable.source),
  "the plotted C4 callback returns the calibrated scalar without temperature input"
);

const model10 = independentC3Yield(10, declared.REF_CO2);
const model30 = independentC3Yield(30, declared.REF_CO2);
const model40 = independentC3Yield(40, declared.REF_CO2);
trueCheck(
  "independent C3 curve is anchored near the measured 10 C endpoint",
  Math.abs(model10 - 0.070) <= 0.005,
  `${model10.toFixed(4)} is within 0.005 of about 0.070`
);
trueCheck(
  "independent C3 curve is anchored near the measured 40 C endpoint",
  Math.abs(model40 - 0.040) <= 0.005,
  `${model40.toFixed(4)} is within 0.005 of about 0.040`
);
trueCheck(
  "independent C3 curve is near the measured 30 C mean",
  Math.abs(model30 - 0.0524) <= 0.003,
  `${model30.toFixed(4)} versus 0.0524 ± 0.0014`
);
// The check this replaced asserted |calibrated - 0.0534| <= 0.01 against a measurement whose SD
// is 0.0009. That tolerance is 11x the SD, so the assertion could not have failed for any
// calibration this page could plausibly ship, and it reported a 5.9-SD disagreement as agreement.
// What is actually defensible is narrower and is stated as a two-sided bracket: for a page about
// GRASSES, the calibrated level should sit above Ehleringer & Bjorkman's single-species-set C4
// mean and below every C4 grass subtype mean in Ehleringer & Pearcy (1983).
{
  const EB77_C4 = 0.0534;
  const EB77_C4_SD = 0.0009;
  // Ehleringer & Pearcy (1983), 330 uL/L, 21% O2, 30 C, C4 grasses by subtype.
  const EP83_C4_GRASS = { nadme: 0.060, pck: 0.064, nadpme: 0.065 };
  const epMin = Math.min(
    EP83_C4_GRASS.nadme,
    EP83_C4_GRASS.pck,
    EP83_C4_GRASS.nadpme
  );
  const gapSd = (independentC4Yield - EB77_C4) / EB77_C4_SD;
  trueCheck(
    "the calibrated C4 level disagrees with the E&B 1977 C4 mean by several SD, and that is reported not hidden",
    gapSd > 3,
    `${independentC4Yield.toFixed(4)} is ${gapSd.toFixed(1)} SD above 0.0534 +/- 0.0009`
  );
  trueCheck(
    "the calibrated C4 level lies inside the measured C4 range for grasses",
    independentC4Yield > EB77_C4 && independentC4Yield < epMin,
    `${EB77_C4} < ${independentC4Yield.toFixed(4)} < ${epMin} (E&P 1983 lowest C4 grass mean)`
  );
}

const ppmCases = [180, 200, 280, 340, 560, 800];
const analyticRoots = ppmCases.map(analyticCrossover);
for (let index = 0; index < ppmCases.length; index += 1) {
  const ppm = ppmCases[index];
  close(
    `implemented bisection root versus analytic root at ${ppm} ppm`,
    pageModel.crossover(ppm),
    analyticRoots[index],
    1e-10
  );
  close(
    `independent yield equality at ${ppm} ppm`,
    independentC3Yield(analyticRoots[index], ppm),
    independentC4Yield,
    1e-12
  );
  if (index > 0) {
    trueCheck(
      `crossover rises from ${ppmCases[index - 1]} to ${ppm} ppm`,
      analyticRoots[index] > analyticRoots[index - 1],
      `${analyticRoots[index - 1].toFixed(3)} C to ` +
      `${analyticRoots[index].toFixed(3)} C`
    );
  }
}
// This is a TAUTOLOGY and is labelled as one. C4_YIELD is defined as c3Yield(REF_TEMP, REF_CO2),
// so crossover(REF_CO2) returns REF_TEMP for any parameter set whatsoever. It is kept because it
// proves the implementation inverts its own equation correctly, and it is NOT evidence that 22 C
// is the right answer. The next check is the one that carries evidence.
close(
  "TAUTOLOGY (kept as a round-trip test only): crossover(340) returns 22 by construction",
  analyticCrossover(declared.REF_CO2),
  declared.REF_TEMP,
  1e-10
);
// Monson, Littlejohn & Williams (1982), Photosynth Res 3(2):153-159, doi:10.1007/BF00040713:
// quantum yields approximately equal at 22-25 C LEAF temperature in Agropyron smithii (C3) and
// Bouteloua gracilis (C4), in 21% O2 and 340 cm3 m-3 CO2. That is the independent warrant for
// anchoring here, and it is a measured leaf temperature at this model's own CO2 and O2.
{
  const MONSON = { lo: 22, hi: 25, co2: 340 };
  trueCheck(
    "the calibration point sits inside Monson et al. 1982's measured 22-25 C leaf window",
    declared.REF_CO2 === MONSON.co2 &&
      declared.REF_TEMP >= MONSON.lo &&
      declared.REF_TEMP <= MONSON.hi,
    `anchored at ${declared.REF_TEMP} C, ${declared.REF_CO2} ppm`
  );
}

const rendered = createPageHarness();
const initialTemp = Number(attribute("temp", "value"));
const initialCo2 = Number(attribute("co2", "value"));
const initialGamma = independentGammaStar(initialTemp);
const initialSpecificity = independentSpecificity(initialTemp);
const initialPhi = independentPhi(initialTemp, initialCo2);
const initialC3 = independentC3Yield(initialTemp, initialCo2);
const initialRoot = analyticCrossover(initialCo2);
const initialDelta = initialC3 - independentC4Yield;
const initialElevation = Math.max(
  0,
  (declared.SEA_LEVEL_WARM_MONTH - initialRoot) / declared.LAPSE
);

function renderedText(id) {
  return rendered.elements.get(id)?.textContent ?? "";
}

textCheck("rendered initial temperature", renderedText("temp-out"), "22.0 °C");
textCheck("rendered initial CO2", renderedText("co2-out"), "340 ppm");
textCheck("rendered initial C3 yield", renderedText("c3-now"), initialC3.toFixed(4));
textCheck(
  "rendered initial C4 yield",
  renderedText("c4-now"),
  independentC4Yield.toFixed(4)
);
textCheck(
  "rendered initial Gamma* and phi",
  renderedText("phi-now"),
  `φ = ${initialPhi.toFixed(3)}, Γ* = ${initialGamma.toFixed(2)} ppm`
);
textCheck("rendered initial winner", renderedText("winner"), "equal");
textCheck(
  "rendered initial yield margin",
  renderedText("margin"),
  `Δ = ${initialDelta >= 0 ? "+" : ""}${initialDelta.toFixed(4)}`
);
textCheck("rendered ledger C3 at 10 C", renderedText("model-10"), model10.toFixed(4));
textCheck("rendered ledger C3 at 30 C", renderedText("model-30"), model30.toFixed(4));
textCheck("rendered ledger C3 at 40 C", renderedText("model-40"), model40.toFixed(4));
// The ledger must print the SIGNED gap against Ehleringer & Bjorkman's measured C4 mean, in
// units of that measurement's own SD, rather than hide it inside a wide tolerance.
{
  const EB77_C4 = 0.0534;
  const EB77_C4_SD = 0.0009;
  const gap = independentC4Yield - EB77_C4;
  const sd = gap / EB77_C4_SD;
  textCheck(
    "rendered ledger C4 calibration prints the signed gap in SD",
    renderedText("model-c4"),
    `${independentC4Yield.toFixed(4)}  (${gap >= 0 ? "+" : ""}${gap.toFixed(4)}, ` +
      `${sd.toFixed(1)} SD above)`
  );
  const epMin = Math.min(0.060, 0.064, 0.065);
  textCheck(
    "rendered ledger C4 grass-subtype comparison",
    renderedText("model-c4-grass"),
    `${independentC4Yield.toFixed(4)}  (${
      independentC4Yield < epMin ? "below all three" : "NOT below all three"
    })`
  );
}
textCheck(
  "rendered initial toy elevation",
  renderedText("elevation"),
  `${initialElevation.toFixed(2)} km`
);
textCheck(
  "rendered complete initial live check",
  renderedText("live-check"),
  `At ${initialTemp.toFixed(1)} °C and ${initialCo2.toFixed(0)} ppm: Γ* = ` +
    `${initialGamma.toFixed(3)} ppm; Sr = ${initialSpecificity.toFixed(1)}` +
    `; φ = ${initialPhi.toFixed(4)}; ΦC3 = ${initialC3.toFixed(5)}` +
    `; ΦC4 = ${independentC4Yield.toFixed(5)}; crossover = ` +
    `${initialRoot.toFixed(3)} °C.`
);

const scenarioHtml = rendered.elements.get("scenarios")?.innerHTML ?? "";
for (const ppm of [180, 340, 560]) {
  trueCheck(
    `rendered scenario crossover at ${ppm} ppm`,
    scenarioHtml.includes(
      `${analyticCrossover(ppm).toFixed(1)} °C`
    ),
    `${analyticCrossover(ppm).toFixed(1)} °C appears in the scenario cards`
  );
}
trueCheck(
  "rendered plot crossover label",
  rendered.drawnText.includes(`cross ${initialRoot.toFixed(1)}°C`),
  `cross ${initialRoot.toFixed(1)}°C was drawn on the canvas`
);

// The dek used to say the model "crosses near 22 °C at 340 ppm CO2" as though that were an
// output. It is an input. The dek, plain text, meta description and JSON-LD must all say so, and
// the old formulation must be gone from every one of them.
trueCheck(
  "dek and metadata identify the 22 C crossing as the calibration, not a result",
  html.includes(
    "it is held at the value this model's own C3 equation gives at 22 °C and 340 ppm CO2, " +
      "so that crossing is the calibration rather than a result"
  ) &&
    !html.includes("This diagnostic model crosses near 22 °C at 340 ppm CO2") &&
    html.includes("this model crossing at 22 °C at 340 ppm is arithmetic, not evidence"),
  "the dek, meta and body all name the crossing as an input"
);
// The old "roughly 16 to 24 °C" empirical range appeared in the dek, the meta, the body and the
// research README with no citation anywhere in the source list. It is replaced by two ranges that
// name their paper and their conditions.
trueCheck(
  "the empirical crossover range is cited, and the uncited 16 to 24 range is gone",
  !html.includes("16 to 24") &&
    html.includes("Monson, Littlejohn and Williams") &&
    html.includes("10.1007/BF00040713") &&
    html.includes(
      "found their quantum yields approximately equal at leaf temperatures between 22 and 25 °C"
    ) &&
    html.includes("10.1104/pp.73.3.555"),
  "Monson et al. 1982 and Ehleringer & Pearcy 1983 are cited where the ranges are stated"
);
// Collatz's 22 C is a warmest-month mean AIR temperature at 35 Pa (350 ppm at 100 kPa). It must
// not be used to label a leaf-temperature axis at 340 ppm.
trueCheck(
  "Collatz is not used as the label on the 340 ppm leaf-temperature calibration point",
  !html.includes("scenario('Collatz reference'") &&
    !html.includes("The calibration point: warmest-month mean.") &&
    html.includes("mean warmest-month <em>air</em> temperature at 35 Pa"),
  "the calibration scenario names the construction, and Collatz keeps its air-temperature framing"
);
trueCheck(
  "body preserves the dated independent-origins count",
  html.includes("A 2011 synthesis recognized 62 independent C4 lineages"),
  "62 lineages are dated to the cited 2011 synthesis"
);
const forbiddenRubiscoAdjective = ["in", "efficient"].join("");
trueCheck(
  "Rubisco avoids the prohibited characterization",
  !new RegExp(
    `\\bRubisco\\b[^.]{0,80}\\b${forbiddenRubiscoAdjective}\\b`,
    "i"
  ).test(html) &&
    !new RegExp(
      `\\b${forbiddenRubiscoAdjective}\\b[^.]{0,80}\\bRubisco\\b`,
      "i"
    ).test(html),
  "the prohibited characterization does not appear near Rubisco"
);

console.log(`\n${checks - failures}/${checks} checks passed.`);
if (failures) {
  console.error(`${failures} check(s) failed.`);
  process.exit(1);
}
process.exit(0);
