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

const PAGE = new URL('../../public/strata/perfect-sampling/index.html', import.meta.url);
const html = fs.readFileSync(PAGE, 'utf8');
let passed = 0;
let failed = 0;

function show(value) {
  if (typeof value === 'bigint') return `${value}n`;
  if (typeof value === 'string') return value;
  return JSON.stringify(value, (_, v) => typeof v === 'bigint' ? `${v}n` : v);
}

function check(name, actual, expected, tolerance = 0) {
  let ok;
  if (typeof actual === 'number' && typeof expected === 'number' && tolerance > 0) {
    ok = Number.isFinite(actual) && Math.abs(actual - expected) <= tolerance;
  } else if (Array.isArray(actual) || (actual && typeof actual === 'object')) {
    ok = show(actual) === show(expected);
  } else {
    ok = Object.is(actual, expected);
  }
  if (ok) {
    passed++;
    console.log(`ok ${String(passed + failed).padStart(3, '0')}  ${name}: ${show(actual)}`);
  } else {
    failed++;
    console.error(`not ok ${String(passed + failed).padStart(3, '0')}  ${name}: got ${show(actual)}, expected ${show(expected)}`);
  }
  return ok;
}

const K = Object.freeze({
  side: 6,
  beta: 0.30,
  start: 64,
  cap: 131072,
  enumHorizon: 16,
  defaultSeed: 9137,
  maps: [[0, 0, 1], [1, 2, 2]],
  spinGlassSide: 64,
  spinGlassBeta: 0.5,
  spinGlassSweeps: 631,
  randomStartExponent: 18,
  sublatticeExponent: 2048
});

function igcd(a, b) {
  a = a < 0n ? -a : a;
  b = b < 0n ? -b : b;
  while (b !== 0n) [a, b] = [b, a % b];
  return a;
}
function q(n, d = 1n) {
  if (d < 0n) [n, d] = [-n, -d];
  const g = igcd(n, d);
  return [n / g, d / g];
}
function qadd([a,b],[c,d]) { return q(a*d+c*b,b*d); }
function qsub([a,b],[c,d]) { return q(a*d-c*b,b*d); }
function qmul([a,b],[c,d]) { return q(a*c,b*d); }
function qdiv([a,b],[c,d]) { return q(a*d,b*c); }
function qstr([n,d]) { return d === 1n ? String(n) : `${n}/${d}`; }

function independentSolve(A, b) {
  const n = A.length;
  const aug = A.map((row, i) => row.map(x => q(...x)).concat([q(...b[i])]));
  for (let col = 0; col < n; col++) {
    const pivot = aug.findIndex((row, i) => i >= col && row[col][0] !== 0n);
    if (pivot < 0) throw new Error('singular system');
    [aug[col], aug[pivot]] = [aug[pivot], aug[col]];
    const scale = aug[col][col];
    for (let j = col; j <= n; j++) aug[col][j] = qdiv(aug[col][j], scale);
    for (let i = 0; i < n; i++) if (i !== col) {
      const factor = aug[i][col];
      for (let j = col; j <= n; j++) aug[i][j] = qsub(aug[i][j], qmul(factor, aug[col][j]));
    }
  }
  return aug.map(row => row[n]);
}

function independentMatrix(maps = K.maps) {
  return Array.from({length:3}, (_, from) => {
    const counts = [0,0,0];
    for (const map of maps) counts[map[from]]++;
    return counts.map(n => q(BigInt(n), BigInt(maps.length)));
  });
}

function independentStationary(maps = K.maps) {
  const P = independentMatrix(maps);
  const A = [];
  for (let destination = 0; destination < 2; destination++) {
    A.push(Array.from({length:3}, (_, from) => qsub(P[from][destination], from === destination ? q(1n) : q(0n))));
  }
  A.push([q(1n), q(1n), q(1n)]);
  return independentSolve(A, [q(0n), q(0n), q(1n)]);
}

function imask(mask, mapIndex, maps = K.maps) {
  let out = 0;
  for (let s = 0; s < 3; s++) if (mask & (1 << s)) out |= 1 << maps[mapIndex][s];
  return out;
}
function single(mask) {
  return mask === 1 ? 0 : mask === 2 ? 1 : mask === 4 ? 2 : -1;
}

