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/neutrino-endpoint/index.html');
const html = fs.readFileSync(htmlPath, 'utf8');

let failures = 0;

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

function close(actual, expected, tolerance) {
  return Number.isFinite(actual) &&
    Number.isFinite(expected) &&
    Math.abs(actual - expected) <= tolerance;
}

function extractScript(id) {
  const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const match = html.match(new RegExp(`<script id="${escaped}"[^>]*>([\\s\\S]*?)<\\/script>`));
  if (!match) throw new Error(`missing script ${id}`);
  return match[1];
}

function evaluateCore(source) {
  const sandbox = { window: {}, globalThis: {} };
  vm.createContext(sandbox);
  vm.runInContext(source, sandbox, { filename: 'shipped-neutrino-core.js' });
  return sandbox.window.NeutrinoCore || sandbox.globalThis.NeutrinoCore;
}

const coreSource = extractScript('neutrino-core');
const shipped = evaluateCore(coreSource);
const published = JSON.parse(extractScript('published-data'));

report(Boolean(shipped), 'page core extracted and evaluated');
report(!html.includes('\u2014'), 'no em dash in shipped HTML');
report(html.trimEnd().endsWith('</body>\n</html>'), 'load-bearing closing tags present');
report(/<section class="check"[\s\S]*?>\s*<h2 id="check-title">The Check<\/h2>/.test(html),
  'visible The Check panel present');

function referencePhase(epsilon, mass) {
  if (mass < 0 || epsilon < mass || !Number.isFinite(epsilon) || !Number.isFinite(mass)) return 0;
  return epsilon * Math.sqrt(Math.max(0, (epsilon - mass) * (epsilon + mass)));
}

function referenceTransmission(surplus, width) {
  if (surplus <= 0) return 0;
  if (surplus >= width) return 1;
  const ratio = surplus / width;
  return ratio / (1 + Math.sqrt(1 - ratio));
}

function referenceMidpoint(fn, start, end, steps) {
  const h = (end - start) / steps;
  let sum = 0;
  for (let i = 0; i < steps; i += 1) sum += fn(start + (i + 0.5) * h);
  return sum * h;
}

function referenceMolecular(epsilon, mass, states) {
  return states.reduce((sum, state) =>
    sum + state.weight * referencePhase(epsilon - state.excitation, mass), 0);
}

function referenceMassMap(lightest, ordering, params) {
  let squared;
  if (ordering === 'NO') {
    squared = [lightest ** 2, lightest ** 2 + params.deltaM21,
      lightest ** 2 + params.deltaM3l];
  } else {
    squared = [lightest ** 2 + Math.abs(params.deltaM3l) - params.deltaM21,
      lightest ** 2 + Math.abs(params.deltaM3l), lightest ** 2];
  }
  const masses = squared.map(value => Math.sqrt(Math.max(0, value)));
  const weights = [
    Math.cos(Math.asin(Math.sqrt(params.sin2Theta13))) ** 2 *
      Math.cos(Math.asin(Math.sqrt(params.sin2Theta12))) ** 2,
    Math.cos(Math.asin(Math.sqrt(params.sin2Theta13))) ** 2 *
      Math.sin(Math.asin(Math.sqrt(params.sin2Theta12))) ** 2,
    Math.sin(Math.asin(Math.sqrt(params.sin2Theta13))) ** 2
  ];
  return {
    masses,
    beta: Math.sqrt(weights.reduce((sum, weight, index) =>
      sum + weight * squared[index], 0)),
    sum: masses.reduce((sum, value) => sum + value, 0)
  };
}

let phaseSweepOk = true;
let phaseCases = 0;
for (let massStep = 0; massStep <= 200; massStep += 1) {
  const mass = massStep / 100;
  for (const windowEV of [3, 5, 10]) {
    for (let point = 0; point <= 240; point += 1) {
      const epsilon = point / 240 * windowEV;
      phaseCases += 1;
      if (!close(shipped.phaseSpace(epsilon, mass), referencePhase(epsilon, mass), 1e-8)) {
        phaseSweepOk = false;
      }
    }
  }
}
report(phaseSweepOk, 'differential phase-space sweep against independent factorization',
  `${phaseCases} reachable plot cases`);

let transmissionOk = true;
for (let i = -50; i <= 200; i += 1) {
  const surplus = i / 100;
  const actual = shipped.transmission(surplus, 0.93);
  const expected = referenceTransmission(surplus, 0.93);
  if (!close(actual, expected, 1e-12)) transmissionOk = false;
}
report(transmissionOk, 'transmission proxy checked by rationalized reference formula',
  '251 surplus-energy cases');

let idealIntegralOk = true;
for (const windowEV of [3, 5, 10]) {
  for (let massStep = 0; massStep <= 200; massStep += 5) {
    const mass = massStep / 100;
    const actual = shipped.missingFraction(mass, windowEV, null, 1200);
    const available = Math.max(0, windowEV * windowEV - mass * mass);
    const massiveArea = available ** 1.5 / 3;
    const zeroArea = windowEV ** 3 / 3;
    const expected = 1 - massiveArea / zeroArea;
    if (!close(actual, expected, 1.2e-5)) idealIntegralOk = false;
  }
}
report(idealIntegralOk, 'ideal missing fraction checked against analytic integral',
  '123 mass-window cases');

