import fs from 'node:fs';
import vm from 'node:vm';
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';

const here = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(here, '..', '..');
const htmlPath = path.join(root, 'public', 'strata', 'the-ellipsoid-that-kept-touching', 'index.html');
const markdownPath = path.join(root, 'src', 'content', 'strata', 'the-ellipsoid-that-kept-touching.md');
const readmePath = path.join(here, 'README.md');
const html = fs.readFileSync(htmlPath, 'utf8');
const markdown = fs.readFileSync(markdownPath, 'utf8');
const readme = fs.readFileSync(readmePath, 'utf8');

let failures = 0;
function check(condition, message) {
  if (condition) {
    console.log(`PASS ${message}`);
  } else {
    failures += 1;
    console.error(`FAIL ${message}`);
  }
}

function extractCore(source) {
  const match = source.match(/<script id="packing-math-core">([\s\S]*?)<\/script>/);
  if (!match) throw new Error('Could not find the shipped math core');
  return match[1];
}

function loadCore(source) {
  const context = { Math, Number, Array, Object, Infinity, globalThis:null };
  context.globalThis = context;
  vm.createContext(context);
  vm.runInContext(source, context, { filename:'packing-math-core.js' });
  return context.PackingMath;
}

const coreSource = extractCore(html);
const page = loadCore(coreSource);
const uiSource = html.match(/<script id="packing-ui">([\s\S]*?)<\/script>/)?.[1] || '';

function exactDeterminant(matrix) {
  const n = matrix.length;
  const A = matrix.map((row) => row.map(BigInt));
  let sign = 1n;
  let previous = 1n;
  for (let k = 0; k < n - 1; k += 1) {
    let pivot = k;
    while (pivot < n && A[pivot][k] === 0n) pivot += 1;
    if (pivot === n) return 0n;
    if (pivot !== k) {
      [A[pivot], A[k]] = [A[k], A[pivot]];
      sign = -sign;
    }
    const p = A[k][k];
    for (let i = k + 1; i < n; i += 1) {
      for (let j = k + 1; j < n; j += 1) {
        A[i][j] = (A[i][j] * p - A[i][k] * A[k][j]) / previous;
      }
    }
    previous = p;
  }
  return sign * A[n - 1][n - 1];
}

function referenceGammaHalf(x) {
  if (Number.isInteger(x)) {
    let value = 1;
    for (let i = 2; i < x; i += 1) value *= i;
    return value;
  }
  const k = Math.round(x - 0.5);
  let value = Math.sqrt(Math.PI);
  for (let i = 0; i < k; i += 1) value *= i + 0.5;
  return value;
}

function referenceBallVolume(n, r) {
  return Math.PI ** (n / 2) * r ** n / referenceGammaHalf(n / 2 + 1);
}

function independentQuadratic(G, z) {
  let total = 0;
  for (let i = 0; i < z.length; i += 1) {
    for (let j = 0; j < z.length; j += 1) total += z[i] * G[i][j] * z[j];
  }
  return total;
}

function bruteShortestSmall(G) {
  const n = G.length;
  let best = Infinity;
  const z = Array(n).fill(0);
  function visit(k) {
    if (k === n) {
      if (z.every((v) => v === 0)) return;
      best = Math.min(best, independentQuadratic(G, z));
      return;
    }
    for (let v = -2; v <= 2; v += 1) {
      z[k] = v;
      visit(k + 1);
    }
  }
  visit(0);
  return best;
}

function referenceInspect(A) {
  const [a,b,d] = A;
  const disc = Math.sqrt((a-d) ** 2 + 4*b*b);
  const lambdaMin = (a+d-disc)/2;
  if (lambdaMin <= 1e-10) return { valid:false, contacts:0, interior:1, cutoff:0 };
  const cutoff = Math.ceil(Math.sqrt((1+1e-7)/lambdaMin));
  let contacts = 0;
  let interior = 0;
  for (let x = -Math.max(cutoff,8); x <= Math.max(cutoff,8); x += 1) {
    for (let y = -Math.max(cutoff,8); y <= Math.max(cutoff,8); y += 1) {
      if (x === 0 && y === 0) continue;
      const q = a*x*x + 2*b*x*y + d*y*y;
      if (q < 1-1e-7) interior += 1;
      else if (Math.abs(q-1) <= 1e-7) contacts += 1;
    }
  }
  return { valid:interior === 0, contacts, interior, cutoff };
}

