#!/usr/bin/env node
/*
  Independent verifier for The Loop Remembers.
  Node 22, no dependencies.

  This file intentionally has its own equations. In PAGE-COUPLING it extracts
  ABEngine from the shipped HTML, executes it in node:vm, and compares that code
  with the independent results below.
*/
import fs from 'node:fs';
import vm from 'node:vm';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

const here = path.dirname(fileURLToPath(import.meta.url));
const pagePath = path.resolve(here, '../../public/strata/aharonov-bohm/index.html');
const html = fs.readFileSync(pagePath, 'utf8');

let checks = 0;
let failures = 0;

function check(name, condition, detail = '') {
  checks += 1;
  if (condition) {
    console.log(`ok ${String(checks).padStart(3, '0')} | ${name}${detail ? ` | ${detail}` : ''}`);
  } else {
    failures += 1;
    console.error(`not ok ${String(checks).padStart(3, '0')} | ${name}${detail ? ` | ${detail}` : ''}`);
  }
}

function close(a, b, abs = 1e-12, rel = 1e-12) {
  return Math.abs(a - b) <= Math.max(abs, rel * Math.max(Math.abs(a), Math.abs(b)));
}

function cMul(a, b) {
  return { re: a.re * b.re - a.im * b.im, im: a.re * b.im + a.im * b.re };
}

function cExp(angle) {
  return { re: Math.cos(angle), im: Math.sin(angle) };
}

function cDistance(a, b) {
  return Math.hypot(a.re - b.re, a.im - b.im);
}

function sorted(values) {
  return Array.from(values).sort((a, b) => a - b);
}

function maxDifference(a, b) {
  let result = 0;
  for (let i = 0; i < a.length; i += 1) result = Math.max(result, Math.abs(a[i] - b[i]));
  return result;
}

const PI2 = 2 * Math.PI;
const H = 6.62607015e-34;
const ELEMENTARY_CHARGE = 1.602176634e-19;
const ELECTRON_FLUX = H / ELEMENTARY_CHARGE;
const SUPERCONDUCTING_STEP = H / (2 * ELEMENTARY_CHARGE);
const SAMPLES = 1024;
const SITES = 128;
const SPECTRUM_STEPS = 401;
const GAUGE_TRIALS = 100;
const HOPPING = 1;
const FRINGE_CYCLES = 8;
const GAUGE_SEED = 0x6d2b79f5;

const SOURCE = Object.freeze({
  ehrenbergYear: 1949,
  ehrenbergVolume: 62,
  ehrenbergFirstPage: 8,
  ehrenbergLastPage: 21,
  abYear: 1959,
  abVolume: 115,
  abPage: 485,
  experimentYear: 1986,
  prlVolume: 56,
  prlPage: 792,
  praVolume: 34,
  praFirstPage: 815,
  praLastPage: 822,
  permalloyNm: 20,
  nbLowerNm: 200,
  nbUpperNm: 300,
  copperNm: 100,
  measureK: 5,
  compareK: 15,
  transitionK: 9,
  transitionUncertaintyK: 1,
  nbCriticalK: 9.2,
  asOfYear: 2026,
  siEdition: 9,
  siVersionMajor: 4,
  siVersionMinor: 1,
  siYear: 2026
});

function independentPhase(fluxInElectronPeriods) {
  return -PI2 * fluxInElectronPeriods;
}

function independentIntensity(x, fluxInElectronPeriods, cycles = FRINGE_CYCLES) {
  return 2 + 2 * Math.cos(PI2 * cycles * x + independentPhase(fluxInElectronPeriods));
}

function independentFringes(fluxInElectronPeriods, count = SAMPLES) {
  return Float64Array.from({ length: count }, (_, index) =>
    independentIntensity(index / (count - 1), fluxInElectronPeriods));
}

function independentLinks(theta, cut = 0, sites = SITES) {
  const links = new Float64Array(sites);
  links[((cut % sites) + sites) % sites] = theta;
  return links;
}

function independentTransform(links, chi) {
  return Float64Array.from(links, (alpha, j) => alpha + chi[j] - chi[(j + 1) % links.length]);
}

