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

const PAGE = new URL('../../public/strata/exotic-spheres/index.html', import.meta.url);
const html = fs.readFileSync(PAGE, 'utf8');
let checks = 0;
let failures = 0;

function show(ok, label, detail = '') {
  checks++;
  if (!ok) failures++;
  process.stdout.write(`${ok ? 'PASS' : 'FAIL'} ${String(checks).padStart(3, '0')}  ${label}${detail ? `: ${detail}` : ''}\n`);
}
function sameBigList(a, b) { return a.length === b.length && a.every((x, i) => x === b[i]); }
function absI(a) { return a < 0n ? -a : a; }
function modI(a, n) { const r = a % n; return r < 0n ? r + n : r; }
function gcdI(a, b) { a = absI(a); b = absI(b); while (b) [a, b] = [b, a % b]; return a; }
function fracI(num, den) {
  if (den <= 0n) throw new Error('positive denominator required');
  num = modI(num, den);
  if (num === 0n) return { num: 0n, den: 1n };
  const g = gcdI(num, den);
  return { num: num / g, den: den / g };
}
function fracEqI(a, b) { return a.num * b.den === b.num * a.den; }
function fracOppI(a, b) { return modI(a.num * b.den + b.num * a.den, a.den * b.den) === 0n; }
function sphereClassI(m) { return modI(m * (m + 1n) / 2n, 28n); }
function invariantsI(m, n) {
  if (n <= 0n) throw new Error('n must be positive');
  const numerator = (n + 2n * m) ** 2n - n;
  return {
    m, n, h4Order: n, linkingNumerator: 1n, linkingDenominator: n,
    pHalf: modI(2n * m, n), mu: fracI(numerator, 224n * n),
    s1: fracI(numerator, 8n * n), rawNumerator: numerator
  };
}
function rootsI(n, sign) {
  const out = [];
  for (let a = 0n; a < n; a++) if (modI(a * a, n) === modI(sign, n)) out.push(a);
  return out;
}
function witnessI(roots, test) { for (const a of roots) if (test(a)) return a; return null; }
function result(ok, alpha) { return { ok, alpha }; }
function classifyI(mA, nA, mB, nB) {
  const A = invariantsI(mA, nA), B = invariantsI(mB, nB);
  if (nA !== nB) {
    const no = result(false, null);
    return { A, B, sameN: false, d: gcdI(nA, 12n), plusRoots: [], minusRoots: [], homPlus: no, homMinus: no, homePlus: no, homeMinus: no, diffPlus: no, diffMinus: no, candidates: 0n };
  }
  const n = nA, d = gcdI(n, 12n), plusD = rootsI(d, 1n), plus = rootsI(n, 1n), minus = rootsI(n, -1n);
  const hp = witnessI(plusD, a => modI(mB - a * mA, d) === 0n);
  const reverseParity = n % 2n === 1n || modI(mA + mB, 2n) === 1n;
  const hm = minus.length > 0 && reverseParity ? minus[0] : null;
  const pTest = a => modI(B.pHalf - a * A.pHalf, n) === 0n;
  const hop = witnessI(plus, a => pTest(a) && fracEqI(A.s1, B.s1));
  const hom = witnessI(minus, a => pTest(a) && fracOppI(A.s1, B.s1));
  const dip = witnessI(plus, a => pTest(a) && fracEqI(A.mu, B.mu));
  const dim = witnessI(minus, a => pTest(a) && fracOppI(A.mu, B.mu));
  return {
    A, B, sameN: true, d, plusRoots: plus, minusRoots: minus,
    homPlus: result(hp !== null, hp), homMinus: result(hm !== null, hm),
    homePlus: result(hop !== null, hop), homeMinus: result(hom !== null, hom),
    diffPlus: result(dip !== null, dip), diffMinus: result(dim !== null, dim), candidates: d + 2n * n
  };
}
function signature(R) {
  return [R.sameN, R.d, R.homPlus.ok, R.homPlus.alpha, R.homMinus.ok, R.homMinus.alpha,
    R.homePlus.ok, R.homePlus.alpha, R.homeMinus.ok, R.homeMinus.alpha,
    R.diffPlus.ok, R.diffPlus.alpha, R.diffMinus.ok, R.diffMinus.alpha,
    R.A.pHalf, R.A.mu.num, R.A.mu.den, R.A.s1.num, R.A.s1.den,
    R.B.pHalf, R.B.mu.num, R.B.mu.den, R.B.s1.num, R.B.s1.den, R.candidates].map(v => String(v)).join('|');
}

