#!/usr/bin/env node
/*
  Independent and page-coupled verifier for The Integer Hiding in the Gap.
  Node 22, no dependencies.
*/
import fs from 'node:fs';
import vm from 'node:vm';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '../..');
const pagePath = path.join(root, 'public/strata/quantum-hall-chern/index.html');
const html = fs.readFileSync(pagePath, 'utf8');
let passed = 0;
let failed = 0;

function check(name, condition, detail = '') {
  if (condition) {
    passed++;
    console.log(`PASS ${String(passed + failed).padStart(2, '0')}  ${name}${detail ? `: ${detail}` : ''}`);
  } else {
    failed++;
    console.error(`FAIL ${String(passed + failed).padStart(2, '0')}  ${name}${detail ? `: ${detail}` : ''}`);
  }
}
function close(a, b, tol = 1e-10) { return Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tol; }
function relative(a, b, tol = 1e-12) { return Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b)); }
function sum(xs) { let s = 0; for (const x of xs) s += x; return s; }
function gcd(a, b) { a = Math.abs(a); b = Math.abs(b); while (b) [a, b] = [b, a % b]; return a; }

console.log('INDEPENDENT EQUATION CHECKS');

const H = 6.62607015e-34;
const ECHARGE = 1.602176634e-19;
const RK = H / (ECHARGE * ECHARGE);
const G0US = 1e6 / RK;
check('fixed Planck constant is represented exactly as the specified decimal', H === 6.62607015e-34);
check('fixed elementary charge is represented exactly as the specified decimal', ECHARGE === 1.602176634e-19);
check('von Klitzing quotient', close(RK, 25812.807459304513, 2e-11), RK.toFixed(12));
check('practical 15-significant-digit decimal', RK.toFixed(10) === '25812.8074593045', RK.toFixed(10));
check('conductance quantum in microsiemens', close(G0US, 38.74045864931824, 2e-14), G0US.toFixed(14));
check('resistance and conductance are reciprocal', relative(RK * G0US, 1e6, 2e-16));
check('C = 2 plateau resistance is half RK', close(RK / 2, 12906.403729652256, 2e-11));
check('C = 3 plateau resistance is one third RK', close(RK / 3, 8604.269153101504, 2e-11));

check('gcd reduces 12 and 30', gcd(12, 30) === 6);
check('1/3 is already reduced', gcd(1, 3) === 1);
check('2/6 reduces to denominator 3', 6 / gcd(2, 6) === 3);
let fractionCount = 0;
for (let q = 2; q <= 31; q++) for (let p = 1; p < q; p++) if (gcd(p, q) === 1) fractionCount++;
check('flux control contains every reduced proper fraction through q = 31', fractionCount === 307, String(fractionCount));
check('largest allowed denominator is 31', Math.max(...Array.from({ length: 30 }, (_, i) => i + 2)) === 31);

function independentGapLabel(p, q, r) {
  let best = null;
  for (let C = -q; C <= q; C++) {
    const numerator = r + p * C;
    if (numerator % q === 0 && (!best || Math.abs(C) < Math.abs(best.C) || (Math.abs(C) === Math.abs(best.C) && C > best.C))) best = { C, s: numerator / q };
  }
  return best;
}
const labels = [[1,3,1,-1],[1,3,2,1],[1,4,1,-1],[2,5,1,2],[2,5,2,-1]];
for (const [p,q,r,want] of labels) {
  const got = independentGapLabel(p,q,r);
  check(`Diophantine label alpha ${p}/${q}, gap ${r}`, got.C === want && r === got.s*q - got.C*p, `C = ${got.C}`);
}