function independentEnumeration(n, maps = K.maps, mutation = '') {
  const total = 2 ** n;
  const fixed = [0,0,0], forward = [0,0,0], cftp = [0,0,0];
  let forwardUnresolved = 0, cftpUnresolved = 0;
  for (let word = 0; word < total; word++) {
    let state = 0;
    let active = 7;
    let meeting = -1;
    for (let t = 0; t < n; t++) {
      const which = (word >>> t) & 1;
      state = maps[which][state];
      if (meeting < 0 || mutation === 'continue-after-meeting') {
        active = imask(active, which, maps);
        if (single(active) >= 0 && meeting < 0) meeting = single(active);
      }
    }
    fixed[state]++;
    if (meeting < 0) forwardUnresolved++; else forward[mutation === 'continue-after-meeting' ? single(active) : meeting]++;
    let pastImage = 7;
    const limit = mutation === 'skip-last-cftp-map' ? n - 1 : n;
    for (let t = 0; t < limit; t++) pastImage = imask(pastImage, (word >>> t) & 1, maps);
    const endpoint = single(pastImage);
    if (endpoint < 0) cftpUnresolved++; else cftp[endpoint]++;
  }
  return {total, fixed, forward, forwardUnresolved, cftp, cftpUnresolved};
}

function independentForwardAbsorption(maps = K.maps) {
  const transient = [3,5,6,7];
  return [0,1,2].map(target => {
    const A = [], b = [];
    for (let i = 0; i < transient.length; i++) {
      const row = transient.map(() => q(0n));
      row[i] = q(1n);
      let rhs = q(0n);
      for (let m = 0; m < 2; m++) {
        const next = imask(transient[i], m, maps);
        const s = single(next);
        if (s === target) rhs = qadd(rhs, q(1n,2n));
        else if (s < 0) {
          const j = transient.indexOf(next);
          row[j] = qsub(row[j], q(1n,2n));
        }
      }
      A.push(row); b.push(rhs);
    }
    return independentSolve(A,b)[3];
  });
}

function independentMix32(input, secondMultiplier = 0x846ca68b) {
  let x = input >>> 0;
  x = (x ^ (x >>> 16)) >>> 0;
  x = Math.imul(x, 0x7feb352d) >>> 0;
  x = (x ^ (x >>> 15)) >>> 0;
  x = Math.imul(x, secondMultiplier) >>> 0;
  return (x ^ (x >>> 16)) >>> 0;
}
function independentWord(seed, time, lane, secondMultiplier) {
  const input = (seed >>> 0) ^ Math.imul(time | 0, 0x9e3779b1) ^ Math.imul((lane + 1) | 0, 0x85ebca6b);
  return independentMix32(input, secondMultiplier);
}
function independentEvent(seed, time, secondMultiplier) {
  return {
    site: Math.floor(independentWord(seed,time,0,secondMultiplier) / 4294967296 * K.side * K.side),
    u: independentWord(seed,time,1,secondMultiplier) / 4294967296
  };
}
function probability(sum, beta = K.beta) { return 1 / (1 + Math.exp(-2 * beta * sum)); }
function isum(spins, site, openBoundary = false) {
  const r = Math.floor(site / K.side), c = site % K.side;
  if (openBoundary) {
    let z = 0;
    if (r > 0) z += spins[(r-1)*K.side+c];
    if (r+1 < K.side) z += spins[(r+1)*K.side+c];
    if (c > 0) z += spins[r*K.side+c-1];
    if (c+1 < K.side) z += spins[r*K.side+c+1];
    return z;
  }
  return spins[((r+K.side-1)%K.side)*K.side+c] + spins[((r+1)%K.side)*K.side+c] +
    spins[r*K.side+(c+K.side-1)%K.side] + spins[r*K.side+(c+1)%K.side];
}
function independentBounds(seed, horizon, options = {}) {
  const low = Array(K.side*K.side).fill(-1), high = Array(K.side*K.side).fill(1);
  for (let time = -horizon; time < 0; time++) {
    const event = independentEvent(seed,time,options.secondMultiplier);
    for (const spins of [low,high]) {
      const sum = isum(spins,event.site,options.openBoundary);
      spins[event.site] = event.u < probability(sum,options.beta ?? K.beta) ? 1 : -1;
    }
  }
  return {low,high,disagree:low.filter((x,i) => x !== high[i]).length};
}
function independentScan(seed, options = {}) {
  const trace = [];
  let updates = 0, result;
  const start = options.start ?? K.start, cap = options.cap ?? K.cap;
  for (let h = start; h <= cap; h *= 2) {
    result = independentBounds(seed,h,options);
    trace.push(result.disagree);
    updates += 2*h;
    if (result.disagree === 0) break;
  }
  return {trace,updates,horizon:start * 2 ** (trace.length-1),result};
}
function maxUpdates(start = K.start, cap = K.cap) {
  let sum = 0;
  for (let h = start; h <= cap; h *= 2) sum += 2*h;
  return sum;
}

