#!/usr/bin/env node

import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';

const htmlUrl = new URL('../../public/strata/the-gap-that-changed-sides/index.html', import.meta.url);
const metadataUrl = new URL('../../src/content/strata/the-gap-that-changed-sides.md', import.meta.url);
const readmeUrl = new URL('./README.md', import.meta.url);
const verifierUrl = new URL(import.meta.url);
const html = await readFile(htmlUrl, 'utf8');
const metadata = await readFile(metadataUrl, 'utf8');
const readme = await readFile(readmeUrl, 'utf8');
const verifierSource = await readFile(verifierUrl, 'utf8');

let checks = 0;
function check(condition, message) {
  assert.ok(condition, message);
  checks += 1;
  console.log(`PASS ${message}`);
}
function close(actual, expected, tolerance, message) {
  assert.ok(Math.abs(actual - expected) <= tolerance,
    `${message}: expected ${expected}, received ${actual}`);
  checks += 1;
  console.log(`PASS ${message}: ${actual}`);
}

const engineMatch = html.match(/<script id="g2-engine">([\s\S]*?)<\/script>/);
check(Boolean(engineMatch), 'The shipped calculation engine must be extractable');
const engineSource = engineMatch[1];
const context = { Math };
vm.createContext(context);
new vm.Script(engineSource, { filename: 'shipped-g2-engine.js' }).runInContext(context);
const engine = context.G2Engine;
check(Boolean(engine), 'The shipped engine must expose G2Engine');

const inlineScripts = [...html.matchAll(
  /<script(?![^>]*type="application\/ld\+json")[^>]*>([\s\S]*?)<\/script>/g
)].map((match) => match[1]).filter((body) => body.trim());
for (const body of inlineScripts) {
  new vm.Script(body, { filename: 'inline-script.js' });
  check(true, 'Inline script parses as JavaScript');
}

function makeElement(id, attributes = '') {
  const listeners = {};
  const element = {
    id,
    style: {},
    dataset: {},
    hidden: false,
    checked: /\bchecked\b/.test(attributes),
    value: attributes.match(/\bvalue="([^"]*)"/)?.[1] ?? '',
    name: attributes.match(/\bname="([^"]*)"/)?.[1] ?? '',
    textContent: '',
    innerHTML: '',
    className: '',
    clientWidth: 700,
    children: [],
    addEventListener(type, listener) {
      (listeners[type] ??= []).push(listener);
    },
    dispatch(type) {
      for (const listener of listeners[type] ?? []) listener({ target: element });
    },
    setAttribute(name, value) {
      element[name] = String(value);
    },
    appendChild(child) {
      element.children.push(child);
    },
    getContext() {
      return {
        setTransform() {}, clearRect() {}, fillRect() {}, beginPath() {},
        moveTo() {}, lineTo() {}, stroke() {}, fillText() {}, save() {},
        translate() {}, rotate() {}, restore() {},
        set fillStyle(value) {}, set strokeStyle(value) {},
        set lineWidth(value) {}, set font(value) {}
      };
    }
  };
  return element;
}

const elements = new Map();
for (const tag of html.matchAll(/<([a-z0-9]+)\b([^>]*\bid="([^"]+)"[^>]*)>/gi)) {
  elements.set(tag[3], makeElement(tag[3], tag[2]));
}
elements.get('dataset').value = 'rho2013';
elements.get('interpolation').value = 'linear';
elements.get('lower-bound').value = '0.605';
elements.get('upper-bound').value = '0.880';
elements.get('rho').value = '0';

