#!/usr/bin/env node
import { readFileSync } from 'node:fs';
import vm from 'node:vm';

const PAGE = new URL('../../public/strata/anderson-localization/index.html', import.meta.url);
const html = readFileSync(PAGE, 'utf8');
let checks = 0;
let failures = 0;
let mutationsCaught = 0;
let mutationsAttempted = 0;

function report(ok, label, detail = '') {
  checks += 1;
  const suffix = detail ? ` | ${detail}` : '';
  if (ok) console.log(`PASS ${String(checks).padStart(3, '0')} | ${label}${suffix}`);
  else {
    failures += 1;
    console.error(`FAIL ${String(checks).padStart(3, '0')} | ${label}${suffix}`);
  }
}

function close(actual, expected, tolerance) {
  return Number.isFinite(actual) && Math.abs(actual - expected) <= tolerance;
}

function relativeClose(actual, expected, tolerance) {
  return Number.isFinite(actual) && Math.abs(actual - expected) <= tolerance * Math.max(1, Math.abs(expected));
}

console.log('ANDERSON LOCALIZATION VERIFIER');
console.log(`page: ${PAGE.pathname}`);

console.log('\nSECTION 1: PAGE STRUCTURE AND DISPLAYED SOURCE DATA');
report(html.startsWith('<!doctype html>'), 'doctype is present');
report(html.endsWith('</script>\n</body>\n</html>\n'), 'load-bearing closing tags are the file ending');
report(!html.includes('\u2014'), 'no em dash appears in shipped prose or code');
report(html.includes('<link rel="canonical" href="https://artwaste.land/strata/anderson-localization/"'), 'canonical URL');
report(html.includes('<link rel="stylesheet" href="/fonts/fonts.css"'), 'local font stylesheet only');
report(!/<(?:script|img|iframe|audio|video|source)\b[^>]*(?:src|srcset)="https?:\/\//i.test(html) && !/<link\b[^>]*rel="stylesheet"[^>]*href="https?:\/\//i.test(html), 'no remote asset request');
report((html.match(/role="status"/g) || []).length >= 5, 'at least five live status regions');
report(html.includes(':focus-visible'), 'visible keyboard focus rule');
report(html.includes('prefers-reduced-motion:reduce'), 'reduced-motion guard');
report(html.includes('Layer 1') && html.indexOf('Layer 1') < html.indexOf('Layer 2') && html.indexOf('Layer 2') < html.indexOf('Layer 3'), 'three layers occur in required order');
report(html.includes('The check'), 'visible check panel');
report(html.includes('2026-08-01') && html.includes('1 August 2026'), 'publication and open-edge dates agree');

const bibliography = [
  ['Absence of Diffusion in Certain Random Lattices', '1958', '10.1103/PhysRev.109.1492'],
  ['Anomaly in the Band Centre of the One-Dimensional Anderson Model', '1981', '10.1007/BF01294272'],
  ['Lyapounov exponent of the one dimensional Anderson model: weak disorder expansions', '1984', '10.1051/jphys:019840045080128300'],
  ['Scaling Theory of Localization: Absence of Quantum Diffusion in Two Dimensions', '1979', '10.1103/PhysRevLett.42.673'],
  ['Direct observation of Anderson localization of matter-waves in a controlled disorder', '2008', '0804.1621'],
  ['The Theory of Impurity Conduction', '1961', '10.1080/00018736100101271'],
  ['Critical exponent for the Anderson transition in the three dimensional orthogonal universality class', '2014', '1307.4483'],
  ['Localization for the one-dimensional Anderson model via positivity and large deviations for the Lyapunov exponent', '2019', '1706.06135'],
  ['Absence of diffusion in the Anderson tight binding model for large disorder or low energy', '1983', '10.1007/BF01209475']
];
for (const [title, year, id] of bibliography) {
  report(html.includes(title), `source title shipped: ${title}`);
  report(html.includes(year), `source year shipped: ${title}`, year);
  report(html.includes(id), `source identifier shipped: ${title}`, id);
}
report(html.includes('ν = 1.571'), 'displayed three-dimensional exponent');
report(html.includes('[1.563, 1.579]'), 'displayed exponent interval');
report(html.includes('x = Et/σ² = 12Et/W²'), 'published Derrida-Gardner scaled coordinate is disclosed');
report(html.includes('Eq. (59)') && html.includes('Eq. (77a)') && html.includes('Eq. (78a)'), 'Derrida-Gardner equation references are visible');
report(html.includes('σ²/t = W²/(12t)') && html.includes('clean bandwidth <span class="mono">4t</span>'), 'absolute anomaly scale is contrasted with the bandwidth');
report(html.includes('96[1 + 3/(16x²)]') && html.includes('1/E²') && html.includes('no sharp cutoff'), 'power-law anomaly tail and coefficient are disclosed');
report(html.includes('96(1 - E²/4t²)') && html.includes('It equals 96 only at'), 'ordinary reference retains the band factor');
report(html.includes('id="x-inspect" type="range" min="-24" max="24" step="2.4" value="0"'), 'scaled-energy slider uses the published coordinate directly');
report(!html.includes('6Et/W²') && !html.includes('/ (6 * hopping)'), 'obsolete half-scaled coordinate is absent');
report(!html.includes('105.2'), 'known 105.2 misprint is not quoted');

console.log('\nSECTION 2: INDEPENDENT EQUATIONS');

const MASK32 = 0xffffffffn;
function independentRandom(seed) {
  let state = BigInt(seed >>> 0 || 1831565813);
  return function () {
    state = (state ^ ((state << 13n) & MASK32)) & MASK32;
    state = (state ^ (state >> 17n)) & MASK32;
    state = (state ^ ((state << 5n) & MASK32)) & MASK32;
    return Number(state) / 4294967296;
  };
}

function independentMix(value) {
  let x = value >>> 0;
  x = Math.imul(x ^ (x >>> 16), 2246822507);
  x = Math.imul(x ^ (x >>> 13), 3266489909);
  return (x ^ (x >>> 16)) >>> 0;
}

function independentSeed(master, point, stream) {
  return independentMix((master + Math.imul(point + 1, 2654435761) + Math.imul(stream + 1, 1597334677)) >>> 0) || 1;
}

function independentVariance(width) {
  // Integral from -W/2 to W/2 of epsilon squared times density 1/W.
  const half = width / 2;
  return (2 * half ** 3 / 3) / width;
}

function independentWeakGamma(energy, width, hopping) {
  const sinSquared = 1 - (energy / (2 * hopping)) ** 2;
  return independentVariance(width) / (8 * hopping * hopping * sinSquared);
}

function gammaIntegral(quarterArgument, panels = 240000) {
  // With t = u^4, Gamma(a) = integral 4 u^(4a-1) exp(-u^4) du.
  const upper = 4;
  const h = upper / panels;
  function f(u) {
    if (u === 0) return quarterArgument === 0.25 ? 4 : 0;
    return 4 * u ** (4 * quarterArgument - 1) * Math.exp(-(u ** 4));
  }
  let sum = f(0) + f(upper);
  for (let i = 1; i < panels; i += 1) sum += (i % 2 ? 4 : 2) * f(i * h);
  return sum * h / 3;
}

function independentLyapunov(energy, width, hopping, sites, seed, angle = 0.37) {
  const random = independentRandom(seed);
  let vector = [Math.cos(angle), Math.sin(angle)];
  let logGrowth = 0;
  let epsilonSum = 0;
  let epsilonSquaredSum = 0;
  for (let i = 0; i < sites; i += 1) {
    const epsilon = (random() - 0.5) * width;
    const matrix = [[(energy - epsilon) / hopping, -1], [1, 0]];
    const product = [
      matrix[0][0] * vector[0] + matrix[0][1] * vector[1],
      matrix[1][0] * vector[0] + matrix[1][1] * vector[1]
    ];
    const norm = Math.hypot(product[0], product[1]);
    vector = [product[0] / norm, product[1] / norm];
    logGrowth += Math.log(norm);
    epsilonSum += epsilon;
    epsilonSquaredSum += epsilon * epsilon;
  }
  const mean = epsilonSum / sites;
  return {
    gamma: logGrowth / sites,
    xi: logGrowth > 0 ? sites / logGrowth : Infinity,
    sampleMean: mean,
    sampleVariance: epsilonSquaredSum / sites - mean * mean,
    finalVector: vector,
    logGrowth
  };
}

for (const energy of [-1.75, -0.4, 0, 0.9, 1.75]) {
  for (const epsilon of [-1.1, 0, 0.73]) {
    const a = energy - epsilon;
    const determinant = a * 0 - (-1) * 1;
    report(determinant === 1, `transfer determinant at E=${energy}, epsilon=${epsilon}`, String(determinant));
  }
}

for (const width of [0.1, 0.25, 0.35, 0.8, 2, 4]) {
  report(close(independentVariance(width), width * width / 12, 2e-15), `box variance from integral at W=${width}`, independentVariance(width).toPrecision(12));
}

for (const energy of [-1.5, -0.6, 0, 0.6, 1.5]) {
  const gamma = independentWeakGamma(energy, 0.8, 1);
  const closed = 0.8 ** 2 / (96 - 24 * energy ** 2);
  report(close(gamma, closed, 2e-16), `weak-disorder equation at E=${energy}`, gamma.toPrecision(12));
  const scaled = 0.8 ** 2 / gamma;
  const scaledClosed = 96 * (1 - energy ** 2 / 4);
  report(close(scaled, scaledClosed, 2e-14), `ordinary scaled length retains band factor at E=${energy}`, scaled.toPrecision(12));
}

const gammaQuarter = gammaIntegral(0.25);
const gammaThreeQuarter = gammaIntegral(0.75);
const independentKW = 12 * (gammaQuarter / gammaThreeQuarter) ** 2;
report(relativeClose(gammaQuarter, 3.625609908221908, 2e-11), 'Gamma(1/4) by transformed quadrature', gammaQuarter.toPrecision(15));
report(relativeClose(gammaThreeQuarter, 1.225416702465178, 2e-11), 'Gamma(3/4) by transformed quadrature', gammaThreeQuarter.toPrecision(15));
report(relativeClose(independentKW, 105.045101530871, 4e-10), 'Kappus-Wegner coefficient from independent integrals', independentKW.toPrecision(15));
report(close(1 / independentWeakGamma(0, 1, 1), 96, 1e-12), 'ordinary center coefficient', String(1 / independentWeakGamma(0, 1, 1)));
report(relativeClose((independentKW / 96 - 1) * 100, 9.4219807613, 5e-10), 'relative band-center lift', `${((independentKW / 96 - 1) * 100).toFixed(10)}%`);

const randomReference = independentRandom(608135816);
const randomValues = Array.from({ length: 6 }, () => randomReference());
const randomExpected = [0.8933073205407709, 0.6838496748823673, 0.263213315512985, 0.8577353795990348, 0.08799692546017468, 0.7697348799556494];
for (let i = 0; i < randomExpected.length; i += 1) {
  report(randomValues[i] === randomExpected[i], `independent xorshift32 reference output ${i + 1}`, randomValues[i].toPrecision(14));
}

for (const x of [-24, -12, -2.4, 0, 2.4, 12, 24]) {
  const width = 0.35;
  const energy = x * width * width / 12;
  const recovered = 12 * energy / (width * width);
  report(close(recovered, x, 2e-15), `scaled-energy round trip at x=${x}`, energy.toPrecision(10));
}

for (const x of [2, 4, 8, 20]) {
  const leadingTailExcess = 96 * (3 / 16) / (x * x);
  report(close(leadingTailExcess * x * x, 18, 2e-15), `Derrida-Gardner leading tail scales as 1/x^2 at x=${x}`, leadingTailExcess.toPrecision(10));
}

const independentCases = [
  [0.6, 0.8, 1, 5000, 608135816],
  [0, 0.35, 1, 12000, 123456789],
  [-0.8, 1.2, 1, 9000, 987654321],
  [0.2, 0.25, 1, 15000, 314159265]
];
for (const [energy, width, hopping, sites, seed] of independentCases) {
  const result = independentLyapunov(energy, width, hopping, sites, seed);
  report(Number.isFinite(result.gamma), `independent finite exponent E=${energy}, W=${width}`, result.gamma.toPrecision(12));
  report(close(result.finalVector[0] ** 2 + result.finalVector[1] ** 2, 1, 3e-15), `renormalized final vector E=${energy}, W=${width}`);
  report(Math.abs(result.sampleMean) < width * 0.04, `sample mean is consistent with centered box E=${energy}, W=${width}`, result.sampleMean.toPrecision(6));
  report(result.sampleVariance > 0, `sample variance is positive E=${energy}, W=${width}`, result.sampleVariance.toPrecision(6));
}

for (const scale of [0.25, 0.7, 1.8, 4]) {
  const base = independentLyapunov(0.31, 0.72, 1, 8000, 42424242).gamma;
  const scaled = independentLyapunov(0.31 * scale, 0.72 * scale, scale, 8000, 42424242).gamma;
  report(close(base, scaled, 3e-15), `dimensionless transfer invariance at scale ${scale}`, `${base.toPrecision(10)} vs ${scaled.toPrecision(10)}`);
}

for (const energy of [-1.2, -0.3, 0.4, 1.3]) {
  const clean = independentLyapunov(energy, 0, 1, 50000, 77).gamma;
  report(Math.abs(clean) < 5e-5, `clean in-band finite exponent tends to zero at E=${energy}`, clean.toExponential(3));
}

console.log('\nSECTION 3: PAGE COUPLING');
const match = html.match(/<script id="anderson-engine">([\s\S]*?)<\/script>/);
report(Boolean(match), 'page engine script extracted');
let engine;
if (match) {
  const context = vm.createContext({});
  vm.runInContext(match[1], context, { filename: 'shipped-anderson-engine.js' });
  engine = context.AndersonEngine;
  report(Boolean(engine), 'shipped page engine executes in node:vm');
} else {
  engine = null;
}

if (engine) {
  const expectedConstants = {
    T:1, BASE_N:250000, BASE_SEED:608135816, INITIAL_ANGLE:0.37,
    TRACE_EVERY:1000, X_MIN:-24, X_MAX:24, ENERGY_COUNT:21,
    DEPTH_N:300000, DEPTH_STREAMS:4, DEPTH_MASTER_SEED:2654435769
  };
  for (const [key, value] of Object.entries(expectedConstants)) {
    report(engine.C[key] === value, `page constant ${key}`, String(engine.C[key]));
  }
  for (const width of [0.25, 0.35, 0.8, 2.4]) {
    report(close(engine.boxVariance(width), independentVariance(width), 2e-15), `page box variance coupling at W=${width}`);
  }
  for (const energy of [-1.4, -0.2, 0, 0.7, 1.4]) {
    report(close(engine.weakGamma(energy, 0.8, 1), independentWeakGamma(energy, 0.8, 1), 2e-16), `page weak gamma coupling at E=${energy}`);
  }
  report(relativeClose(engine.kwCoefficient(), independentKW, 4e-10), 'page gamma-function engine matches independent quadrature', engine.kwCoefficient().toPrecision(15));
  report(engine.xGrid().length === 21, 'page energy grid count');
  report(close(engine.xGrid()[0], -24, 0) && close(engine.xGrid()[10], 0, 0) && close(engine.xGrid()[20], 24, 0), 'page energy grid endpoints and center');
  for (const x of [-24, -2.4, 0, 7.2, 24]) {
    const energy = engine.xToEnergy(x, 0.35, 1);
    report(close(energy, x * 0.35 ** 2 / 12, 2e-16), `page uses x = Et/sigma^2 at x=${x}`, energy.toPrecision(10));
    report(close(engine.energyToX(energy, 0.35, 1), x, 3e-15), `page published-coordinate inverse at x=${x}`);
  }

  const pageRandom = engine.xorshift32(608135816);
  for (let i = 0; i < randomExpected.length; i += 1) {
    report(pageRandom() === randomExpected[i], `page pseudorandom stream coupling ${i + 1}`);
  }

  for (const [energy, width, hopping, sites, seed] of independentCases) {
    const independent = independentLyapunov(energy, width, hopping, sites, seed);
    const shipped = engine.lyapunov(energy, width, hopping, sites, seed, 1000);
    report(relativeClose(shipped.gamma, independent.gamma, 2e-13), `shipped transfer exponent coupling E=${energy}, W=${width}`, `${shipped.gamma.toPrecision(12)} vs ${independent.gamma.toPrecision(12)}`);
    report(relativeClose(shipped.sampleMean, independent.sampleMean, 2e-13), `shipped sample mean coupling E=${energy}, W=${width}`);
    report(relativeClose(shipped.sampleVariance, independent.sampleVariance, 2e-13), `shipped sample variance coupling E=${energy}, W=${width}`);
    report(close(shipped.logGrowth / sites, shipped.gamma, 2e-16), `shipped accumulated log identity E=${energy}, W=${width}`);
    report(shipped.trace.at(-1)[0] === sites, `shipped convergence trace reaches final site E=${energy}, W=${width}`);
    report(relativeClose(shipped.trace.at(-1)[1], shipped.gamma, 2e-15), `shipped convergence endpoint equals exponent E=${energy}, W=${width}`);
  }

  const point = engine.profilePoint(0, 0.35, 1, 20000, 4, engine.C.DEPTH_MASTER_SEED, 10);
  let gammaSum = 0;
  for (let stream = 0; stream < 4; stream += 1) {
    const seed = independentSeed(engine.C.DEPTH_MASTER_SEED, 10, stream);
    report(engine.streamSeed(engine.C.DEPTH_MASTER_SEED, 10, stream) === seed, `page depth seed coupling stream ${stream + 1}`, String(seed));
    gammaSum += independentLyapunov(0, 0.35, 1, 20000, seed).gamma;
  }
  const pointExpected = 0.35 ** 2 / (gammaSum / 4);
  report(relativeClose(point.scaled, pointExpected, 2e-13), 'page profile point couples all independent streams', `${point.scaled.toPrecision(12)} vs ${pointExpected.toPrecision(12)}`);
  report(point.work === 80000, 'page profile point reports exact work', String(point.work));

  const defaultRun = engine.lyapunov(0.6, 0.8, 1, engine.C.BASE_N, engine.C.BASE_SEED, engine.C.TRACE_EVERY);
  console.log('\nRECOMPUTED DEFAULT PAGE NUMBERS');
  console.log(`ordinary center coefficient       ${String(1 / engine.weakGamma(0, 1, 1))}`);
  console.log(`band-center coefficient          ${engine.kwCoefficient().toFixed(9)}`);
  console.log(`band-center relative lift        ${((engine.kwCoefficient() / 96 - 1) * 100).toFixed(9)}%`);
  console.log(`default finite gamma             ${defaultRun.gamma.toPrecision(12)}`);
  console.log(`default amplitude length         ${defaultRun.xi.toPrecision(12)} sites`);
  console.log(`default disorder sample mean     ${defaultRun.sampleMean.toPrecision(12)}`);
  console.log(`default disorder sample variance ${defaultRun.sampleVariance.toPrecision(12)}`);
  console.log(`default weak forecast            ${engine.weakXi(0.6, 0.8, 1).toPrecision(12)} sites`);
  console.log(`depth grid                       ${engine.xGrid().length} points from ${engine.xGrid()[0]} to ${engine.xGrid().at(-1)}`);
}

console.log('\nSECTION 4: MUTATION SWEEP');
function mutation(label, corruptedValue, validator) {
  mutationsAttempted += 1;
  const caught = !validator(corruptedValue);
  if (caught) mutationsCaught += 1;
  report(caught, `mutation caught: ${label}`, `mutated result ${String(corruptedValue)}`);
}

mutation('flip the transfer off-diagonal sign', -1, value => close(value, 1, 1e-15));
mutation('replace box variance divisor 12 with 11', 0.8 ** 2 / 11, value => close(value, independentVariance(0.8), 1e-15));
mutation('replace weak center coefficient 96 with 95', 95, value => close(value, 96, 1e-12));
mutation('invert the gamma-function ratio', 12 * (gammaThreeQuarter / gammaQuarter) ** 2, value => relativeClose(value, independentKW, 4e-10));
mutation('replace scaled-energy factor 12 with 11', 11 * 0.02 / 0.35 ** 2, value => close(value, 12 * 0.02 / 0.35 ** 2, 1e-14));
mutation('drop the ordinary band-dispersion factor', 96, value => close(value, 96 * (1 - 0.6 ** 2 / 4), 1e-14));
mutation('replace the 1/x^2 tail with 1/x', 18 / 4, value => close(value, 18 / (4 * 4), 1e-14));
mutation('drop one endpoint from the energy grid', 20, value => value === 21);
mutation('change the first xorshift left shift from 13 to 12', (() => {
  let x = 608135816 | 0;
  x ^= x << 12; x ^= x >>> 17; x ^= x << 5;
  return (x >>> 0) / 4294967296;
})(), value => value === randomExpected[0]);
mutation('add the previous amplitude instead of subtracting it', (() => {
  const random = independentRandom(608135816);
  let a = Math.cos(0.37), b = Math.sin(0.37), sum = 0;
  for (let i = 0; i < 5000; i += 1) {
    const epsilon = (random() - 0.5) * 0.8;
    const next = (0.6 - epsilon) * a + b;
    const norm = Math.hypot(next, a);
    b = a / norm; a = next / norm; sum += Math.log(norm);
  }
  return sum / 5000;
})(), value => relativeClose(value, independentLyapunov(0.6, 0.8, 1, 5000, 608135816).gamma, 2e-13));
mutation('divide accumulated growth by N minus one', (() => {
  const r = independentLyapunov(0.6, 0.8, 1, 5000, 608135816);
  return r.logGrowth / 4999;
})(), value => relativeClose(value, independentLyapunov(0.6, 0.8, 1, 5000, 608135816).gamma, 2e-13));
mutation('report intensity length as amplitude length', (() => {
  const r = independentLyapunov(0.6, 0.8, 1, 5000, 608135816);
  return 1 / (2 * r.gamma);
})(), value => relativeClose(value, independentLyapunov(0.6, 0.8, 1, 5000, 608135816).xi, 2e-13));
mutation('reuse one stream four times', (() => {
  const seed = independentSeed(2654435769, 10, 0);
  const g = independentLyapunov(0, 0.35, 1, 20000, seed).gamma;
  return 0.35 ** 2 / g;
})(), value => {
  let sum = 0;
  for (let s = 0; s < 4; s += 1) sum += independentLyapunov(0, 0.35, 1, 20000, independentSeed(2654435769, 10, s)).gamma;
  return relativeClose(value, 0.35 ** 2 / (sum / 4), 2e-13);
});
mutation('change fixed hopping without rescaling energy and disorder', independentLyapunov(0.6, 0.8, 1.1, 5000, 608135816).gamma, value => relativeClose(value, independentLyapunov(0.6, 0.8, 1, 5000, 608135816).gamma, 2e-13));

console.log(`\nMUTATIONS CAUGHT: ${mutationsCaught}/${mutationsAttempted}`);
report(mutationsCaught === mutationsAttempted, 'mutation sweep catches every attempted corruption', `${mutationsCaught}/${mutationsAttempted}`);

console.log(`\nASSERTIONS: ${checks - failures}/${checks} passed`);
if (checks < 40) {
  console.error(`FAIL verifier contract: only ${checks} assertions`);
  process.exitCode = 1;
} else if (failures) {
  console.error(`FAIL ${failures} assertion(s) failed`);
  process.exitCode = 1;
} else {
  console.log('SUCCESS every independent, coupled, and mutation check passed');
}