function independentWilson(links) {
  let product = { re: 1, im: 0 };
  for (const alpha of links) product = cMul(product, cExp(alpha));
  return product;
}

function independentRng(seed) {
  let state = seed >>> 0;
  return () => {
    state ^= state << 13;
    state ^= state >>> 17;
    state ^= state << 5;
    return (state >>> 0) / 4294967296;
  };
}

function independentGaugePhases(seed, sites = SITES) {
  const random = independentRng(seed);
  return Float64Array.from({ length: sites }, () => PI2 * (random() - 0.5));
}

function independentSpectrum(theta, sites = SITES, hopping = HOPPING) {
  return Float64Array.from({ length: sites }, (_, m) =>
    -2 * hopping * Math.cos((PI2 * m + theta) / sites));
}

function independentCovarianceResidual(base, transformed, chi, hopping = HOPPING) {
  let maximum = 0;
  for (let j = 0; j < base.length; j += 1) {
    const k = (j + 1) % base.length;
    const actualForward = cExp(transformed[j]);
    actualForward.re *= -hopping;
    actualForward.im *= -hopping;
    const expectedForward = cExp(base[j] + chi[j] - chi[k]);
    expectedForward.re *= -hopping;
    expectedForward.im *= -hopping;
    maximum = Math.max(maximum, cDistance(actualForward, expectedForward));
    maximum = Math.max(maximum, cDistance(
      { re: actualForward.re, im: -actualForward.im },
      { re: expectedForward.re, im: -expectedForward.im }
    ));
  }
  return maximum;
}

function independentGaugeAudit(theta) {
  const auditBase = independentLinks(theta, 0);
  const target = cExp(theta);
  let maxCovariance = 0;
  let maxWilson = 0;
  for (let trial = 0; trial < GAUGE_TRIALS; trial += 1) {
    const phases = independentGaugePhases((GAUGE_SEED + Math.imul(trial + 1, 0x9e3779b9)) >>> 0);
    const changed = independentTransform(auditBase, phases);
    maxCovariance = Math.max(maxCovariance, independentCovarianceResidual(auditBase, changed, phases));
    maxWilson = Math.max(maxWilson, cDistance(independentWilson(changed), target));
  }
  return {
    maxCovariance,
    maxWilson,
    linkUpdates: GAUGE_TRIALS * SITES,
    directedChecks: GAUGE_TRIALS * SITES * 2
  };
}

console.log('\nEQUATIONS AND EXACT CONSTANTS');
check('Planck constant matches the exact SI definition', H === 6.62607015e-34);
check('elementary charge matches the exact SI definition', ELEMENTARY_CHARGE === 1.602176634e-19);
check('electron flux period is h divided by e', close(ELECTRON_FLUX, 4.135667696923859e-15, 1e-29, 1e-15), ELECTRON_FLUX.toExponential(15));
check('superconducting step is h divided by two e', close(SUPERCONDUCTING_STEP, 2.0678338484619295e-15, 1e-29, 1e-15), SUPERCONDUCTING_STEP.toExponential(15));
check('electron period is twice the superconducting step', ELECTRON_FLUX / SUPERCONDUCTING_STEP === 2);
check('zero flux gives zero phase', Object.is(independentPhase(0), -0) || independentPhase(0) === 0);
check('half-period positive flux gives minus pi', close(independentPhase(0.5), -Math.PI));
check('one-period positive flux gives minus two pi', close(independentPhase(1), -PI2));
check('reversing flux reverses phase', close(independentPhase(-0.371), -independentPhase(0.371)));
check('zero-flux centre intensity is four', close(independentIntensity(0, 0), 4));
check('half-period centre intensity is zero', close(independentIntensity(0, 0.5), 0, 1e-14));
check('one-period centre intensity returns to four', close(independentIntensity(0, 1), 4));
check('intensity is periodic in one electron flux period', close(independentIntensity(0.173, -0.28), independentIntensity(0.173, 0.72)));
check('opposite flux reverses the fringe displacement', close(independentIntensity(0.125, 0.25), independentIntensity(-0.125, -0.25)));
const fringe = independentFringes(0.137);
check('fringe engine emits the declared sample count', fringe.length === SAMPLES);
check('every fringe intensity stays nonnegative', Math.min(...fringe) >= -1e-14);
check('every fringe intensity stays at or below four', Math.max(...fringe) <= 4 + 1e-14);