console.log('\nEQUATIONS AND DATA');
check('lattice sites', K.side*K.side, 36);
check('all binary starts', 2n ** BigInt(K.side*K.side), 68719476736n);
check('two bounding trajectories', 2, 2);
check('start horizon', K.start, 64);
check('display cap', K.cap, 131072);
check('cap is a doubled horizon', Math.log2(K.cap/K.start), 11);
check('number of displayed horizons through cap', Math.log2(K.cap/K.start)+1, 12);
check('maximum local updates through cap', maxUpdates(), 524160);
check('maximum is below stated strict bound', maxUpdates() < 524288, true);

const probs = [-4,-2,0,2,4].map(s => probability(s));
check('heat-bath p(-4)', probs[0], 0.08317269649392238, 1e-15);
check('heat-bath p(-2)', probs[1], 0.23147521650098238, 1e-15);
check('heat-bath p(0)', probs[2], 0.5, 0);
check('heat-bath p(2)', probs[3], 0.7685247834990175, 1e-15);
check('heat-bath p(4)', probs[4], 0.9168273035060777, 1e-15);
check('logistic symmetry at neighbor sum 2', probs[1]+probs[3], 1, 1e-15);
check('logistic monotonicity over possible sums', probs.every((x,i) => i === 0 || x > probs[i-1]), true);

const P = independentMatrix().map(row => row.map(qstr));
check('transition row 0', P[0], ['1/2','1/2','0']);
check('transition row 1', P[1], ['1/2','0','1/2']);
check('transition row 2', P[2], ['0','1/2','1/2']);
check('transition row 0 sums to one', independentMatrix()[0].reduce(qadd), [1n,1n]);
check('transition row 1 sums to one', independentMatrix()[1].reduce(qadd), [1n,1n]);
check('transition row 2 sums to one', independentMatrix()[2].reduce(qadd), [1n,1n]);
check('D is coordinatewise monotone', K.maps[0][0] <= K.maps[0][1] && K.maps[0][1] <= K.maps[0][2], true);
check('U is coordinatewise monotone', K.maps[1][0] <= K.maps[1][1] && K.maps[1][1] <= K.maps[1][2], true);

const pi = independentStationary().map(qstr);
check('stationary component 0', pi[0], '1/3');
check('stationary component 1', pi[1], '1/3');
check('stationary component 2', pi[2], '1/3');
const absorb = independentForwardAbsorption().map(qstr);
check('forward stopped output at 0', absorb[0], '1/2');
check('forward stopped output at 1', absorb[1], '0');
check('forward stopped output at 2', absorb[2], '1/2');

const words = independentEnumeration(K.enumHorizon);
check('enumerated word count', words.total, 65536);
check('fixed burn-in counts from state 0', words.fixed, [21846,21845,21845]);
check('forward resolved counts by length 16', words.forward, [32767,0,32767]);
check('forward unresolved words', words.forwardUnresolved, 2);
check('CFTP endpoint counts at horizon 16', words.cftp, [21845,21844,21845]);
check('CFTP unresolved words', words.cftpUnresolved, 2);
check('fixed counts conserve all words', words.fixed.reduce((a,b)=>a+b,0), words.total);
check('forward counts plus unresolved conserve all words', words.forward.reduce((a,b)=>a+b,words.forwardUnresolved), words.total);
check('CFTP counts plus unresolved conserve all words', words.cftp.reduce((a,b)=>a+b,words.cftpUnresolved), words.total);

