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

const TAU = 2 * Math.PI;
const KG = 0.97163540631;
const MAC_POS = 0.2500888;
const MAC_NEG = -0.255426;
let assertions = 0;
let failures = 0;

function report(ok, label, detail = '') {
  assertions += 1;
  if (!ok) failures += 1;
  console.log(`${ok ? 'ok' : 'FAIL'} ${String(assertions).padStart(3, '0')}  ${label}${detail ? ` | ${detail}` : ''}`);
}
function near(a, b, tolerance, label) {
  report(Number.isFinite(a) && Number.isFinite(b) && Math.abs(a - b) <= tolerance, label,
    `got ${a}, expected ${b}, tolerance ${tolerance}`);
}
function exact(a, b, label) { report(Object.is(a, b), label, `got ${String(a)}, expected ${String(b)}`); }
function truth(value, label, detail = '') { report(Boolean(value), label, detail); }
function mod(x, m) { return ((x % m) + m) % m; }
function gcd(a, b) { while (b) [a, b] = [b, a % b]; return Math.abs(a); }
function independentConvergents(maxQ) {
  const out = [];
  let f0 = 1, f1 = 1;
  while (f0 + f1 <= maxQ) {
    const q = f0 + f1;
    out.push({ p: f1, q });
    [f0, f1] = [f1, q];
  }
  return out;
}
function independentStep(theta, momentum, K) {
  const kicked = momentum + K * Math.sin(theta);
  return { theta: theta + kicked, momentum: kicked };
}
function independentTangent(theta, K) {
  const c = K * Math.cos(theta);
  return [1 + c, 1, c, 1];
}
function mul(A, B) {
  return [A[0] * B[0] + A[1] * B[2], A[0] * B[1] + A[1] * B[3],
    A[2] * B[0] + A[3] * B[2], A[2] * B[1] + A[3] * B[3]];
}
function independentIterate(theta, momentum, K, q, keep = false) {
  let M = [1, 0, 0, 1], action = 0, correction = 0;
  const points = keep ? [] : null;
  for (let i = 0; i < q; i += 1) {
    if (points) points.push({ theta, momentum });
    M = mul(independentTangent(theta, K), M);
    const next = independentStep(theta, momentum, K);
    const term = 0.5 * next.momentum ** 2 - K * Math.cos(theta);
    const y = term - correction;
    const sum = action + y;
    correction = (sum - action) - y;
    action = sum;
    ({ theta, momentum } = next);
  }
  return { theta, momentum, M, action, points };
}
function independentSolve(p, q, K, theta, momentum) {
  theta = mod(theta, TAU);
  for (let iteration = 0; iteration < 60; iteration += 1) {
    const z = independentIterate(theta, momentum, K, q);
    const f0 = z.theta - theta - TAU * p;
    const f1 = z.momentum - momentum;
    const error = Math.max(Math.abs(f0), Math.abs(f1));
    if (error < 2e-11) {
      const full = independentIterate(theta, momentum, K, q, true);
      return { theta, momentum, ...full, error, R: (2 - full.M[0] - full.M[3]) / 4 };
    }
    const [m0, m1, m2, m3] = z.M;
    const a = m0 - 1, b = m1, c = m2, d = m3 - 1;
    const determinant = a * d - b * c;
    if (!Number.isFinite(determinant) || Math.abs(determinant) < 1e-22) return null;
    const dx = (-f0 * d + b * f1) / determinant;
    const dy = (c * f0 - a * f1) / determinant;
    let scale = 1;
    for (; scale >= 1 / 65536; scale /= 2) {
      const nt = theta + scale * dx, ni = momentum + scale * dy;
      const trial = independentIterate(nt, ni, K, q);
      const e = Math.max(Math.abs(trial.theta - nt - TAU * p), Math.abs(trial.momentum - ni));
      if (e < error) { theta = mod(nt, TAU); momentum = ni; break; }
    }
    if (scale < 1 / 65536) return null;
  }
  return null;
}
const independentAnchorCache = new Map();
function independentAnchor(p, q, sign) {
  const key = `${p}/${q}/${sign}`;
  if (independentAnchorCache.has(key)) return independentAnchorCache.get(key);
  const phases = [0, .25, .5, .75, 1, 1.25, 1.5, 1.75, 2];
  const momenta = [-.5, -.25, 0, .25, .5];
  for (const pf of phases) for (const mf of momenta) {
    const root = independentSolve(p, q, KG, pf * TAU / q, TAU * p / q + mf * TAU / q);
    if (!root || root.R * sign <= .02) continue;
    independentAnchorCache.set(key, root);
    return root;
  }
  independentAnchorCache.set(key, null);
  return null;
}
function independentContinue(p, q, K, sign) {
  const anchor = independentAnchor(p, q, sign);
  if (!anchor) return null;
  if (Math.abs(K - KG) < 1e-15) return anchor;
  let theta = anchor.theta, momentum = anchor.momentum, root = anchor;
  for (let slice = 1; slice <= 32; slice += 1) {
    const kk = KG + (K - KG) * slice / 32;
    root = independentSolve(p, q, kk, theta, momentum);
    if (!root || root.R * sign <= 0) return null;
    theta = root.theta;
    momentum = root.momentum;
  }
  return root;
}
function independentTransitionSignal(K) {
  const aPlus = independentContinue(34, 55, K, 1);
  const aMinus = independentContinue(34, 55, K, -1);
  const bPlus = independentContinue(55, 89, K, 1);
  const bMinus = independentContinue(55, 89, K, -1);
  if (!aPlus || !aMinus || !bPlus || !bMinus) return NaN;
  const a = Math.sqrt(Math.abs(aPlus.R * aMinus.R));
  const b = Math.sqrt(Math.abs(bPlus.R * bMinus.R));
  return Math.log(b / a);
}
function independentFindTransition() {
  let low = .97, high = .974;
  let fLow = independentTransitionSignal(low), fHigh = independentTransitionSignal(high);
  if (!Number.isFinite(fLow) || !Number.isFinite(fHigh) || fLow * fHigh > 0) return null;
  for (let i = 0; i < 18; i += 1) {
    const mid = (low + high) / 2;
    const fMid = independentTransitionSignal(mid);
    if (!Number.isFinite(fMid)) return null;
    if (fLow * fMid <= 0) { high = mid; fHigh = fMid; }
    else { low = mid; fLow = fMid; }
  }
  return { low, high, estimate: (low + high) / 2, refinements: 18 };
}