console.log('\nGAUGE COVARIANCE AND HOLONOMY');
const theta = independentPhase(0.371);
const base = independentLinks(theta, 17);
const chi = independentGaugePhases(GAUGE_SEED);
const transformed = independentTransform(base, chi);
const baseWilson = independentWilson(base);
const transformedWilson = independentWilson(transformed);
check('lattice has the declared number of links', base.length === SITES);
check('branch cut stores the phase on the selected link', close(base[17], theta));
check('all other unscrumbled links carry zero phase', base.every((value, index) => index === 17 || value === 0));
check('gauge phase generator emits one value per site', chi.length === SITES);
check('gauge phases lie in the chosen half-open interval', chi.every(value => value >= -Math.PI && value < Math.PI));
check('gauge scramble changes at least one local link', transformed.some((value, index) => Math.abs(value - base[index]) > 1e-6));
check('site-phase differences telescope around the ring', close(Array.from(transformed).reduce((a, b) => a + b, 0), theta, 1e-13));
check('unscrumbled Wilson loop equals exp i theta', cDistance(baseWilson, cExp(theta)) < 1e-13);
check('scrambled Wilson loop equals exp i theta', cDistance(transformedWilson, cExp(theta)) < 1e-13);
check('Wilson loop survives the gauge scramble', cDistance(baseWilson, transformedWilson) < 1e-13);
check('forward and reverse Hamiltonian links obey covariance', independentCovarianceResidual(base, transformed, chi) < 1e-14);
const movedBase = independentLinks(theta, 91);
check('moving the branch cut changes the local representation', movedBase[17] === 0 && movedBase[91] === theta);
check('moving the branch cut preserves the Wilson loop', cDistance(independentWilson(movedBase), baseWilson) < 1e-14);
const uniform = Float64Array.from({ length: SITES }, () => theta / SITES);
check('uniformly distributing the phase preserves its sum', close(Array.from(uniform).reduce((a, b) => a + b, 0), theta, 1e-13));
check('uniformly distributing the phase preserves the Wilson loop', cDistance(independentWilson(uniform), baseWilson) < 1e-13);

console.log('\nTIGHT-BINDING SPECTRUM');
const spectrum0 = independentSpectrum(0);
const spectrumTheta = independentSpectrum(theta);
const spectrumPeriod = independentSpectrum(theta + PI2);
check('spectrum has one energy per lattice site', spectrumTheta.length === SITES);
check('zero-flux m zero energy is minus two t', close(spectrum0[0], -2));
check('all energies remain inside the tight-binding band', Array.from(spectrumTheta).every(value => value >= -2 - 1e-14 && value <= 2 + 1e-14));
check('spectrum trace is zero', close(Array.from(spectrumTheta).reduce((a, b) => a + b, 0), 0, 1e-12));
check('sum of squared energies is two N t squared', close(Array.from(spectrumTheta).reduce((a, b) => a + b * b, 0), 2 * SITES, 1e-10));
check('adding one electron flux period preserves the spectrum as a set', maxDifference(sorted(spectrumTheta), sorted(spectrumPeriod)) < 1e-13);
check('changing the branch cut cannot enter the analytic spectrum', maxDifference(sorted(spectrumTheta), sorted(independentSpectrum(Array.from(movedBase).reduce((a, b) => a + b, 0)))) < 1e-13);
check('spectral grid evaluates the declared number of energies', SPECTRUM_STEPS * SITES === 51328);
check('gauge audit transforms the declared number of links', GAUGE_TRIALS * SITES === 12800);
check('gauge audit checks both directed entries per link', GAUGE_TRIALS * SITES * 2 === 25600);
const independentAudit = independentGaugeAudit(independentPhase(0.371));
check('full independent gauge audit has only floating-point Wilson error', independentAudit.maxWilson < 1e-12, independentAudit.maxWilson.toExponential(3));
check('full independent gauge audit has exact covariance construction', independentAudit.maxCovariance === 0);
check('full independent gauge audit reports every transformed link', independentAudit.linkUpdates === 12800);
check('full independent gauge audit reports every directed entry', independentAudit.directedChecks === 25600);

