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

const here = path.dirname(fileURLToPath(import.meta.url));
const htmlPath = path.resolve(here, '../../public/strata/everything-you-can-count-says-yes/index.html');
const html = fs.readFileSync(htmlPath, 'utf8');

function assert(name, condition, detail = '') {
  if (!condition) {
    console.error(`FAIL ${name}${detail ? `: ${detail}` : ''}`);
    process.exitCode = 1;
    return;
  }
  console.log(`PASS ${name}${detail ? `: ${detail}` : ''}`);
}

function extractCore(source) {
  const match = source.match(/\/\* VERIFY_CORE_START \*\/([\s\S]*?)\/\* VERIFY_CORE_END \*\//);
  if (!match) throw new Error('verification core markers not found');
  return match[1];
}

function loadCore(source) {
  const sandbox = {
    Math,
    Number,
    Array,
    Int8Array,
    Int32Array,
    Uint8Array,
    Float64Array
  };
  vm.createContext(sandbox);
  vm.runInContext(`${source}
this.core = { segmentedCompute, liSeries, mertensCertificate, skewesCertificate, deriveSkewesRun };`, sandbox);
  return sandbox.core;
}

const shippedSource = extractCore(html);
const shipped = loadCore(shippedSource);

function referenceSieve(limit) {
  const mu = new Int8Array(limit + 1);
  const mertens = new Int32Array(limit + 1);
  const primeFlags = new Uint8Array(limit + 1);
  const primeCounts = new Int32Array(limit + 1);
  const primes = [];
  const least = new Int32Array(limit + 1);
  mu[1] = 1;
  for (let n = 2; n <= limit; n += 1) {
    if (least[n] === 0) {
      least[n] = n;
      primes.push(n);
      mu[n] = -1;
      primeFlags[n] = 1;
    }
    for (const p of primes) {
      const product = p * n;
      if (product > limit) break;
      least[product] = p;
      if (n % p === 0) {
        mu[product] = 0;
        break;
      }
      mu[product] = -mu[n];
    }
  }
  let m = 0;
  let pi = 0;
  for (let n = 1; n <= limit; n += 1) {
    m += mu[n];
    pi += primeFlags[n];
    mertens[n] = m;
    primeCounts[n] = pi;
  }
  return { mu, mertens, primeFlags, primeCounts };
}

function arraysEqual(a, b) {
  if (a.length !== b.length) return false;
  for (let i = 0; i < a.length; i += 1) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

const reachableLimits = [100000, 250000, 500000, 1000000, 2000000];
for (const limit of reachableLimits) {
  const actual = shipped.segmentedCompute(limit, 32768);
  const expected = referenceSieve(limit);
  const same = arraysEqual(actual.mu, expected.mu)
    && arraysEqual(actual.mertens, expected.mertens)
    && arraysEqual(actual.primeFlags, expected.primeFlags)
    && arraysEqual(actual.primeCounts, expected.primeCounts);
  assert(`differential segmented sweep through ${limit.toLocaleString('en-US')}`, same);
}

function adaptiveSimpson(f, a, b, epsilon, depth = 24) {
  const c = (a + b) / 2;
  const fa = f(a);
  const fb = f(b);
  const fc = f(c);
  const whole = (b - a) * (fa + 4 * fc + fb) / 6;
  function recurse(left, right, fLeft, fMid, fRight, estimate, eps, remaining) {
    const mid = (left + right) / 2;
    const lmid = (left + mid) / 2;
    const rmid = (mid + right) / 2;
    const fLmid = f(lmid);
    const fRmid = f(rmid);
    const leftEstimate = (mid - left) * (fLeft + 4 * fLmid + fMid) / 6;
    const rightEstimate = (right - mid) * (fMid + 4 * fRmid + fRight) / 6;
    const delta = leftEstimate + rightEstimate - estimate;
    if (remaining === 0 || Math.abs(delta) <= 15 * eps) {
      return leftEstimate + rightEstimate + delta / 15;
    }
    return recurse(left, mid, fLeft, fLmid, fMid, leftEstimate, eps / 2, remaining - 1)
      + recurse(mid, right, fMid, fRmid, fRight, rightEstimate, eps / 2, remaining - 1);
  }
  return recurse(a, b, fa, fc, fb, whole, epsilon, depth);
}

function liReference(x) {
  const z = Math.log(x);
  const integrand = t => t === 0 ? 1 : Math.expm1(t) / t;
  return 0.5772156649015328606 + Math.log(z) + adaptiveSimpson(integrand, 0, z, 2e-13);
}

for (const x of [2, 3, 10, 97, 1000, 100000, 2000000]) {
  const actual = shipped.liSeries(x);
  const expected = liReference(x);
  assert(`independent li quadrature at x=${x}`, Math.abs(actual.value - expected) < 2e-10,
    `difference ${Math.abs(actual.value - expected).toExponential(3)}`);
  assert(`li tail estimate at x=${x}`, actual.truncation < 1e-8);
}

function mertensReference(stress) {
  const exactFiniteMagnitude = 1008867n;
  const scaledRemainder = 569n * BigInt(stress);
  const lowerScaled = exactFiniteMagnitude * 1000000n - scaledRemainder * 100n;
  return Number(lowerScaled) / 1e12;
}

for (const stress of [1, 100, 500, 1000, 1177, 1178, 1400]) {
  const actual = shipped.mertensCertificate(stress);
  const expected = mertensReference(stress);
  assert(`independent Mertens ledger at ${stress}x`, Math.abs(actual.lower - expected) < 2e-15);
  assert(`Mertens verdict at ${stress}x`, actual.passes === (expected > 1.0088));
}

const skewesTerms = [4.45e-50, 5.53e-9, 8.92e-7, 3.55e-9, 7.37e-15, 5.37e-8];
for (const stress of [1, 2, 4, 6, 7, 8]) {
  const expected = 7.0294e-6 - skewesTerms.reduce((sum, value) => sum + value * stress, 0);
  const actual = shipped.skewesCertificate(stress);
  assert(`independent Skewes ledger at ${stress}x`, Math.abs(actual.lower - expected) < 2e-20);
  assert(`Skewes verdict at ${stress}x`, actual.passes === (expected > 0));
}

const publishedRun = shipped.deriveSkewesRun(6.07e-6);
assert('2015 peak lower bound is reproduced', publishedRun.log10Peak > Math.log10(9.85e149));
assert('2015 consecutive run rounds down to 7.17e152',
  publishedRun.exponent === 152 && publishedRun.mantissa > 7.17 && publishedRun.mantissa < 7.18,
  `${publishedRun.mantissa.toFixed(6)}e${publishedRun.exponent}`);

assert('published M(10^24) is shipped exactly', html.includes("m24:'7189337839'"));
assert('published M(10^25) is shipped exactly', html.includes("m25:'-258560632948'"));
assert('contiguous 10^16 claim is labelled separately', html.includes("contiguousMertens:'10000000000000000'"));
assert('Büthe 10^19 lower range is shipped', html.includes("skewesLower:'10000000000000000000'"));
assert('2015 interval endpoints are shipped exactly',
  html.includes('727.951334747') && html.includes('727.951336105'));
assert('source identifiers are present',
  [
    'arXiv:2607.07566',
    '10.1090/mcom/3275',
    '10.1090/S0025-5718-2013-02716-0',
    'arXiv:2502.21021',
    '10.1090/mcom/3264',
    '10.1090/S0025-5718-2015-02930-5',
    '10.1016/j.jnt.2025.07.002'
  ].every(identifier => html.includes(identifier)));

const mutatedSource = shippedSource.replace('localMu[j] = -localMu[j];', 'localMu[j] = localMu[j];');
assert('mutation target was found', mutatedSource !== shippedSource);
const mutated = loadCore(mutatedSource);
const mutatedActual = mutated.segmentedCompute(500, 64);
const mutationExpected = referenceSieve(500);
const mutationDetected = !arraysEqual(mutatedActual.mu, mutationExpected.mu)
  || !arraysEqual(mutatedActual.mertens, mutationExpected.mertens);
assert('deliberate page mutation is detected', mutationDetected,
  'the verifier fails when the shipped prime-factor sign flip is perturbed; the source file was not changed');

assert('visible check panel exists', /<h2 id="check-heading">The check<\/h2>/.test(html));
assert('two operable certificate benches exist',
  html.includes('id="mertens-stress"') && html.includes('id="skewes-stress"'));
const controls = [...html.matchAll(/<(?:input|select)\b[^>]*\bid="([^"]+)"/g)].map(match => match[1]);
const labels = new Set([...html.matchAll(/<label\b[^>]*\bfor="([^"]+)"/g)].map(match => match[1]));
assert('every input and select has an explicit label', controls.every(id => labels.has(id)),
  `${controls.length} controls checked`);
assert('live readouts expose polite status',
  (html.match(/role="status"/g) || []).length >= 6 && html.includes('aria-live="polite"'));
assert('reduced-motion guard exists', html.includes('@media (prefers-reduced-motion: reduce)'));
assert('390, 768, and 1440 layouts are contained',
  html.includes('overflow-x:hidden')
  && html.includes('.ledger-wrap, .table-wrap')
  && html.includes('overflow-x:auto')
  && html.includes('@media (max-width:760px)')
  && html.includes('@media (max-width:430px)'));
assert('canonical and honest Article metadata exist',
  html.includes('rel="canonical" href="https://artwaste.land/strata/everything-you-can-count-says-yes/"')
  && html.includes('"@type":"Article"')
  && html.includes('"name":"Mertens Function and Skewes Number Live Calculator"'));
assert('page carries load-bearing closing tags', html.trimEnd().endsWith('</body>\n</html>'));
assert('forbidden em dash is absent', !html.includes(String.fromCodePoint(0x2014)));

if (process.exitCode) process.exit(process.exitCode);