const defaultScan = independentScan(K.defaultSeed);
check('default seed horizon trace', defaultScan.trace, [30,22,17,0]);
check('default seed certified horizon', defaultScan.horizon, 512);
check('default seed updates', defaultScan.updates, 1920);
check('default seed endpoint equality', defaultScan.result.low, defaultScan.result.high);
check('default seed plus spins', defaultScan.result.low.filter(x=>x===1).length, 26);
check('event site stays in the lattice', Array.from({length:2048},(_,i)=>independentEvent(K.defaultSeed,-i-1).site).every(x=>x>=0&&x<36), true);
check('same indexed event is replayed exactly', independentEvent(9137,-128), independentEvent(9137,-128));

check('spin-glass site count from source data', K.spinGlassSide*K.spinGlassSide, 4096);
check('sampled initial configurations', 2 ** K.randomStartExponent, 262144);
check('sublattice state-space exponent', K.spinGlassSide*(K.spinGlassSide/2), 2048);
const powerLog = K.sublatticeExponent*Math.log10(2);
check('2^2048 decimal exponent', Math.floor(powerLog), 616);
check('2^2048 leading mantissa rounded to two decimals', Number((10**(powerLog-Math.floor(powerLog))).toFixed(2)), 3.23);
check('reported source beta retained as data', K.spinGlassBeta, 0.5);
check('reported source sweeps retained as data', K.spinGlassSweeps, 631);

console.log('\nPAGE STRUCTURE AND SOURCE RECORD');
check('canonical URL', /<link rel="canonical" href="https:\/\/artwaste\.land\/strata\/perfect-sampling\/"/.test(html), true);
check('local font only', /href="\/fonts\/fonts\.css"/.test(html), true);
check('no remote script or stylesheet requests', !/<script[^>]+src="https?:/i.test(html) && !/<link[^>]+rel="stylesheet"[^>]+href="https?:/i.test(html), true);
check('layer 1 precedes layer 2', html.indexOf('Layer 1 / the squeeze') < html.indexOf('Layer 2 / the direction matters'), true);
check('layer 2 precedes layer 3', html.indexOf('Layer 2 / the direction matters') < html.indexOf('Layer 3 / the open edge'), true);
check('visible check panel follows the open edge', html.indexOf('Layer 3 / the open edge') < html.indexOf('id="check-title"'), true);
check('ARIA live Ising readout', /id="ising-status" role="status" aria-live="polite"/.test(html), true);
check('ARIA live stopping-rule readout', /id="rule-law" role="status" aria-live="polite"/.test(html), true);
check('heat-bath equation and field convention shown', html.includes('exp(-2 beta sum of four neighbor spins)') && html.includes('J = 1, external field = 0'), true);
check('reduced-motion guard', /prefers-reduced-motion:reduce/.test(html) && /prefers-reduced-motion: reduce/.test(html), true);
check('visible focus styling', /:focus-visible/.test(html), true);
check('load-bearing ending', html.trim().endsWith('</script>\n</body>\n</html>'), true);
check('no em dash character', html.includes('\u2014'), false);
check('Propp-Wilson year', /year:1996/.test(html), true);
check('Propp-Wilson volume and pages', /Random Structures & Algorithms 9\(1-2\), 223-252/.test(html), true);
check('Novotny arXiv identifier', /arXiv:cond-mat\/9905195/.test(html), true);
check('Chanal-Krauth DOI', /10\.1103\/PhysRevLett\.100\.060601/.test(html), true);
check('Wilson read-once arXiv identifier', /arXiv:math\.PR\/9910050/.test(html), true);
check('unopened publisher disclosure', /publisher full text was not opened/i.test(html), true);