console.log('\nSUPERCONDUCTING PARITY');
for (let n = -6; n <= 6; n += 1) {
  const ratio = n / 2;
  const holonomy = cExp(independentPhase(ratio));
  const expected = n % 2 === 0 ? 1 : -1;
  check(`n=${n} gives the expected even-odd electron holonomy`, close(holonomy.re, expected, 1e-14) && close(holonomy.im, 0, 1e-14));
}
check('two superconducting steps equal one electron period', close(2 * SUPERCONDUCTING_STEP, ELECTRON_FLUX));
check('one superconducting step gives phase magnitude pi', close(Math.abs(independentPhase(SUPERCONDUCTING_STEP / ELECTRON_FLUX)), Math.PI));

console.log('\nSOURCE DATA TRANSCRIPTIONS');
for (const [name, expected] of Object.entries({
  ehrenbergYear: 1949, ehrenbergVolume: 62, ehrenbergFirstPage: 8, ehrenbergLastPage: 21,
  abYear: 1959, abVolume: 115, abPage: 485, experimentYear: 1986,
  prlVolume: 56, prlPage: 792, praVolume: 34, praFirstPage: 815, praLastPage: 822,
  permalloyNm: 20, nbLowerNm: 200, nbUpperNm: 300, copperNm: 100,
  measureK: 5, compareK: 15, transitionK: 9, transitionUncertaintyK: 1,
  nbCriticalK: 9.2, asOfYear: 2026, siEdition: 9, siVersionMajor: 4,
  siVersionMinor: 1, siYear: 2026
})) {
  check(`source datum ${name} matches the opened-source record`, SOURCE[name] === expected);
}
for (const doi of [
  '10.1088/0370-1301/62/1/303',
  '10.1103/PhysRev.115.485',
  '10.1103/PhysRevLett.56.792',
  '10.1103/PhysRevA.34.815',
  '10.59161/AUEZ1291'
]) {
  check(`displayed DOI is the opened-source identifier ${doi}`, html.includes(doi));
}

console.log('\nPAGE-COUPLING: EXECUTE THE SHIPPED PAGE ENGINE');
const engineMatch = html.match(/<script id="ab-engine">([\s\S]*?)<\/script>/);
check('page contains one extractable ABEngine script', Boolean(engineMatch));
let page = null;
if (engineMatch) {
  const context = vm.createContext({ console, Math, Float64Array, Array, Object });
  vm.runInContext(engineMatch[1], context, { filename: 'shipped-ab-engine.js' });
  page = context.ABEngine;
}
check('executed page script exports ABEngine', Boolean(page));