const theoryButtons = [...html.matchAll(/<button\b([^>]*\bdata-theory="([^"]+)"[^>]*)>/g)]
  .map((match, index) => {
    const button = makeElement(`theory-button-${index}`, match[1]);
    button.dataset.theory = match[2];
    return button;
  });
const radioElements = [...elements.values()].filter((element) => element.name);
const documentStub = {
  activeElement: null,
  getElementById(id) { return elements.get(id); },
  createElement() { return makeElement('created'); },
  querySelector(selector) {
    const name = selector.match(/input\[name="([^"]+)"\]/)?.[1];
    return radioElements.find((element) => element.name === name && element.checked) ?? null;
  },
  querySelectorAll(selector) {
    if (selector === '[data-theory]') return theoryButtons;
    if (selector.includes('input[name=')) return radioElements;
    return [];
  }
};
const uiContext = {
  Math,
  G2Engine: engine,
  document: documentStub,
  window: { devicePixelRatio: 1, addEventListener() {} },
  setTimeout,
  clearTimeout
};
uiContext.globalThis = uiContext;
vm.createContext(uiContext);
const uiSource = inlineScripts.find((body) => body.includes('function updateComparison'));
check(Boolean(uiSource), 'The browser interface script must be extractable');
new vm.Script(uiSource, { filename: 'shipped-g2-interface.js' }).runInContext(uiContext);
check(elements.get('delta-output').textContent === '38.5', 'Interface must render the live current difference');
check(elements.get('z-output').textContent === '0.60 σ', 'Interface must render the live current significance');
check(elements.get('integral-output').textContent === '380.78', 'Interface must render the default raw proxy for the recorded Table V window');
check(elements.get('published-rho2013').textContent === '380.06 ± 0.61 ± 3.64',
  'Interface must render the published RHO2013 benchmark from engine inputs');
theoryButtons.find((button) => button.dataset.theory === 'ee').dispatch('click');
check(elements.get('ee-comparison').hidden === false && elements.get('numeric-comparison').hidden === true,
  'Electron-positron control must fail closed without the numerical comparison');

function referenceComparison(experiment, theory, rho) {
  const delta = experiment.value - theory.value;
  const squared = experiment.sigma ** 2 + theory.sigma ** 2
    - 2 * rho * experiment.sigma * theory.sigma;
  return { delta, sigma: Math.sqrt(squared), z: delta / Math.sqrt(squared) };
}

for (const experimentKey of ['world', 'fnal']) {
  for (const theoryKey of ['wp20', 'ti25']) {
    for (let rho = -0.95; rho <= 0.95001; rho += 0.05) {
      const actual = engine.comparison(experimentKey, theoryKey, Number(rho.toFixed(2)));
      const expected = referenceComparison(
        engine.sources.experiment[experimentKey],
        engine.sources.theory[theoryKey],
        Number(rho.toFixed(2))
      );
      close(actual.delta, expected.delta, 1e-10, 'Difference sweep');
      close(actual.sigma, expected.sigma, 1e-10, 'Uncertainty sweep');
      close(actual.z, expected.z, 1e-10, 'Significance sweep');
    }
  }
}

const current = engine.comparison('world', 'ti25', 0);
close(current.delta, 38.5, 1e-12, 'Current central-value difference');
close(current.sigma, Math.sqrt(14.5 ** 2 + 62 ** 2), 1e-12, 'Current quadrature uncertainty');
close(current.z, 0.6046519625428081, 1e-12, 'Current significance');

const historical = engine.comparison('world', 'wp20', 0);
close(historical.delta, 261.5, 1e-12, 'Cross-era central-value difference');
close(historical.sigma, Math.sqrt(14.5 ** 2 + 43 ** 2), 1e-12, 'Cross-era quadrature uncertainty');
close(historical.z, 5.762582498105233, 1e-12, 'Cross-era significance');

const fnalCurrent = engine.comparison('fnal', 'ti25', 0);
close(fnalCurrent.delta, 37.5, 1e-12, 'Fermilab-only current difference');
close(fnalCurrent.sigma, Math.sqrt(14.8 ** 2 + 62 ** 2), 1e-12, 'Fermilab-only current uncertainty');

close(engine.naiveCmd3(), 200 / Math.sqrt(42 ** 2 + 34 ** 2), 1e-12,
  'Naive independent CMD-3 diagnostic');

check(engine.sources.experiment.world.value === 116592071.5, 'World-average central value');
check(engine.sources.experiment.world.sigma === 14.5, 'World-average uncertainty');
check(engine.sources.experiment.fnal.value === 116592070.5, 'Fermilab-only central value');
check(engine.sources.experiment.fnal.sigma === 14.8, 'Fermilab-only uncertainty');
check(engine.sources.theory.wp20.value === 116591810, '2020 theory central value');
check(engine.sources.theory.wp20.sigma === 43, '2020 theory uncertainty');
check(engine.sources.theory.ti25.value === 116592033, '2025 theory central value');
check(engine.sources.theory.ti25.sigma === 62, '2025 theory uncertainty');
check(engine.sources.constants.alphaInverse === 137.035999177, 'CODATA inverse alpha');
check(engine.sources.constants.muonMassGeV === 0.1056583755, 'CODATA muon mass');
check(engine.sources.constants.pionMassGeV === 0.13957039, 'PDG charged-pion mass');
check(engine.sources.benchmarks.cmd3 === 5260, 'CMD-3-based full two-pion benchmark');
check(engine.sources.benchmarks.cmd3Sigma === 42, 'CMD-3-based benchmark uncertainty');
check(engine.sources.benchmarks.earlier === 5060, 'Earlier-data full two-pion benchmark');
check(engine.sources.benchmarks.earlierSigma === 34, 'Earlier-data benchmark uncertainty');
check(engine.sources.benchmarks.rho2013.value === 380.06, 'Published RHO2013 window value');
check(engine.sources.benchmarks.rho2013.stat === 0.61, 'Published RHO2013 statistical uncertainty');
check(engine.sources.benchmarks.rho2013.syst === 3.64, 'Published RHO2013 systematic uncertainty');
check(engine.sources.benchmarks.rho2018.value === 379.30, 'Published RHO2018 window value');
check(engine.sources.benchmarks.rho2018.stat === 0.33, 'Published RHO2018 statistical uncertainty');
check(engine.sources.benchmarks.rho2018.syst === 2.62, 'Published RHO2018 systematic uncertainty');
check(engine.sources.benchmarks.combined.value === 379.35, 'Published combined window value');
check(engine.sources.benchmarks.combined.stat === 0.30, 'Published combined statistical uncertainty');
check(engine.sources.benchmarks.combined.syst === 2.95, 'Published combined systematic uncertainty');
check(engine.sources.benchmarks.latticeAverage.value === 713.2, 'Published 2025 lattice HVP average');
check(engine.sources.benchmarks.latticeAverage.sigma === 6.1, 'Published 2025 lattice HVP uncertainty');
check(engine.sources.benchmarks.hybrid.value === 715.1, 'Published 2026 hybrid HVP value');
check(engine.sources.benchmarks.hybrid.stat === 2.5, 'Published 2026 hybrid statistical uncertainty');
check(engine.sources.benchmarks.hybrid.syst === 2.3, 'Published 2026 hybrid systematic uncertainty');
check(engine.sources.benchmarks.hybrid.total === 3.4, 'Published 2026 hybrid total uncertainty');

function locate(points, energy) {
  let low = 0;
  let high = points.length - 1;
  while (high - low > 1) {
    const middle = Math.floor((low + high) / 2);
    if (points[middle][0] <= energy) low = middle;
    else high = middle;
  }
  return [low, high];
}

function referenceFormFactor(points, energy, rule) {
  if (energy <= points[0][0]) return points[0][1];
  if (energy >= points.at(-1)[0]) return points.at(-1)[1];
  const [low, high] = locate(points, energy);
  if (rule === 'left') return points[low][1];
  const fraction = (energy - points[low][0]) / (points[high][0] - points[low][0]);
  return points[low][1] * (1 - fraction) + points[high][1] * fraction;
}

function midpointKernel(s, count = 800) {
  const muonSquared = 0.1056583755 ** 2;
  let sum = 0;
  for (let index = 0; index < count; index += 1) {
    const x = (index + 0.5) / count;
    sum += x ** 2 * (1 - x) / (x ** 2 + (1 - x) * s / muonSquared);
  }
  return sum / count;
}

function referenceWindow(points, lower, upper, rule, count = 2200) {
  const lo = Math.max(lower, points[0][0]);
  const hi = Math.min(upper, points.at(-1)[0]);
  if (hi <= lo) return 0;
  const alpha = 1 / 137.035999177;
  const pion = 0.13957039;
  function referenceIntegrand(energy) {
    const s = energy ** 2;
    const beta = Math.sqrt(Math.max(0, 1 - 4 * pion ** 2 / s));
    const ratio = beta ** 3 * referenceFormFactor(points, energy, rule) / 4;
    return 2 * alpha ** 2 / (3 * Math.PI ** 2) * midpointKernel(s) * ratio / energy;
  }
  function midpointSegment(segmentLo, segmentHi, segments) {
    const width = (segmentHi - segmentLo) / segments;
    let subtotal = 0;
    for (let index = 0; index < segments; index += 1) {
      subtotal += referenceIntegrand(segmentLo + (index + 0.5) * width);
    }
    return subtotal * width;
  }
  if (rule === 'left') {
    let total = 0;
    for (let index = 0; index < points.length - 1; index += 1) {
      const segmentLo = Math.max(lo, points[index][0]);
      const segmentHi = Math.min(hi, points[index + 1][0]);
      if (segmentHi > segmentLo) total += midpointSegment(segmentLo, segmentHi, 28);
    }
    return total * 1e10;
  }
  return midpointSegment(lo, hi, count) * 1e10;
}

for (const datasetKey of ['rho2013', 'rho2018']) {
  const points = engine.data[datasetKey];
  check(points.every((point, index) => index === 0 || point[0] > points[index - 1][0]),
    `${datasetKey} energies must be strictly increasing`);
  for (const rule of ['linear', 'left']) {
    const windows = [
      [points[0][0], points.at(-1)[0]],
      [0.68, 0.80],
      [0.74, 0.79]
    ];
    for (const [lower, upper] of windows) {
      const actual = engine.windowIntegral(datasetKey, lower, upper, rule);
      const expected = referenceWindow(points, lower, upper, rule);
      close(actual, expected, 0.08, `${datasetKey} ${rule} window ${lower} to ${upper}`);
    }
  }
}

// Window counts and endpoints reread in https://arxiv.org/html/2302.08834v3#S8.T5 on 2026-10-14.
check(engine.data.rho2013.length === 44, 'RHO2013 recorded Table V window row count');
check(engine.data.rho2018.length === 72, 'RHO2018 recorded Table V window row count');
close(engine.data.rho2013[0][0], 0.604872, 0, 'RHO2013 first energy');
close(engine.data.rho2013.at(-1)[0], 0.879938, 0, 'RHO2013 last energy');
close(engine.data.rho2018[0][0], 0.600144, 0, 'RHO2018 first energy');
close(engine.data.rho2018.at(-1)[0], 0.880145, 0, 'RHO2018 last energy');

const normalizedData = JSON.stringify(engine.data);
const dataSha256 = createHash('sha256').update(normalizedData).digest('hex');
const expectedDataSha256 = 'a1fae07971cb12333280e377315c407283bb6ec842596fd0705fad5639bf2d6b';
check(dataSha256 === expectedDataSha256, `Embedded Table V SHA-256 must remain ${expectedDataSha256}`);

const mutatedSource = engineSource.replace('sigma:62, label:\'2025 lattice\'', 'sigma:63, label:\'2025 lattice\'');
check(mutatedSource !== engineSource, 'Mutation must alter the shipped source');
const mutationContext = { Math };
vm.createContext(mutationContext);
new vm.Script(mutatedSource, { filename: 'mutated-g2-engine.js' }).runInContext(mutationContext);
let mutationDetected = false;
try {
  assert.equal(mutationContext.G2Engine.comparison('world', 'ti25', 0).sigma, current.sigma);
} catch {
  mutationDetected = true;
}
check(mutationDetected, 'A one-unit theory-uncertainty mutation must be detected');

check((html.match(/<html\b/g) || []).length === 1 && (html.match(/<\/html>/g) || []).length === 1,
  'HTML root tags must balance');
check((html.match(/<body\b/g) || []).length === 1 && (html.match(/<\/body>/g) || []).length === 1,
  'Body tags must balance');
check((html.match(/<main\b/g) || []).length === 1 && (html.match(/<\/main>/g) || []).length === 1,
  'Main tags must balance');
// Site chrome (the Nearby box, placards) is generated into the page from OTHER layers' text and can carry
// their punctuation; the character rules below are about this layer's own words, so they read the page
// without those generated blocks (the house pattern: stripChrome in other verifiers).
const ownHtml = html.replace(/\s*<!--aw-([a-z-]+):start-->[\s\S]*?<!--aw-\1:end-->/g, '');
const forbiddenLongDash = String.fromCodePoint(0x2014);
check(![ownHtml, metadata, readme, verifierSource].some((text) => text.includes(forbiddenLongDash)),
  'All four artifacts must not contain forbidden long dashes');
const forbiddenEllipsis = String.fromCodePoint(0x2026);
check(![ownHtml, metadata, readme, verifierSource].some((text) => text.includes(forbiddenEllipsis)),
  'All four artifacts must not contain ellipsis characters');
check(html.includes('NO CONSENSUS VALUE'), 'The data-driven route must visibly fail closed');
check(html.includes('role="status"') && html.includes('aria-live="polite"'),
  'The page must expose live text updates to assistive technology');
check(html.includes('@media (prefers-reduced-motion:reduce)'), 'Reduced-motion support must be present');
check(html.includes('width:min(72rem,100%)'), 'The layout must cap wide-screen line length');
check(html.includes('@media (max-width:760px)') && html.includes('@media (max-width:410px)'),
  'Responsive rules must cover the 768 and 390 pixel review widths');
check(html.includes('.formula { overflow-x:auto;'), 'Wide formulae must scroll inside their container');
check(/<canvas[^>]*aria-label="[^"]+"/.test(html), 'The canvas must have a text alternative');
for (const control of html.matchAll(/<(?:input|select)\b[^>]*\bid="([^"]+)"[^>]*>/g)) {
  check(html.includes(`for="${control[1]}"`), `Control ${control[1]} must have a label`);
}
for (const identifier of [
  '2505.21476', '10.1016/j.physrep.2025.08.002', '2506.03069',
  '10.1103/7clf-sm2v', '2006.04822', '10.1016/j.physrep.2020.07.006',
  '2002.12347', '10.1038/s41586-021-03418-1',
  '2302.08834', '10.1103/PhysRevD.109.112002', '2309.12910',
  '10.1103/PhysRevLett.132.231903', '2312.02053',
  '10.1140/epjc/s10052-024-12964-7', '2407.10913',
  '10.1038/s41586-026-10449-z'
]) {
  check(html.includes(identifier) && readme.includes(identifier),
    `Primary identifier ${identifier} must appear in the page and research record`);
}
check(metadata.includes('href: "/strata/the-gap-that-changed-sides/"'), 'Metadata href must match the slug');
const dek = metadata.match(/^dek: "([^"]+)"$/m)?.[1];
const description = html.match(/<meta name="description" content="([^"]+)" \/>/)?.[1];
check(Boolean(dek) && dek === description, 'HTML description must exactly match the metadata dek');

console.log(`PASS assertion count ${checks}`);
console.log(`PASS current comparison ${current.delta.toFixed(1)} / ${current.sigma.toFixed(2)} = ${current.z.toFixed(2)} sigma`);
console.log(`PASS cross-era diagnostic ${historical.delta.toFixed(1)} / ${historical.sigma.toFixed(2)} = ${historical.z.toFixed(2)} sigma`);
console.log(`PASS CMD-3 diagnostic ${engine.naiveCmd3().toFixed(2)} sigma`);
console.log(`PASS Table V SHA-256 ${dataSha256}`);
console.log('PASS mutation sensitized: sigma 62 changed to 63 and was detected');