console.log('SECTION: EQUATIONS AND ARITHMETIC');
near((Math.sqrt(5) - 1) / 2, 0.6180339887498948, 2e-16, 'inverse golden ratio from sqrt(5)');
near(((Math.sqrt(5) - 1) / 2) ** 2 + (Math.sqrt(5) - 1) / 2, 1, 3e-16, 'golden quadratic identity');
const expectedPairs = [[1,2],[2,3],[3,5],[5,8],[8,13],[13,21],[21,34],[34,55],[55,89],[89,144]];
const conv = independentConvergents(144);
exact(conv.length, expectedPairs.length, 'ten convergents through denominator 144');
conv.forEach((c, i) => {
  exact(c.p, expectedPairs[i][0], `convergent ${i + 1} numerator`);
  exact(c.q, expectedPairs[i][1], `convergent ${i + 1} denominator`);
  exact(gcd(c.p, c.q), 1, `convergent ${i + 1} is reduced`);
});
for (let i = 2; i < conv.length; i += 1) {
  exact(conv[i].p, conv[i - 1].p + conv[i - 2].p, `Fibonacci numerator recurrence at row ${i + 1}`);
  exact(conv[i].q, conv[i - 1].q + conv[i - 2].q, `Fibonacci denominator recurrence at row ${i + 1}`);
}

const stepCases = [
  [0, 0.7, 0.6], [Math.PI / 2, -0.2, 0.9], [Math.PI, 1.1, KG],
  [5.7, -3.2, 1.2], [-1.25, 9.4, 0.73]
];
for (const [theta, momentum, K] of stepCases) {
  const got = independentStep(theta, momentum, K);
  near(got.momentum, momentum + K * Math.sin(theta), 2e-15, `kick equation at theta ${theta}`);
  near(got.theta, theta + got.momentum, 2e-15, `drift uses kicked momentum at theta ${theta}`);
  const J = independentTangent(theta, K);
  near(J[0] * J[3] - J[1] * J[2], 1, 2e-15, `Jacobian determinant at theta ${theta}`);
}
near(63 / 64, 0.984375, 0, 'converse-KAM fraction');
near(63 / 64 - KG, 0.01273959369, 5e-15, 'gap from numerical candidate to rigorous exclusion');