function close(a, b, tolerance = 1e-9) {
  return Math.abs(a-b) <= tolerance * Math.max(1,Math.abs(a),Math.abs(b));
}

for (let n = 1; n <= 24; n += 1) {
  const lattice = page.latticeForDimension(n);
  const exact = exactDeterminant(lattice.gram);
  const floating = page.determinant(lattice.gram);
  check(close(floating, Number(exact), 1e-8), `dimension ${n} shipped determinant matches independent exact Bareiss arithmetic`);

  const stats = page.packingStats(n);
  const expectedMin = n === 1 ? 1 : n === 24 ? 4 : 2;
  check(close(stats.shortest.minNorm, expectedMin), `dimension ${n} complete page search returns the sourced minimal norm`);

  const referenceBall = referenceBallVolume(n, stats.radius);
  check(close(stats.ball, referenceBall, 1e-11), `dimension ${n} ball volume matches an independent gamma recurrence`);
  check(close(stats.density, referenceBall / Math.sqrt(Number(exact)), 1e-10), `dimension ${n} density uses ball volume divided by exact covolume`);
}

for (const n of [1,2,3,4,5,6,7,8]) {
  const G = page.latticeForDimension(n).gram;
  check(close(page.shortestCertified(G).minNorm, bruteShortestSmall(G)), `dimension ${n} branch-and-bound matches independent coefficient brute force`);
}

const matrixGrid = [];
for (const a of [1,1.25,1.6,2]) {
  for (const d of [1,1.4,1.8]) {
    for (const b of [-0.5,-0.25,0,0.25,0.5]) matrixGrid.push([a,b,d]);
  }
}
for (const A of matrixGrid) {
  const actual = page.inspectEllipsoid(A);
  const expected = referenceInspect(A);
  check(actual.valid === expected.valid, `ellipsoid ${A.join(',')} validity matches independent exhaustive enumeration`);
  check(actual.contacts.length === expected.contacts, `ellipsoid ${A.join(',')} contact count matches independent exhaustive enumeration`);
  if (actual.positive) {
    check(actual.cutoff >= expected.cutoff, `ellipsoid ${A.join(',')} cutoff is certified by the minimum eigenvalue`);
  }
}

for (const n of [3,10,100,1000]) {
  for (const cK of [0.01,0.1,0.75]) {
    for (const cR of [0.2,2/Math.E,2]) {
      const actual = page.ratioStats(n,cK,cR);
      const rogers = (cK*n*n)/(cR*n);
      const venkatesh = (cK*n*n)/(0.5*n*Math.log(Math.log(n)));
      const campos = (cK*n*n)/(0.5*n*Math.log(n));
      check(close(actual.overRogers,rogers), `ratio sweep n=${n}, cK=${cK}, cR=${cR} matches independent Rogers algebra`);
      check(close(actual.overVenkatesh,venkatesh), `ratio sweep n=${n}, cK=${cK} matches independent Venkatesh algebra`);
      check(close(actual.overCampos,campos), `ratio sweep n=${n}, cK=${cK} matches independent Campos algebra`);
    }
  }
}

const walkStart = uiSource.indexOf('function seeded()');
const walkEnd = uiSource.indexOf('function drawEllipsoid(info)');
check(walkStart >= 0 && walkEnd > walkStart, 'seeded chamber functions are present in the shipped UI');
if (walkStart >= 0 && walkEnd > walkStart) {
  const walkContext = { Math, Number, Array, Object, Infinity, M:page, A:[1.6,0,1.4], previousA:[1.6,0,1.4], seed:1 };
  vm.createContext(walkContext);
  vm.runInContext(uiSource.slice(walkStart,walkEnd),walkContext,{ filename:'shipped-walk-functions.js' });
  for (const seed of [1,2,0x5f3759df,0xffffffff]) {
    walkContext.seed = seed;
    walkContext.A = [1.6,0,1.4];
    walkContext.previousA = walkContext.A.slice();
    let valid = true;
    let monotone = true;
    let priorContacts = 0;
    let steps = 0;
    while (steps < 600) {
      const before = page.inspectEllipsoid(walkContext.A);
      if (!before.valid) { valid = false; break; }
      if (before.contacts.length < priorContacts) monotone = false;
      priorContacts = before.contacts.length;
      if (before.free === 0) break;
      walkContext.certifiedStep();
      steps += 1;
    }
    const after = page.inspectEllipsoid(walkContext.A);
    check(valid && after.valid, `seed ${seed} keeps every shipped walk state valid at tolerance 1e-7`);
    check(monotone, `seed ${seed} never loses an accumulated contact`);
    check(after.rank === 3 && after.free === 0, `seed ${seed} reaches three independent constraints and freezes`);
  }
}