if (page) {
  check('page exact h matches independent exact h', page.DATA.h === H);
  check('page exact e matches independent exact e', page.DATA.e === ELEMENTARY_CHARGE);
  check('page h/e matches independent division', close(page.electronFluxQuantum(), ELECTRON_FLUX, 1e-29, 1e-15));
  check('page h/(2e) matches independent division', close(page.superconductingFluxQuantum(), SUPERCONDUCTING_STEP, 1e-29, 1e-15));
  for (const ratio of [-1, -0.5, -0.137, 0, 0.137, 0.5, 1]) {
    check(`page phase agrees independently at flux ratio ${ratio}`, close(page.phaseFromFluxRatio(ratio), independentPhase(ratio)));
  }
  for (const [x, ratio] of [[0, 0], [0, 0.5], [0.123, 0.371], [0.777, -0.284], [1, 1]]) {
    check(`page intensity agrees independently at x=${x}, ratio=${ratio}`, close(page.intensityAt(x, ratio), independentIntensity(x, ratio)));
  }
  const pageFringe = page.fringeSamples(0.137);
  check('page fringe array has independent length', pageFringe.length === fringe.length);
  check('page fringe samples match all independent samples', maxDifference(pageFringe, fringe) < 1e-13);
  const pageChi = page.gaugePhases(GAUGE_SEED);
  check('page pseudorandom gauge phases replay independently', maxDifference(pageChi, chi) === 0);
  const pageBase = page.baseLinks(theta, 17);
  check('page branch-cut links match independent links', maxDifference(pageBase, base) === 0);
  const pageTransformed = page.transformLinks(pageBase, pageChi);
  check('page gauge transform matches independent transform', maxDifference(pageTransformed, transformed) === 0);
  check('page Wilson product matches independent product', cDistance(page.wilson(pageTransformed), transformedWilson) < 1e-13);
  check('page covariance residual matches independent residual', close(page.covarianceResidual(pageBase, pageTransformed, pageChi), independentCovarianceResidual(base, transformed, chi), 1e-15));
  check('page spectrum matches all independent branches', maxDifference(page.spectrum(theta), spectrumTheta) < 1e-14);
  check('page spectrum periodicity check is below tolerance', page.spectrumDifference(theta, theta + PI2) < 1e-13);
  const pageGrid = page.spectralGrid();
  check('page spectral grid has the independent row count', pageGrid.length === SPECTRUM_STEPS);
  check('page spectral grid has the independent column count', pageGrid[0].length === SITES);
  let gridMaximum = 0;
  for (let fluxIndex = 0; fluxIndex < SPECTRUM_STEPS; fluxIndex += 1) {
    const ratio = -1 + 2 * fluxIndex / (SPECTRUM_STEPS - 1);
    gridMaximum = Math.max(gridMaximum, maxDifference(pageGrid[fluxIndex], independentSpectrum(independentPhase(ratio))));
  }
  check('all 51,328 shipped spectral evaluations match independently', gridMaximum < 1e-14, gridMaximum.toExponential(3));
  const pageAudit = page.gaugeAudit(independentPhase(0.371));
  check('page full-audit covariance maximum matches independently', close(pageAudit.maxCovariance, independentAudit.maxCovariance, 1e-15));
  check('page full-audit Wilson maximum matches independently', close(pageAudit.maxWilson, independentAudit.maxWilson, 1e-15));
  check('page full-audit link count matches independently', pageAudit.linkUpdates === independentAudit.linkUpdates);
  check('page full-audit directed count matches independently', pageAudit.directedChecks === independentAudit.directedChecks);
  for (let n = -3; n <= 3; n += 1) {
    check(`page shield ratio agrees independently for n=${n}`, page.shieldFluxRatio(n) === n / 2);
    check(`page parity class agrees independently for n=${n}`, close(page.parityClass(n), n % 2 === 0 ? 0 : Math.PI));
  }

  const pageSource = page.DATA.source;
  for (const key of Object.keys(SOURCE)) {
    check(`page source datum ${key} matches independent record`, pageSource[key] === SOURCE[key]);
  }

  const dataOutKeys = [...html.matchAll(/data-out="([^"]+)"/g)].map(match => match[1]);
  const supportedKeys = new Set([
    'model.sites', 'model.sitesB', 'model.sitesC', 'model.gaugeTrials', 'model.gaugeTrialsB',
    'model.fringeCycles', 'model.samplesB', 'model.spectrumSteps', 'computed.linkUpdates',
    'computed.directedChecks', 'computed.spectralEvaluations', 'source.experimentYear',
    'source.experimentYearB', 'source.experimentYearC', 'source.experimentYearD',
    'source.permalloyNm', 'source.nbLowerNm', 'source.nbUpperNm', 'source.copperNm',
    'source.measureK', 'source.compareK', 'source.transitionK', 'source.transitionUncertaintyK',
    'source.transitionUncertaintyK2', 'source.nbCriticalK', 'source.ehrenbergYear',
    'source.ehrenbergYearB', 'source.ehrenbergVolume', 'source.ehrenbergFirstPage',
    'source.ehrenbergLastPage', 'source.abYear', 'source.abYearB', 'source.abVolume',
    'source.abPage', 'source.prlVolume', 'source.prlPage', 'source.praVolume',
    'source.praFirstPage', 'source.praLastPage', 'source.asOfYear', 'source.siEdition',
    'source.siVersionMajor', 'source.siVersionMinor', 'source.siYear'
  ]);
  check('every visible data-out key has verifier coverage', dataOutKeys.every(key => supportedKeys.has(key)), `${new Set(dataOutKeys).size} unique keys`);
  check('all verifier-covered data-out keys are present on the page', [...supportedKeys].every(key => dataOutKeys.includes(key)));
}