console.log('SECTION: INDEPENDENT PERIODIC ORBITS');
const independentRows = [];
for (const { p, q } of conv) {
  const plus = independentAnchor(p, q, 1);
  const minus = independentAnchor(p, q, -1);
  independentRows.push({ p, q, plus, minus, gap: plus && minus ? Math.abs(plus.action - minus.action) : NaN });
  truth(plus, `${p}/${q} positive-residue branch found`);
  truth(minus, `${p}/${q} negative-residue branch found`);
  if (plus) {
    truth(plus.R > 0, `${p}/${q} positive branch has positive residue`, `R=${plus.R}`);
    truth(plus.error < 2e-11, `${p}/${q} positive branch closes`, `error=${plus.error}`);
  }
  if (minus) {
    truth(minus.R < 0, `${p}/${q} negative branch has negative residue`, `R=${minus.R}`);
    truth(minus.error < 2e-11, `${p}/${q} negative branch closes`, `error=${minus.error}`);
  }
  if (plus && minus) truth(Math.abs(plus.action - minus.action) > 0, `${p}/${q} action branches are numerically distinct`);
}
const tail = independentRows.slice(-4);
truth(tail.every(r => Math.abs(r.plus.R - MAC_POS) < .004), 'high-q positive residues reproduce MacKay neighborhood');
truth(tail.every(r => Math.abs(r.minus.R - MAC_NEG) < .004), 'high-q negative residues reproduce MacKay neighborhood');
for (let i = 1; i < tail.length; i += 1) truth(tail[i].gap < tail[i - 1].gap, `critical action gap descends from q=${tail[i - 1].q} to q=${tail[i].q}`,
  `${tail[i - 1].gap} -> ${tail[i].gap}`);
const independentTransition = independentFindTransition();
truth(independentTransition, 'independent finite-q transition proxy brackets');
if (independentTransition) {
  truth(independentTransition.low < independentTransition.high, 'independent transition interval is ordered');
  truth(independentTransition.low > KG, 'finite-q proxy remains distinct from published benchmark');
  exact(independentTransition.refinements, 18, 'independent transition uses disclosed refinement count');
}

console.log('SECTION: PAGE COUPLING');
const htmlPath = new URL('../../public/strata/kam-last-torus/index.html', import.meta.url);
const html = fs.readFileSync(htmlPath, 'utf8');
const match = html.match(/<script id="kam-engine">([\s\S]*?)<\/script>/);
truth(match, 'shipped engine script extracted from HTML');
const context = vm.createContext({ console, setTimeout, clearTimeout });
vm.runInContext(match[1], context, { filename: 'kam-last-torus-page-engine.js' });
const page = context.KAMEngine;
truth(page, 'shipped page engine executed in node:vm');
near(page.goldenOmega(), (Math.sqrt(5) - 1) / 2, 0, 'page omega matches independent expression');
const pageConv = Array.from(page.convergents(144), c => ({ p: c.p, q: c.q }));
exact(JSON.stringify(pageConv), JSON.stringify(conv), 'page convergent generator matches independent generator');
for (const [theta, momentum, K] of stepCases) {
  const a = page.mapStep(theta, momentum, K), b = independentStep(theta, momentum, K);
  near(a.theta, b.theta, 0, `page drift coupling at theta ${theta}`);
  near(a.momentum, b.momentum, 0, `page kick coupling at theta ${theta}`);
  const J = Array.from(page.tangent(theta, K));
  near(page.determinant(J), 1, 2e-15, `page determinant coupling at theta ${theta}`);
}
const orbitCase = independentIterate(.37, 2.4, .83, 34, true);
const pageOrbit = page.iterateLift(.37, 2.4, .83, 34, true);
near(pageOrbit.theta, orbitCase.theta, 0, 'page lifted theta after 34 steps');
near(pageOrbit.momentum, orbitCase.momentum, 0, 'page lifted momentum after 34 steps');
near(pageOrbit.action, orbitCase.action, 0, 'page compensated action after 34 steps');
for (let i = 0; i < 4; i += 1) near(pageOrbit.M[i], orbitCase.M[i], 0, `page monodromy entry ${i}`);