const proxyStates = [
  { excitation: 0, weight: 0.35 },
  { excitation: 0.75, weight: 0.40 },
  { excitation: 1.75, weight: 0.25 }
];
let molecularOk = true;
for (const windowEV of [3, 5, 10]) {
  for (let massStep = 0; massStep <= 200; massStep += 20) {
    const mass = massStep / 100;
    const actual = shipped.missingFraction(mass, windowEV, proxyStates, 1200);
    const zeroArea = referenceMidpoint(
      epsilon => referenceMolecular(epsilon, 0, proxyStates), 0, windowEV, 24000);
    const massArea = referenceMidpoint(
      epsilon => referenceMolecular(epsilon, mass, proxyStates), 0, windowEV, 24000);
    const expected = (zeroArea - massArea) / zeroArea;
    if (!close(actual, expected, 1.7e-5)) molecularOk = false;
  }
}
report(molecularOk, 'molecular proxy checked against independent midpoint integration',
  '33 mass-window cases');

let mapOk = true;
let mapCases = 0;
for (const ordering of ['NO', 'IO']) {
  for (let step = 0; step <= 200; step += 1) {
    const lightest = step / 1000;
    const params = published.nufit[ordering];
    const actual = shipped.massMap(lightest, ordering, params);
    const expected = referenceMassMap(lightest, ordering, params);
    mapCases += 1;
    if (!close(actual.beta, expected.beta, 1e-12) ||
        !close(actual.sum, expected.sum, 1e-12) ||
        !close(actual.m1, expected.masses[0], 1e-12) ||
        !close(actual.m2, expected.masses[1], 1e-12) ||
        !close(actual.m3, expected.masses[2], 1e-12)) {
      mapOk = false;
    }
  }
}
report(mapOk, 'mass map swept against trigonometric-weight reference',
  `${mapCases} reachable slider and ordering cases`);

const expectedPublished = {
  bestM2: -0.14,
  plusError: 0.13,
  minusError: 0.15,
  statError: 0.108,
  systError: 0.072,
  lokhovTkachovLimit: 0.45,
  feldmanCousinsLimit: 0.31,
  measurementDays: 259,
  publishedMillionCounts: 36,
  constrainedSystematics: 144,
  scanSteps: 68237
};
for (const [key, expected] of Object.entries(expectedPublished)) {
  report(published.katrin[key] === expected, `published KATRIN number ${key}`,
    `source value ${expected}`);
}

report(published.release.doi === '10.5281/zenodo.13644900',
  'published Zenodo DOI');
report(published.release.dataMd5 === '7c9e30c35c394d87917cc56c7bf7ff53',
  'published KATRIN data MD5');
report(published.release.inputsMd5 === '6fcb3fbd3059190caa95f37243a9593a',
  'published KATRIN inputs MD5');
report(published.desi.lcdmLimit === 0.0642, 'published DESI flat Lambda-CDM limit');
report(published.desi.w0waLimit === 0.163, 'published DESI w0-wa CDM limit');

const noFloor = shipped.massMap(0, 'NO', published.nufit.NO);
const ioFloor = shipped.massMap(0, 'IO', published.nufit.IO);
report(close(noFloor.beta, 0.008838035704555621, 1e-14),
  'normal-ordering m_beta floor');
report(close(noFloor.sum, 0.058993330403980394, 1e-14),
  'normal-ordering mass-sum floor');
report(close(ioFloor.beta, 0.049025498640931746, 1e-14),
  'inverted-ordering m_beta floor');
report(close(ioFloor.sum, 0.0994466326141203, 1e-14),
  'inverted-ordering mass-sum floor');

const mutantSource = coreSource.replace(
  'epsilon < mass || mass < 0',
  'epsilon <= mass + 0.01 || mass < 0'
);
let mutationCaught = false;
if (mutantSource !== coreSource) {
  const mutant = evaluateCore(mutantSource);
  for (let i = 0; i <= 20; i += 1) {
    const epsilon = i / 1000;
    if (!close(mutant.phaseSpace(epsilon, 0), referencePhase(epsilon, 0), 1e-12)) {
      mutationCaught = true;
      break;
    }
  }
}
report(mutationCaught,
  'mutation audit caught a deliberate inequality error in an extracted copy',
  'shipped HTML was never modified');

const requiredCitations = [
  '10.1126/science.adq9592',
  '10.5281/zenodo.13644900',
  '10.1038/s41567-021-01463-1',
  '10.1007/JHEP12(2024)216',
  '10.1103/w9pk-xsk7',
  '10.1038/s41586-025-09739-9'
];
for (const citation of requiredCitations) {
  report(html.includes(citation), `citation present ${citation}`);
}

if (failures > 0) {
  console.error(`FAILED ${failures} assertion(s)`);
  process.exit(1);
}

console.log('PASS all assertions');