check(exactDeterminant(page.latticeForDimension(8).gram) === 1n, 'published E8 determinant is 1');
check(page.shortestCertified(page.latticeForDimension(8).gram).minNorm === 2, 'published E8 minimal norm is 2');
check(exactDeterminant(page.latticeForDimension(24).gram) === 1n, 'published Leech determinant is 1');
check(page.shortestCertified(page.latticeForDimension(24).gram).minNorm === 4, 'published Leech minimal norm is 4');
check(close(2/Math.E,0.7357588823428847,1e-14), 'Rogers proof constant 2/e recomputes to the cited decimal cross-check');
check([1,2,3,8,24].every((n) => html.includes(`dimensions 1, 2, 3, 8, and 24`)), 'page limits unrestricted exact-optimum prose to the verified dimension list');

const requiredIdentifiers = [
  '10.1007/s00222-026-01412-w',
  '2504.05042',
  '10.2307/1969390',
  '10.1093/imrn/rns096',
  '2411.14973',
  '2312.10026',
  '10.1215/00127094-2738857',
  '10.4007/annals.2017.185.3.7',
  '10.4007/annals.2017.185.3.8'
];
for (const id of requiredIdentifiers) {
  check(html.includes(id) && readme.includes(id), `verified source identifier ${id} appears in page and research record`);
}

const mutatedSource = coreSource.replace('if (q < 1 - tolerance) interior.push', 'if (q <= 1 + tolerance) interior.push');
check(mutatedSource !== coreSource, 'deliberate interior-inequality mutation was applied to the extracted shipped core');
const mutant = loadCore(mutatedSource);
check(page.inspectEllipsoid([1,0,1]).valid && !mutant.inspectEllipsoid([1,0,1]).valid, 'mutation test catches a broken boundary-versus-interior inequality, then leaves the shipped file untouched');

const forbiddenEmDash = String.fromCodePoint(0x2014);
// The house rule forbids the em dash in THIS page's own prose. It deliberately does not
// touch verbatim quotation, and the site-wide "nearby layers" navigation block is generated
// from other strata's real titles, some of which predate the rule and legitimately carry one
// (for example "Every Circle a Whole Number - and Never a Square"). Rewriting another layer's
// title to satisfy this check would turn a quotation into a misquotation, so the injected
// block is excluded and everything the page actually authors is still checked.
const authored = html.replace(/<nav[^>]*aw-nearby[\s\S]*?<\/nav>/g, '');
for (const [name,text] of [['HTML',authored],['frontmatter',markdown],['research README',readme],['verifier',fs.readFileSync(fileURLToPath(import.meta.url),'utf8')]]) {
  check(!text.includes(forbiddenEmDash), `${name} contains no em dash in its own prose`);
}
check(authored.length < html.length || !/aw-nearby/.test(html),
  'the nearby-layers exclusion actually matched (guards against the check silently widening)');
check(html.trimEnd().endsWith('</body>\n</html>'), 'page ends with load-bearing body and html closing tags');
check(/<section class="check"/.test(html) && />The check</.test(html), 'visible check panel is present');
check(/@media \(prefers-reduced-motion: reduce\)/.test(html), 'reduced-motion guard is present');
check(!/<script\b[^>]*\bsrc=["']https?:\/\//i.test(html) &&
  !/<img\b[^>]*\bsrc=["']https?:\/\//i.test(html) &&
  !/<link\b[^>]*\brel=["']stylesheet["'][^>]*\bhref=["']https?:\/\//i.test(html),
  'page has no third-party runtime asset request');

if (failures) {
  console.error(`\n${failures} assertion(s) failed.`);
  process.exit(1);
}
console.log('\nAll assertions passed. The in-memory mutation was caught; the shipped page was not changed.');
