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

const pagePath = new URL('../../public/strata/the-middle-layer-breaks-the-bound/index.html', import.meta.url);
const html = readFileSync(pagePath, 'utf8');
let failures = 0;

function assertLine(label, condition, detail = '') {
  if (!condition) failures += 1;
  console.log(`${condition ? 'PASS' : 'FAIL'} ${label}${detail ? `: ${detail}` : ''}`);
}

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

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

function loadShippedMath(source) {
  const sandbox = {};
  vm.createContext(sandbox);
  vm.runInContext(source, sandbox, { filename: 'shipped-math-core.js' });
  return sandbox.MiddleLayerMath;
}

const shippedSource = extractMathCore(html);
const shipped = loadShippedMath(shippedSource);
assertLine('lifted the shipped math-core from index.html', Boolean(shipped));

function referenceStrings(n, weight) {
  const output = [];
  function visit(position, onesLeft, prefix) {
    if (position === n) {
      if (onesLeft === 0) output.push(prefix);
      return;
    }
    if (onesLeft < 0 || onesLeft > n - position) return;
    visit(position + 1, onesLeft, `${prefix}0`);
    visit(position + 1, onesLeft - 1, `${prefix}1`);
  }
  visit(0, weight, '');
  return output;
}

function referenceLayer(n) {
  const k = Math.floor(n / 2);
  const lower = referenceStrings(n, k);
  const upper = referenceStrings(n, k + 1);
  const counts = new Map(upper.map((value) => [value, 0]));
  let routes = 0;
  for (const source of lower) {
    for (let i = 0; i < n; i += 1) {
      if (source[i] !== '0') continue;
      const target = `${source.slice(0, i)}1${source.slice(i + 1)}`;
      counts.set(target, counts.get(target) + 1);
      routes += 1;
    }
  }
  const values = [...counts.values()];
  const squares = values.reduce((sum, value) => sum + value * value, 0);
  return {
    lowerCount: lower.length,
    upperCount: upper.length,
    routes,
    minimum: Math.min(...values),
    maximum: Math.max(...values),
    squares,
    gain: squares / routes
  };
}

for (let n = 4; n <= 18; n += 1) {
  const actual = shipped.buildMiddleLayer(n);
  const expected = referenceLayer(n);
  const matches =
    actual.qCount === expected.lowerCount &&
    actual.qPrimeCount === expected.upperCount &&
    actual.contributionCount === expected.routes &&
    actual.minimumMultiplicity === expected.minimum &&
    actual.maximumMultiplicity === expected.maximum &&
    actual.sumSquared === expected.squares &&
    actual.collisionGain === expected.gain;
  assertLine(`differential middle-layer sweep N=${n}`, matches,
    `Q=${actual.qCount}, Q'=${actual.qPrimeCount}, routes=${actual.contributionCount}, gain=${actual.collisionGain}`);
}

function referenceBeta(n, smoothness) {
  return (n - 1) / ((n - 1) + smoothness);
}

for (let n = 2; n <= 10; n += 1) {
  for (let smoothness = 2; smoothness <= 10; smoothness += 1) {
    for (const R of [10, 1000, 1000000]) {
      for (const epsilon of [0.01, 0.1, 0.25]) {
        const actual = shipped.powerBench(n, smoothness, R, epsilon);
        const beta = referenceBeta(n, smoothness);
        const expectedPower = Math.exp((beta - epsilon) * Math.log(R));
        const matches =
          close(actual.beta, beta) &&
          close(actual.selectedExponent, beta - epsilon) &&
          close(actual.selectedPower, expectedPower) &&
          close(actual.logR, Math.log(R)) &&
          close(actual.epsilonPower, Math.exp(epsilon * Math.log(R)));
        if (!matches) {
          assertLine(`differential power sweep n=${n}, k=${smoothness}, R=${R}, epsilon=${epsilon}`, false);
        }
      }
    }
  }
}
assertLine('differential power sweep across every reachable n and k with three R and epsilon samples', failures === 0);

for (let d = 2; d <= 10; d += 1) {
  let expected = 1;
  for (let i = 1; i < d; i += 1) expected *= 2;
  assertLine(`incidence-cap formula d=${d}`, shipped.incidenceCap(d) === expected, String(expected));
}

const literalChecks = [
  ['Cairo identifier and version', /arXiv:2502\.06137v2/],
  ['Cairo author literal', /<strong>Hannah Cairo<\/strong>/],
  ['Cairo v1 timestamp', /10 February 2025 at 03:55:11 UTC/],
  ['Cairo v2 timestamp', /12 March 2025 at 13:44:52 UTC/],
  ['Cairo and Zhang identifier and version', /arXiv:2512\.08064v1/],
  ['Cairo and Zhang author literal', /<strong>Hannah Cairo and Ruixiang Zhang<\/strong>/],
  ['Cairo and Zhang timestamp', /8 December 2025 at 21:56:05 UTC/],
  ['Fenves identifier and version', /arXiv:2606\.27020v1/],
  ['Fenves author literal', /<strong>Inbo Gottlieb Fenves<\/strong>/],
  ['Fenves timestamp', /25 June 2026 at 13:32:43 UTC/],
  ['middle layer attributed to Section 3.2', /middle-layer construction in Section 3\.2/],
  ['incidence cap attributed to Lemma 3.5', /incidence cap in Lemma 3\.5/],
  ['all mathematical sources labelled preprints', /three mathematical works above are cited as arXiv preprints/],
  ['fixed sphere and paraboloid remain open', /sphere and paraboloid remains unresolved/]
];
for (const [label, pattern] of literalChecks) {
  assertLine(label, pattern.test(html));
}

const mutatedSource = shippedSource.replace('var upperWeight = k + 1;', 'var upperWeight = k + 2;');
assertLine('mutation target found in shipped source', mutatedSource !== shippedSource);
let mutationCaught = false;
if (mutatedSource !== shippedSource) {
  const mutant = loadShippedMath(mutatedSource);
  const mutantActual = mutant.buildMiddleLayer(8);
  const reference = referenceLayer(8);
  mutationCaught =
    mutantActual.qPrimeCount !== reference.upperCount ||
    mutantActual.minimumMultiplicity !== reference.minimum ||
    mutantActual.sumSquared !== reference.squares;
}
assertLine('intentional upper-layer mutation is rejected by the independent reference', mutationCaught,
  'the verifier was tested against a perturbed copy; the shipped page was not modified');

assertLine('page ends with load-bearing closing tags', /<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html));
assertLine('no em dash appears in the shipped page', !html.includes('\u2014'));

console.log(failures === 0 ? 'PASS all independent checks' : `FAIL ${failures} assertion(s)`);
process.exit(failures === 0 ? 0 : 1);