const pageRowsRaw = page.ladder(KG, 144);
const pageRows = Array.from(pageRowsRaw, r => r);
exact(pageRows.length, independentRows.length, 'page critical ladder row count');
for (let i = 0; i < pageRows.length; i += 1) {
  const a = pageRows[i], b = independentRows[i];
  exact(a.p, b.p, `page ladder p at q=${b.q}`);
  exact(a.q, b.q, `page ladder q at q=${b.q}`);
  near(a.plus.R, b.plus.R, 2e-9, `page positive residue at q=${b.q}`);
  near(a.minus.R, b.minus.R, 2e-9, `page negative residue at q=${b.q}`);
  near(a.gap, b.gap, 2e-10, `page action gap at q=${b.q}`);
}
const pageTransition = page.findTransition(55, 89);
truth(pageTransition, 'shipped page transition proxy brackets');
if (pageTransition && independentTransition) {
  near(pageTransition.low, independentTransition.low, 2e-8, 'page transition lower endpoint coupling');
  near(pageTransition.high, independentTransition.high, 2e-8, 'page transition upper endpoint coupling');
  near(pageTransition.estimate, independentTransition.estimate, 2e-8, 'page transition estimate coupling');
  exact(pageTransition.refinements, independentTransition.refinements, 'page transition refinement coupling');
}
near(page.SOURCE.kg, KG, 0, 'page published threshold transcription');
near(page.SOURCE.mackayPositive, MAC_POS, 0, 'page positive MacKay transcription');
near(page.SOURCE.mackayNegative, MAC_NEG, 0, 'page negative MacKay transcription');
exact(page.SOURCE.converseNumerator, 63, 'page converse-KAM numerator');
exact(page.SOURCE.converseDenominator, 64, 'page converse-KAM denominator');
exact(page.SOURCE.asOf, '2026-08-01', 'page open-edge date');
exact(page.SETTINGS.portraitSeeds, 64, 'page portrait seed count disclosed');
near(page.SETTINGS.controlLow, .6, 0, 'page control lower endpoint disclosed');
near(page.SETTINGS.controlHigh, 1.2, 0, 'page control upper endpoint disclosed');
exact(page.SETTINGS.portraitSteps, 2000, 'page portrait iterate count disclosed');
exact(page.SETTINGS.selectedSteps, 4000, 'page selected-orbit iterate count disclosed');
exact(page.SETTINGS.newtonIterations, 60, 'page Newton ceiling disclosed');
near(page.SETTINGS.newtonTolerance, 2e-11, 0, 'page Newton tolerance disclosed');
exact(page.SETTINGS.continuationSlices, 32, 'page continuation slices disclosed');
exact(page.SETTINGS.transitionRefinements, 18, 'page transition refinements disclosed');
near(page.SETTINGS.transitionLow, .97, 0, 'page transition lower bracket disclosed');
near(page.SETTINGS.transitionHigh, .974, 0, 'page transition upper bracket disclosed');