console.log('\nPAGE-COUPLING');
const engineMatch = html.match(/<script id="perfect-engine">([\s\S]*?)<\/script>/);
check('page engine script extracted', Boolean(engineMatch), true);
let pageEngine;
if (engineMatch) {
  const sandbox = {};
  vm.createContext(sandbox);
  vm.runInContext(engineMatch[1], sandbox, {filename:'perfect-sampling-page-engine.js'});
  pageEngine = sandbox.PerfectSamplingEngine;
}
check('shipped side constant', pageEngine.C.SIDE, K.side);
check('shipped beta constant', pageEngine.C.BETA, K.beta);
check('shipped cap constant', pageEngine.C.CAP, K.cap);
check('shipped enum horizon', pageEngine.C.ENUM_HORIZON, K.enumHorizon);
check('shipped matrix', Array.from(pageEngine.transitionMatrix(), row => Array.from(row, pageEngine.fstr)), P);
check('shipped stationary solve', Array.from(pageEngine.stationary(),pageEngine.fstr), pi);
check('shipped absorbing solve', Array.from(pageEngine.forwardAbsorption(),pageEngine.fstr), absorb);
const pageWords = pageEngine.enumerateWords(16);
check('shipped fixed enumeration', Array.from(pageWords.fixed), words.fixed);
check('shipped forward enumeration', Array.from(pageWords.forward), words.forward);
check('shipped forward unresolved', pageWords.forwardUnresolved, words.forwardUnresolved);
check('shipped CFTP enumeration', Array.from(pageWords.cftp), words.cftp);
check('shipped CFTP unresolved', pageWords.cftpUnresolved, words.cftpUnresolved);
check('shipped maximum doubling cost', pageEngine.maxDoublingUpdates(K.cap), maxUpdates());
check('shipped heat probability at -4', pageEngine.heatProbability(-4,K.beta), probs[0], 1e-15);
check('shipped event at indexed time', pageEngine.eventAt(9137,-128), independentEvent(9137,-128));
const pageScan = pageEngine.scanCFTP(K.defaultSeed);
check('shipped default trace', Array.from(pageScan.trace,x=>x.disagree), defaultScan.trace);
check('shipped default endpoint', Array.from(pageScan.result.low), defaultScan.result.low);
check('shipped default update count', pageScan.updates, defaultScan.updates);
check('shipped 2^2048 display', pageEngine.powerOfTwoScientific(2048,2), '3.23 x 10^616');
check('shipped source count', pageEngine.SOURCES.length, 4);
check('shipped source access labels', Array.from(pageEngine.SOURCES,s=>s.access), [
  'Publisher metadata and abstract retrieved; publisher full text was not opened. The theorem statement was cross-checked against the opened Novotny exposition.',
  'Opened.','Opened.','Opened.'
]);

console.log('\nMUTATION SWEEP');
const canonicalEvent = independentEvent(9137,-128);
const mutations = [
  ['lattice side 6 to 7', () => 2n**49n === 68719476736n],
  ['beta 0.30 to 0.31', () => Math.abs(probability(4,0.31)-probs[4]) <= 1e-15],
  ['D image of state 2 changed', () => show(independentMatrix([[0,0,0],[1,2,2]]).map(r=>r.map(qstr))) === show(P)],
  ['U image of state 0 changed', () => show(independentMatrix([[0,0,1],[0,2,2]]).map(r=>r.map(qstr))) === show(P)],
  ['enumeration horizon shortened', () => independentEnumeration(15).total === words.total],
  ['last CFTP map skipped', () => show(independentEnumeration(16,K.maps,'skip-last-cftp-map').cftp) === show(words.cftp)],
  ['forward process allowed past first meeting', () => show(independentEnumeration(16,K.maps,'continue-after-meeting').forward) === show(words.forward)],
  ['hash avalanche multiplier changed', () => show(independentEvent(9137,-128,0x846ca68d)) === show(canonicalEvent)],
  ['periodic boundary changed to open', () => independentScan(9137,{openBoundary:true}).trace.join(',') === defaultScan.trace.join(',')],
  ['cap halved', () => maxUpdates(K.start,K.cap/2) === maxUpdates()],
  ['starting horizon doubled', () => independentScan(9137,{start:128}).updates === defaultScan.updates],
  ['sample exponent 18 to 17', () => 2**17 === 262144],
  ['sublattice exponent 2048 to 2047', () => Math.floor(2047*Math.log10(2)) === 616 && (10**((2047*Math.log10(2))%1)).toFixed(2) === '3.23'],
  ['reported sweep datum changed', () => 630 === K.spinGlassSweeps]
];
let caught = 0;
for (const [name, mutatedCheck] of mutations) {
  let mutationPassed = false;
  try { mutationPassed = Boolean(mutatedCheck()); } catch { mutationPassed = false; }
  if (!mutationPassed) {
    caught++;
    console.log(`caught ${String(caught).padStart(2,'0')}  ${name}`);
  } else {
    failed++;
    console.error(`escaped mutation  ${name}`);
  }
}
check('all deliberate mutations caught', caught, mutations.length);
console.log(`MUTATIONS CAUGHT: ${caught}/${mutations.length}`);

console.log(`\nRESULT: ${passed} checks passed, ${failed} failed.`);
if (failed > 0) process.exitCode = 1;