function complexMatrix(n) { return { n, re: new Float64Array(n*n), im: new Float64Array(n*n) }; }
function at(n, r, c) { return r*n+c; }
function addHermitian(A, i, j, re, im) {
  A.re[at(A.n,i,j)] += re; A.im[at(A.n,i,j)] += im;
  if (i !== j) { A.re[at(A.n,j,i)] += re; A.im[at(A.n,j,i)] -= im; }
}
function independentHarper(p,q,kx,ky,hopping = 1,boundary = true) {
  const g = gcd(p,q); p /= g; q /= g;
  const A = complexMatrix(q);
  for (let m=0;m<q;m++) A.re[at(q,m,m)] = -2*hopping*Math.cos(ky+2*Math.PI*p*m/q);
  if (q === 1) { A.re[0] += -2*hopping*Math.cos(kx); return A; }
  for (let m=0;m<q-1;m++) addHermitian(A,m,m+1,-hopping,0);
  if (boundary) addHermitian(A,q-1,0,-hopping*Math.cos(q*kx),-hopping*Math.sin(q*kx));
  return A;
}
function trace(A) { let s=0; for(let i=0;i<A.n;i++) s+=A.re[at(A.n,i,i)]; return s; }
function frobenius2(A) { let s=0; for(let i=0;i<A.re.length;i++) s+=A.re[i]**2+A.im[i]**2; return s; }
function isHermitian(A,tol=1e-13) {
  for(let i=0;i<A.n;i++) for(let j=0;j<A.n;j++) if(Math.abs(A.re[at(A.n,i,j)]-A.re[at(A.n,j,i)])>tol || Math.abs(A.im[at(A.n,i,j)]+A.im[at(A.n,j,i)])>tol) return false;
  return true;
}

const h13 = independentHarper(1,3,0,0);
check('Harper 1/3 matrix dimension', h13.n === 3);
check('Harper 1/3 matrix is Hermitian', isHermitian(h13));
check('Harper 1/3 trace at zero momentum', close(trace(h13),0,1e-14), trace(h13).toExponential(2));
check('Harper 1/3 Frobenius norm squared', close(frobenius2(h13),12,1e-13), frobenius2(h13).toFixed(12));
const analytic13 = [-1-Math.sqrt(3),-1+Math.sqrt(3),2];
check('analytic lowest eigenvalue at alpha 1/3 and k = 0', close(analytic13[0],-2.732050807568877,1e-14));
check('analytic middle eigenvalue at alpha 1/3 and k = 0', close(analytic13[1],0.7320508075688772,1e-14));
check('analytic highest eigenvalue at alpha 1/3 and k = 0', analytic13[2] === 2);
check('analytic eigenvalues sum to trace', close(sum(analytic13),trace(h13),1e-14));
check('analytic eigenvalue squares equal matrix Frobenius norm', close(sum(analytic13.map(x=>x*x)),frobenius2(h13),1e-13));
check('analytic eigenvalue product equals determinant', close(analytic13.reduce((a,b)=>a*b,1),-4,1e-13));
const h12 = independentHarper(1,2,0,0);
check('q = 2 keeps both bonds between the two magnetic sites', close(h12.re[at(2,0,1)],-2,1e-14));
check('q = 2 analytic lower eigenvalue', close(-2*Math.sqrt(2),-2.8284271247461903,1e-14));
check('q = 2 analytic upper eigenvalue', close(2*Math.sqrt(2),2.8284271247461903,1e-14));
const h10 = independentHarper(0,1,0,0);
check('zero-flux one-site dispersion at Gamma is -4t', close(h10.re[0],-4,1e-14));
const generic = independentHarper(2,7,.173,-1.21);
check('generic magnetic Hamiltonian remains Hermitian', isHermitian(generic));
check('generic coprime Harper trace vanishes', close(trace(generic),0,1e-13), trace(generic).toExponential(2));

function independentRng(seed) {
  return () => { seed |= 0; seed = seed + 0x6D2B79F5 | 0; let t=seed; t=Math.imul(t^t>>>15,t|1); t^=t+Math.imul(t^t>>>7,t|61); return ((t^t>>>14)>>>0)/4294967296; };
}
function independentOnsites(n,W,seed) { const rng=independentRng(seed); return Float64Array.from({length:n},()=>W*(rng()-.5)); }
const onsite = independentOnsites(144,2,137);
const onsiteSum = sum(onsite);
const onsiteChecksum = sum(Array.from(onsite,(x,i)=>x*(i+1)));
check('seeded disorder has 144 onsite values', onsite.length === 144);
check('first seeded onsite value', close(onsite[0],0.4692872380837798,1e-15), onsite[0].toFixed(15));
check('last seeded onsite value', close(onsite[143],-0.44995874306187034,1e-15), onsite[143].toFixed(15));
check('all uniform onsite values lie in [-1,1)', Math.min(...onsite)>=-1 && Math.max(...onsite)<1);
check('seeded onsite sum', close(onsiteSum,-13.73838103748858,1e-12), onsiteSum.toFixed(12));
check('seeded onsite checksum', close(onsiteChecksum,-970.9345054924488,1e-10), onsiteChecksum.toFixed(9));
check('open 12 by 12 lattice has 264 undirected bonds', 2*12*11 === 264);
check('off-diagonal Frobenius contribution is 528', 2*(2*12*11) === 528);
const independentDisorderFrob = sum(Array.from(onsite,x=>x*x)) + 528;
check('independent disordered Frobenius norm is finite', Number.isFinite(independentDisorderFrob) && independentDisorderFrob>528);