console.log('SECTION: DOCUMENT CONTRACT');
truth(html.includes('<meta name="aw-plain"'), 'plain-language metadata present');
truth(html.includes('role="status"') && html.includes('aria-live="polite"'), 'accessible live status present');
truth(html.includes(':focus-visible'), 'visible keyboard focus style present');
truth(html.includes('prefers-reduced-motion:reduce'), 'reduced-motion CSS guard present');
truth(html.includes('prefers-reduced-motion: reduce'), 'reduced-motion runtime guard present');
const remoteRuntimeUrls = Array.from(html.matchAll(/<(?:script|img|link)\b[^>]*(?:src|href)="(https?:\/\/[^\"]+)"/gi), m => m[1]);
truth(remoteRuntimeUrls.every(url => url.startsWith('https://artwaste.land/')), 'no third-party runtime requests', remoteRuntimeUrls.join(', '));
truth(html.trimEnd().endsWith('</html>'), 'HTML has final closing tag');
truth(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html), 'load-bearing closing tags are in order');
truth(!html.includes(String.fromCodePoint(8212)) && !html.includes('&' + 'mdash;'), 'no prohibited long-dash prose or entity');
truth(html.includes('Physics Reports</em> 52(5), 1979') && html.includes('10.1016/0370-1573(79)90023-1'), 'Chirikov 1979 source metadata transcribed');
truth(html.includes('Physica D</em> 411, 2020') && html.includes('2001.00086') && html.includes('2020.132569'), 'Sander and Meiss source metadata transcribed');
truth(html.includes('arXiv:nlin/0006021'), 'Chirikov 2000 source identifier transcribed');
truth(html.includes('Physica D</em> 7, 1983') && html.includes('0167-2789(83)90131-8'), 'MacKay 1983 source metadata transcribed');
truth(html.includes("IHÉS</em> 63, 1986") && html.includes('10.1007/BF02831625'), 'Mather 1986 source metadata transcribed');
truth(html.includes('Communications in Mathematical Physics</em> 98, 1985') && html.includes('10.1007/BF01209326'), 'MacKay and Percival 1985 source metadata transcribed');
truth(html.includes('min="0.6" max="1.2"') && html.includes('data-k="0.6"') && html.includes('data-k="1.2"'), 'shipped kick controls match disclosed endpoints');

console.log('SECTION: MUTATION SWEEP');
const baseTheta = .73, baseI = 1.19, baseK = .82;
const expectedStep = independentStep(baseTheta, baseI, baseK);
const expectedJ = independentTangent(baseTheta, baseK);
const expectedR = (2 - 3.4 - .7) / 4;
const expectedActionTerm = .5 * expectedStep.momentum ** 2 - baseK * Math.cos(baseTheta);
const mutations = [
  ['kick uses cosine', () => ({ ...expectedStep, momentum: baseI + baseK * Math.cos(baseTheta) }), x => Math.abs(x.momentum - expectedStep.momentum) < 1e-14],
  ['kick sign reversed', () => ({ ...expectedStep, momentum: baseI - baseK * Math.sin(baseTheta) }), x => Math.abs(x.momentum - expectedStep.momentum) < 1e-14],
  ['drift uses old momentum', () => ({ ...expectedStep, theta: baseTheta + baseI }), x => Math.abs(x.theta - expectedStep.theta) < 1e-14],
  ['Jacobian omits identity term', () => [baseK * Math.cos(baseTheta), 1, baseK * Math.cos(baseTheta), 1], x => Math.abs((x[0] * x[3] - x[1] * x[2]) - 1) < 1e-14],
  ['residue denominator changed', () => (2 - 3.4 - .7) / 2, x => Math.abs(x - expectedR) < 1e-14],
  ['action potential sign changed', () => .5 * expectedStep.momentum ** 2 + baseK * Math.cos(baseTheta), x => Math.abs(x - expectedActionTerm) < 1e-14],
  ['golden square root changed', () => (Math.sqrt(6) - 1) / 2, x => Math.abs(x - (Math.sqrt(5) - 1) / 2) < 1e-14],
  ['converse numerator changed', () => 62 / 64, x => Math.abs(x - 63 / 64) < 1e-14],
  ['benchmark last digit changed', () => 0.97163540632, x => Math.abs(x - KG) < 5e-12],
  ['Fibonacci recurrence changed', () => [1, 2, 3, 6], x => x[3] === x[2] + x[1]],
  ['monodromy multiplication reversed to identity', () => mul([1,0,0,1], [1,0,0,1]), x => Math.abs(x[0] - expectedJ[0]) < 1e-14],
  ['action gap forced to zero', () => 0, x => x > 0]
];
let caught = 0;
for (const [name, mutate, accepts] of mutations) {
  const detected = !accepts(mutate());
  if (detected) caught += 1;
  truth(detected, `mutation caught: ${name}`);
}
exact(caught, mutations.length, `mutation sweep caught ${caught} of ${mutations.length}`);

console.log(`SUMMARY: ${assertions - failures}/${assertions} assertions passed; mutations ${caught}/${mutations.length} caught.`);
if (failures) process.exitCode = 1;