check('page has no third-party script requests', [...html.matchAll(/<script[^>]+src="([^"]+)"/g)].every(match => match[1].startsWith('/')));
check('page has no third-party stylesheet requests', [...html.matchAll(/<link[^>]+rel="stylesheet"[^>]+href="([^"]+)"/g)].every(match => match[1].startsWith('/')));
check('page includes an aria-live status region', /role="status"[^>]+aria-live="polite"/.test(html));
check('page includes a visible focus style', /:focus-visible/.test(html));
check('page includes a reduced-motion guard', /prefers-reduced-motion:reduce/.test(html) && /prefers-reduced-motion: reduce/.test(html));
check('page bounds the main column to the viewport', /main\{width:min\(100%,54rem\)/.test(html));
check('page makes every canvas fluid-width', /canvas\{display:block;width:100%/.test(html));
check('page contains narrow-screen grid collapse', /@media\(max-width:650px\)[\s\S]*?\.metrics,\.depth-grid\{grid-template-columns:1fr\}/.test(html));
check('wide source tables scroll inside their own container', /\.scroll\{overflow-x:auto/.test(html));
check('all three range controls have explicit labels', ['flux-slider', 'n-slider', 'cut-slider'].every(id => html.includes(`for="${id}"`) && html.includes(`id="${id}"`)));
check('page ends with all load-bearing closing tags', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
check('page prose contains no prohibited em dash', !html.includes(String.fromCodePoint(0x2014)));

console.log('\nMUTATION SWEEP: EACH WRONG ENGINE MUST BE CAUGHT');
let mutationsAttempted = 0;
let mutationsCaught = 0;

function mutation(name, wrongValue, rightValue, tolerance = 1e-12) {
  mutationsAttempted += 1;
  const scale = Math.max(Math.abs(rightValue), Number.MIN_VALUE);
  const caught = Math.abs(wrongValue - rightValue) > tolerance * scale;
  if (caught) mutationsCaught += 1;
  check(`mutation caught: ${name}`, caught, `wrong=${wrongValue} right=${rightValue}`);
}

mutation('Planck constant shifted by one part per thousand', (H * 1.001) / ELEMENTARY_CHARGE, ELECTRON_FLUX, 1e-15);
mutation('elementary charge shifted by one percent', H / (ELEMENTARY_CHARGE * 0.99), ELECTRON_FLUX, 1e-15);
mutation('electron charge sign removed', PI2 * 0.137, independentPhase(0.137));
mutation('factor two pi removed from phase', -0.137, independentPhase(0.137));
mutation('interference cross term halved', 2 + Math.cos(independentPhase(0.371)), independentIntensity(0, 0.371));
mutation('superconducting step replaced by electron period', 3, 3 / 2);
mutation('odd trapped flux misclassified as phase zero', 0, Math.PI);

const wrongPlusTransform = Float64Array.from(base, (alpha, j) => alpha + chi[j] + chi[(j + 1) % base.length]);
mutation('gauge transform uses plus instead of minus', cDistance(independentWilson(wrongPlusTransform), baseWilson), 0, 1e-13);
const wrongOpenTransform = Float64Array.from(base, (alpha, j) => alpha + chi[j] - (j + 1 < base.length ? chi[j + 1] : 0));
mutation('last gauge link forgets periodic closure', cDistance(independentWilson(wrongOpenTransform), baseWilson), 0, 1e-13);
mutation('tight-binding energy sign flipped', 2 * Math.cos(theta / SITES), independentSpectrum(theta)[0]);
mutation('lattice truncated to the wrong site count', 127, SITES, 0);
mutation('spectral grid truncated by one flux point', 400 * SITES, SPECTRUM_STEPS * SITES, 0);
mutation('fringe array truncated by one screen sample', SAMPLES - 1, SAMPLES, 0);

check('all attempted mutations were caught', mutationsCaught === mutationsAttempted, `${mutationsCaught}/${mutationsAttempted}`);

console.log(`\nRESULT | ${checks - failures}/${checks} checks passed | mutations caught ${mutationsCaught}/${mutationsAttempted}`);
if (failures > 0) process.exitCode = 1;