console.log('\nPAGE-COUPLING');
const engineMatch = html.match(/<script id="qh-engine">([\s\S]*?)<\/script>/);
check('shipped engine script is extractable', Boolean(engineMatch));
let Q = null;
if (engineMatch) {
  const context = { Math, Float64Array, console: { log(){}, error(){} } };
  context.globalThis = context;
  vm.createContext(context);
  try { vm.runInContext(engineMatch[1], context, { filename: 'shipped-qh-engine.js' }); Q = context.QHEngine; }
  catch (error) { console.error(error); }
}
check('shipped engine executes without a DOM', Boolean(Q));
if (Q) {
  const si=Q.siValues();
  check('page Planck input matches independent input', si.h === H);
  check('page charge input matches independent input', si.e === ECHARGE);
  check('page RK matches independent quotient', close(si.rk,RK,1e-12));
  check('page conductance unit matches independent reciprocal', close(si.g0uS,G0US,1e-14));
  check('page fraction reducer maps 6/15 to 2/5', Q.reduceFraction(6,15).p===2 && Q.reduceFraction(6,15).q===5);
  for (const [p,q,r,want] of labels) check(`page gap label couples at ${p}/${q}, r ${r}`, Q.gapLabel(p,q,r).C===want);

  const A=Q.harper(1,3,0,0),EV=Q.eigHermitian(A);
  check('page Harper dimension matches independent dimension', A.n===h13.n);
  check('page Harper real entries match independent entries', Array.from(A.re).every((x,i)=>close(x,h13.re[i],1e-14)));
  check('page Harper imaginary entries match independent entries', Array.from(A.im).every((x,i)=>close(x,h13.im[i],1e-14)));
  check('page lowest eigenvalue matches analytic value', close(EV.values[0],analytic13[0],1e-11), EV.values[0].toFixed(12));
  check('page middle eigenvalue matches analytic value', close(EV.values[1],analytic13[1],1e-11), EV.values[1].toFixed(12));
  check('page highest eigenvalue matches analytic value', close(EV.values[2],analytic13[2],1e-11), EV.values[2].toFixed(12));
  check('page lowest eigenvector residual', Q.eigenResidual(A,EV,0)<1e-10, Q.eigenResidual(A,EV,0).toExponential(3));
  check('page middle eigenvector residual', Q.eigenResidual(A,EV,1)<1e-10, Q.eigenResidual(A,EV,1).toExponential(3));
  check('page highest eigenvector residual', Q.eigenResidual(A,EV,2)<1e-10, Q.eigenResidual(A,EV,2).toExponential(3));
  let maxOrtho=0;
  for(let a=0;a<3;a++) for(let b=0;b<3;b++) { let rr=0,ri=0; for(let r=0;r<3;r++){const ar=EV.vr[at(3,r,a)],ai=-EV.vi[at(3,r,a)],br=EV.vr[at(3,r,b)],bi=EV.vi[at(3,r,b)];rr+=ar*br-ai*bi;ri+=ar*bi+ai*br;} maxOrtho=Math.max(maxOrtho,Math.hypot(rr-(a===b?1:0),ri)); }
  check('page eigenvectors are orthonormal', maxOrtho<1e-11,maxOrtho.toExponential(3));

  const S=Q.spectrum(1,3,16);
  check('page 16 by 16 spectrum uses 256 momentum points', S.samples.length===256);
  check('page alpha 1/3 spectrum has three bands', S.bands.length===3);
  check('page alpha 1/3 spectrum exposes two sampled gaps', S.gaps.length===2);
  check('page first sampled gap is positive', S.gaps[0].width>0);
  check('page second sampled gap is positive', S.gaps[1].width>0);

  const C13=Q.chernMesh(1,3,1,21);
  const C132=Q.chernMesh(1,3,2,15);
  const C25=Q.chernMesh(2,5,1,15);
  check('page 21 mesh Chern for 1/3 first gap matches Diophantine integer', close(C13.chern,-1,1e-9),C13.chern.toFixed(12));
  check('page 15 mesh Chern for 1/3 second gap matches Diophantine integer', close(C132.chern,1,1e-9),C132.chern.toFixed(12));
  check('page 15 mesh Chern for 2/5 first gap matches Diophantine integer', close(C25.chern,2,1e-9),C25.chern.toFixed(12));
  check('page clean direct gap is open', C13.minGap>1);
  check('page occupied-subspace links are well conditioned', C13.minDet>.8);
  const refined=Q.chernRefined(1,3,1);
  check('page 15 and 21 meshes agree', Math.abs(refined.fine.chern-refined.coarse.chern)<1e-10);
  check('page marks the baseline invariant resolved', refined.resolved===true);

  const D=Q.disorderHamiltonian(12,1,3,2,137);
  check('page seeded onsite sequence matches independent sequence', Array.from(D.onsite).every((x,i)=>close(x,onsite[i],1e-15)));
  check('page seeded onsite checksum matches independent checksum', close(sum(Array.from(D.onsite,(x,i)=>x*(i+1))),onsiteChecksum,1e-11));
  check('page disordered matrix is Hermitian', isHermitian(D.A,1e-13));
  check('page disordered trace equals onsite sum', close(trace(D.A),onsiteSum,1e-12));
  check('page disordered Frobenius norm matches independent bond count', close(frobenius2(D.A),independentDisorderFrob,1e-10));
  const DE=Q.eigHermitian(D.A,1e-11,40), analysis=Q.analyzeEigenstates(DE);
  check('disordered eigenvalue sum matches trace', close(sum(DE.values),onsiteSum,2e-8));
  check('disordered eigenvalue squares match Frobenius norm', close(sum(Array.from(DE.values,x=>x*x)),independentDisorderFrob,2e-7));
  check('all IPR values satisfy 1/N lower bound', Math.min(...analysis.ipr)>=1/144-1e-11);
  check('all IPR values satisfy unit upper bound', Math.max(...analysis.ipr)<=1+1e-11);
  check('all participation fractions lie in [1/N,1]', Math.min(...analysis.pr)>=1/144-1e-11 && Math.max(...analysis.pr)<=1+1e-11);
  const marker=Q.localMarker(DE,-1.35,12);
  check('default Fermi energy occupies 48 states', marker.occupied===48,String(marker.occupied));
  check('default central marker reproduces the finite baseline', close(marker.average,-0.788100477672,2e-9),marker.average.toFixed(12));
  check('page prints marker deviation rather than forcing an integer', Math.abs(marker.average-Math.round(marker.average))>.1);
  const dos=Q.gaussianDOS(DE.values,-1.35,.12);
  check('default Gaussian DOS is positive and finite', Number.isFinite(dos)&&dos>0,dos.toFixed(9));
  check('default Gaussian DOS baseline', close(dos,4.518391775497,2e-8),dos.toFixed(12));
  let ptrace=0,pherm=true;for(let i=0;i<144;i++){ptrace+=marker.P.re[at(144,i,i)];for(let j=0;j<144;j++)if(Math.abs(marker.P.re[at(144,i,j)]-marker.P.re[at(144,j,i)])>1e-9||Math.abs(marker.P.im[at(144,i,j)]+marker.P.im[at(144,j,i)])>1e-9)pherm=false;}
  check('occupied projector trace equals occupied count', close(ptrace,marker.occupied,2e-8),ptrace.toFixed(9));
  check('occupied projector is Hermitian', pherm);
}