console.log('\nSTRUCTURE AND SOURCE-DATA CHECKS');
show(html.startsWith('<!doctype html>'), 'page starts with the HTML doctype');
show(html.trimEnd().endsWith('</script>\n</body>\n</html>'), 'load-bearing closing tags are present and ordered');
show(!html.includes('\u2014'), 'page contains no em dash');
show(!/<(?:script|img)\b[^>]*\bsrc=["']https?:\/\//i.test(html) && !/<link\b[^>]*\brel=["']stylesheet["'][^>]*\bhref=["']https?:\/\//i.test(html), 'no third-party asset request appears');
for (const id of ['layer1-title','layer2-title','open-title','check-title','sphere-status','pair-status']) {
  show(html.includes(`id="${id}"`), `required visible or live region exists: ${id}`);
}
for (const [datum, label] of [
  ['1956','Milnor publication year'],['1962','Eells-Kuiper publication year'],['1963','Kervaire-Milnor publication year'],
  ['2003','Crowley-Escher publication year'],['1982','Freedman publication year'],['2026-08-01','open-edge status date'],
  ['10.2307/1969983','Milnor DOI'],['10.1007/BF02412768','Eells-Kuiper DOI'],['10.2307/1970128','Kervaire-Milnor DOI'],
  ['10.1016/S0926-2245(03)00012-3','Crowley-Escher DOI'],['10.4310/jdg/1214437136','Freedman DOI']
]) show(html.includes(datum), `source transcription present: ${label}`);

console.log('\nINDEPENDENT BASE DERIVATION');
const expectedSequence = [0,1,3,6,10,15,21,0,8,17,27,10,22,7,21,8,24,13,3,22,14,7,1,24,20,17,15,14,14,15,17,20,24,1,7,14,22,3,13,24,8,21,7,22,10,27,17,8,0,21,15,10,6,3,1,0].map(BigInt);
for (let m = 0; m < expectedSequence.length; m++) show(sphereClassI(BigInt(m)) === expectedSequence[m], `m=${m} gives oriented class ${expectedSequence[m]}`);
const reachedI = [...new Set(expectedSequence.map(String))].map(BigInt).sort((a,b) => a < b ? -1 : a > b ? 1 : 0);
const expectedReached = [0,1,3,6,7,8,10,13,14,15,17,20,21,22,24,27].map(BigInt);
const expectedMissing = [2,4,5,9,11,12,16,18,19,23,25,26].map(BigInt);
show(sameBigList(reachedI, expectedReached), 'reached set is the specified 16 residues');
show(reachedI.length === 16, 'bundle family reaches 16 oriented classes');
show(reachedI.filter(x => x !== 0n).length === 15, 'bundle family reaches 15 exotic oriented classes');
const missingI = Array.from({length:28},(_,i)=>BigInt(i)).filter(x => !reachedI.includes(x));
show(sameBigList(missingI, expectedMissing), 'the complementary 12 classes are exact');
for (let m = -28n; m <= 28n; m++) show(sphereClassI(m + 56n) === sphereClassI(m), `period 56 holds at m=${m}`);
let orbitCount = 0; const orbitSeen = new Set();
for (let r = 0n; r < 28n; r++) if (!orbitSeen.has(String(r))) { orbitCount++; orbitSeen.add(String(r)); orbitSeen.add(String(modI(-r,28n))); }
show(orbitCount === 15, 'orientation reversal gives 15 unoriented sphere types');
show(modI(-0n,28n) === 0n, 'class 0 is fixed by orientation reversal');
show(modI(-14n,28n) === 14n, 'class 14 is fixed by orientation reversal');
for (let r = 0n; r < 28n; r++) show(modI(-modI(-r,28n),28n) === r, `orientation reversal is an involution on class ${r}`);

console.log('\nINDEPENDENT INVARIANT CHECKS');
const exactCases = [
  [0n,1n,0n,0n,1n,0n,1n],[1n,1n,0n,0n,1n,1n,28n],[7n,1n,0n,0n,1n,0n,1n],
  [0n,5n,0n,1n,2n,1n,56n],[1n,5n,2n,1n,10n,11n,280n],[-1n,2n,0n,7n,8n,223n,224n],
  [2n,3n,1n,11n,12n,23n,336n],[5n,7n,3n,1n,28n,141n,784n]
];
for (const [m,n,p,sn,sd,mun,mud] of exactCases) {
  const I = invariantsI(m,n);
  show(I.pHalf === p, `p1/2 exact for M(${m},${n})`);
  show(I.s1.num === sn && I.s1.den === sd, `s1 exact for M(${m},${n})`);
  show(I.mu.num === mun && I.mu.den === mud, `mu exact for M(${m},${n})`);
  show(fracEqI(I.s1, fracI(28n * I.mu.num, I.mu.den)), `s1 equals 28 mu for M(${m},${n})`);
}
show(sameBigList(rootsI(5n,1n),[1n,4n]), 'roots of +1 modulo 5 are exact');
show(sameBigList(rootsI(5n,-1n),[2n,3n]), 'roots of -1 modulo 5 are exact');
show(sameBigList(rootsI(12n,1n),[1n,5n,7n,11n]), 'roots of +1 modulo 12 are exact');
show(rootsI(12n,-1n).length === 0, 'no root of -1 exists modulo 12');
show(sameBigList(rootsI(2n,-1n),[1n]), 'the reversing root modulo 2 is exact');

console.log('\nINDEPENDENT CLASSIFICATION EXAMPLES');
const homOnly = classifyI(0n,5n,1n,5n);
show(homOnly.homPlus.ok && !homOnly.homePlus.ok && !homOnly.homeMinus.ok, 'M(0,5) and M(1,5) are homotopy equivalent but not homeomorphic');
const homeNotDiff = classifyI(0n,1n,1n,1n);
show(homeNotDiff.homePlus.ok && homeNotDiff.homeMinus.ok, 'M(0,1) and M(1,1) are homeomorphic in both orientation columns');
show(!homeNotDiff.diffPlus.ok && !homeNotDiff.diffMinus.ok, 'M(0,1) and M(1,1) are not diffeomorphic');
const reverseOnly = classifyI(-1n,2n,0n,2n);
show(!reverseOnly.homPlus.ok && reverseOnly.homMinus.ok, 'M(-1,2) and M(0,2) first match after orientation reversal');
show(!reverseOnly.diffPlus.ok && reverseOnly.diffMinus.ok, 'M(-1,2) and M(0,2) are orientation-reversingly diffeomorphic');
const sameSmooth = classifyI(0n,1n,7n,1n);
show(sameSmooth.diffPlus.ok && sameSmooth.diffMinus.ok, 'M(0,1) and M(7,1) have the same smooth type');
const differentN = classifyI(0n,5n,0n,7n);
show(!differentN.homPlus.ok && !differentN.homMinus.ok && differentN.candidates === 0n, 'different H4 orders stop the classification immediately');
for (let n = 1n; n <= 18n; n++) for (let a = -5n; a <= 5n; a++) for (let b = -5n; b <= 5n; b++) {
  const R = classifyI(a,n,b,n);
  if (R.diffPlus.ok) show(R.homePlus.ok && R.homPlus.ok, `preserving implication ladder holds for (${a},${n}) and (${b},${n})`);
  if (R.diffMinus.ok) show(R.homeMinus.ok && R.homMinus.ok, `reversing implication ladder holds for (${a},${n}) and (${b},${n})`);
}

console.log('\nPAGE-COUPLING: EXECUTE THE SHIPPED ENGINE');
const match = html.match(/<script data-engine="exotic">([\s\S]*?)<\/script>/);
show(Boolean(match), 'page engine script can be extracted');
let Page;
if (match) {
  const sandbox = {};
  vm.runInNewContext(match[1], sandbox, { filename: 'exotic-spheres-page-engine.js', timeout: 2000 });
  Page = sandbox.ExoticEngine;
}
show(Boolean(Page), 'extracted engine executes and exports ExoticEngine');
if (Page) {
  for (const [key,value] of [['SPHERE_MOD',28n],['SPHERE_PERIOD',56n],['MU_FACTOR',224n],['S1_FACTOR',8n],['HOMOTOPY_MOD',12n],['N_CAP',5000n],['M_CAP',1000000000000n]]) show(Page.C[key] === value, `shipped constant ${key} is exact`);
  show(sameBigList(Array.from(Page.reachedSphereClasses()), expectedReached), 'shipped engine reproduces the independent reached set');
  show(Page.unorientedSphereTypes() === 15, 'shipped engine reproduces the independent unoriented count');
  for (let m = -112n; m <= 112n; m++) show(Page.sphereClass(m) === sphereClassI(m), `page coupling for sphere class at m=${m}`);
  for (const n of [1n,2n,3n,5n,7n,12n,29n,64n]) for (const m of [-31n,-7n,-1n,0n,1n,8n,55n]) {
    const A = Page.invariants(m,n), B = invariantsI(m,n);
    show([A.pHalf,A.mu.num,A.mu.den,A.s1.num,A.s1.den,A.rawNumerator].every((x,i)=>x === [B.pHalf,B.mu.num,B.mu.den,B.s1.num,B.s1.den,B.rawNumerator][i]), `page invariant coupling for M(${m},${n})`);
  }
  const pairCases = [[0n,1n,1n,1n],[0n,5n,1n,5n],[-1n,2n,0n,2n],[0n,1n,7n,1n],[1n,12n,5n,12n],[3n,13n,44n,13n],[8n,29n,-17n,29n],[0n,5n,0n,7n]];
  for (const args of pairCases) show(signature(Page.classify(...args)) === signature(classifyI(...args)), `page classification coupling for ${args.join(',')}`);
}

console.log('\nMUTATION SWEEP');
const goldenMu = invariantsI(1n,5n).mu;
const goldenS1 = invariantsI(5n,7n).s1;
const mutations = [
  ['sphere modulus 28 to 27', () => modI(8n*9n/2n,27n) !== sphereClassI(8n)],
  ['sphere modulus 28 to 29', () => modI(8n*9n/2n,29n) !== sphereClassI(8n)],
  ['triangular division removed', () => modI(8n*9n,28n) !== sphereClassI(8n)],
  ['period 56 truncated to 7', () => new Set(expectedSequence.slice(0,7).map(String)).size !== reachedI.length],
  ['mu denominator factor 224 to 223', () => !fracEqI(fracI(((5n+2n)**2n-5n),223n*5n),goldenMu)],
  ['mu denominator factor 224 to 225', () => !fracEqI(fracI(((5n+2n)**2n-5n),225n*5n),goldenMu)],
  ['mu numerator drops minus n', () => !fracEqI(fracI((5n+2n)**2n,224n*5n),goldenMu)],
  ['mu numerator uses n plus m', () => !fracEqI(fracI((5n+1n)**2n-5n,224n*5n),goldenMu)],
  ['p1/2 coefficient 2 to 1', () => modI(1n,5n) !== invariantsI(1n,5n).pHalf],
  ['p1/2 coefficient 2 to 3', () => modI(3n,5n) !== invariantsI(1n,5n).pHalf],
  ['s1 denominator factor 8 to 7', () => !fracEqI(fracI((7n+10n)**2n-7n,7n*7n),goldenS1)],
  ['s1 denominator factor 8 to 9', () => !fracEqI(fracI((7n+10n)**2n-7n,9n*7n),goldenS1)],
  ['linking generator sign flipped', () => modI(-1n,5n) !== 1n],
  ['homotopy modulus 12 to 11', () => gcdI(12n,11n) !== classifyI(1n,12n,5n,12n).d],
  ['homotopy modulus 12 to 13', () => gcdI(12n,13n) !== classifyI(1n,12n,5n,12n).d],
  ['plus-root test changed to square zero', () => rootsI(5n,0n).join(',') !== rootsI(5n,1n).join(',')],
  ['reversing s1 uses equality instead of opposite', () => fracEqI(reverseOnly.A.s1,reverseOnly.B.s1) !== fracOppI(reverseOnly.A.s1,reverseOnly.B.s1)],
  ['reversing homotopy parity inverted', () => modI(-1n+0n,2n) !== 0n],
  ['different n values treated as equal', () => classifyI(0n,5n,0n,7n).sameN !== true],
  ['orientation sign omitted from sphere class', () => modI(1n,28n) !== modI(-1n,28n)]
];
let caught = 0;
for (const [name, catches] of mutations) {
  let ok = false;
  try { ok = Boolean(catches()); } catch { ok = true; }
  if (ok) caught++;
  show(ok, `mutation caught: ${name}`);
}
show(caught === mutations.length, `mutation score ${caught}/${mutations.length}`);
console.log(`\nMUTATIONS CAUGHT ${caught}/${mutations.length}`);
console.log(`ASSERTIONS ${checks}, FAILURES ${failures}`);
if (failures) process.exitCode = 1;