console.log('\nSHIPPED PAGE CONTRACT');
check('canonical URL is correct', html.includes('<link rel="canonical" href="https://artwaste.land/strata/quantum-hall-chern/"'));
check('plain-language metadata is present', html.includes('<!--aw-plain:start-->'));
check('page names the 16 by 16 base mesh', html.includes('16 by 16 momentum mesh'));
check('page names the 21 by 21 Chern mesh', html.includes('21 by 21 Chern calculation'));
check('page names the 15 by 15 refinement mesh', html.includes('15 by 15 versus 21 by 21'));
check('page names the 12 by 12 open lattice', html.includes('12 by 12 open lattice'));
check('page names the central 6 by 6 average', html.includes('central 6 by 6'));
check('page names the DOS broadening', html.includes('η = 0.12t'));
check('page names the exact SI effective date', html.includes('20 May 2019'));
check('page distinguishes exact quotient from realization', html.includes('The quotient is exact as a definition. The displayed decimal is rounded'));
check('page distinguishes localized bulk states from edge states', html.includes('a low-participation bulk state in this plot is not an edge state'));
check('page names the unresolved direct-gap threshold in its engine', html.includes('fine.minGap>1e-6'));
check('page names the unresolved overlap threshold in its engine', html.includes('fine.minDet>1e-8'));
check('page has an aria-live spectrum status', /id="spectrum-status"[^>]*role="status"[^>]*aria-live="polite"/.test(html));
check('page has a reduced-motion guard', html.includes('prefers-reduced-motion: reduce'));
check('page has a visible focus rule', html.includes(':focus-visible'));
check('page has no third-party script source', !/<script[^>]+src="https?:\/\//i.test(html));
check('page has load-bearing final tags', /<\/script><\/body><\/html>\s*$/.test(html));
check('page contains no Unicode em dash', !html.includes(String.fromCodePoint(0x2014)));

console.log('\nMUTATION SWEEP');
function baselineOracle(m) {
  const rk=m.h/(m.e*m.e);
  const gap=independentGapLabel(1,3,1).C*m.gapSign;
  const A=independentHarper(1,3,0,0,m.hopping,m.boundary);
  const os=independentOnsites(144,m.W,m.seed);
  const checksum=sum(Array.from(os,(x,i)=>x*(i+1)));
  const dosScale=.12/m.eta;
  const markerScale=m.markerFactor/(4*Math.PI);
  return relative(rk,RK,1e-13) && gap===-1 && close(frobenius2(A),12,1e-10) && close(checksum,onsiteChecksum,1e-9) && close(dosScale,1,1e-12) && close(markerScale,1,1e-12);
}
const base={h:H,e:ECHARGE,gapSign:1,hopping:1,boundary:true,W:2,seed:137,eta:.12,markerFactor:4*Math.PI};
check('unmutated oracle passes before sensitivity tests', baselineOracle(base));
const mutations=[
  ['Planck constant +0.1%',{h:H*1.001}],
  ['elementary charge +0.1%',{e:ECHARGE*1.001}],
  ['gap sign reversed',{gapSign:-1}],
  ['hopping reduced',{hopping:.9}],
  ['magnetic boundary bond removed',{boundary:false}],
  ['disorder width changed',{W:2.1}],
  ['disorder seed changed',{seed:138}],
  ['DOS width changed',{eta:.2}],
  ['marker prefactor halved',{markerFactor:2*Math.PI}]
];
let caught=0;
for(const [name,change] of mutations){const mutant={...base,...change};const detected=!baselineOracle(mutant);if(detected)caught++;check(`mutation caught: ${name}`,detected);}
let attempted=mutations.length;
function executeMutatedEngine(source) {
  const context={Math,Float64Array,console:{log(){},error(){}}};context.globalThis=context;vm.createContext(context);vm.runInContext(source,context);return context.QHEngine;
}
if(engineMatch){
  attempted++;
  const changedH=engineMatch[1].replace('var H_SI = 6.62607015e-34;','var H_SI = 6.7e-34;');
  const caughtH=!close(executeMutatedEngine(changedH).siValues().rk,RK,1e-12);if(caughtH)caught++;check('shipped-script mutation caught: changed Planck input',caughtH);
  attempted++;
  const changedSign=engineMatch[1].replace('var d=r+p*C','var d=r-p*C');
  const caughtSign=executeMutatedEngine(changedSign).gapLabel(1,3,1).C!==-1;if(caughtSign)caught++;check('shipped-script mutation caught: changed gap equation sign',caughtSign);
}
console.log(`Mutations caught: ${caught}/${attempted}`);
check('every attempted mutation was caught', caught===attempted);

console.log(`\nRESULT: ${passed} passed, ${failed} failed, ${passed+failed} total assertions.`);
if (passed < 40) {
  console.error('FAIL verifier itself has fewer than 40 assertions');
  process.exit(1);
}
process.exit(failed===0?0:1);
