import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

const here = path.dirname(fileURLToPath(import.meta.url));
const htmlPath = path.resolve(here, "../../public/strata/omega-minus/index.html");

function fail(message) {
  console.error(`FAIL: ${message}`);
  process.exitCode = 1;
}

function assert(condition, message) {
  if (!condition) fail(message);
}

function close(actual, expected, tolerance, label) {
  if (!Number.isFinite(actual) || Math.abs(actual - expected) > tolerance) {
    fail(`${label}: expected ${expected}, got ${actual}`);
  }
}

function fixed(value, places) {
  return Number(value).toFixed(places);
}

const html = fs.readFileSync(htmlPath, "utf8");
const fixtureMatch = html.match(
  /<script id="verified-data" type="application\/json">([\s\S]*?)<\/script>/
);
assert(Boolean(fixtureMatch), "page fixture is present");
if (!fixtureMatch) process.exit(1);

let page;
try {
  page = JSON.parse(fixtureMatch[1]);
} catch (error) {
  console.error(error);
  fail("page fixture is valid JSON");
  process.exit(1);
}

// Independently transcribed external anchors. These are not imported from the page.
const source = {
  historical: [
    { id: "delta", label: "Delta", S: 0, mass: 1238 },
    { id: "sigma", label: "Sigma-star", S: -1, mass: 1385 },
    { id: "xi", label: "Xi-star", S: -2, mass: 1532 }
  ],
  paperPrediction: 1680,
  event: { mass: 1686, sigma: 12 },
  pdg2026: {
    omega: { mass: 1672.45, sigma: 0.29 },
    xiZero: { mass: 1314.86, sigma: 0.20 },
    chargedKaon: { mass: 493.677, sigma: 0.013 },
    xiMinus: { mass: 1321.71, sigma: 0.07 },
    neutralKaon: { mass: 497.611, sigma: 0.013 }
  },
  particles: {
    kMinus: { charge: -1, strangeness: -1, baryon: 0 },
    proton: { charge: 1, strangeness: 0, baryon: 1 },
    omegaMinus: { charge: -1, strangeness: -3, baryon: 1 },
    kPlus: { charge: 1, strangeness: 1, baryon: 0 },
    kZero: { charge: 0, strangeness: 1, baryon: 0 },
    xiZero: { charge: 0, strangeness: -2, baryon: 1 },
    piMinus: { charge: -1, strangeness: 0, baryon: 0 }
  }
};

assert(JSON.stringify(page.historical) === JSON.stringify(source.historical),
  "historical page anchors match the discovery paper");
close(page.published.paperPrediction, source.paperPrediction, 0, "paper prediction anchor");
close(page.published.event.mass, source.event.mass, 0, "first-event mass anchor");
close(page.published.event.sigma, source.event.sigma, 0, "first-event uncertainty anchor");

for (const key of ["omega", "xiZero", "chargedKaon"]) {
  close(page.published.pdg2026[key].mass, source.pdg2026[key].mass, 0,
    `${key} 2026 mass anchor`);
  close(page.published.pdg2026[key].sigma, source.pdg2026[key].sigma, 0,
    `${key} 2026 uncertainty anchor`);
}

const masses = source.historical.map((row) => row.mass);
const spacingOne = masses[1] - masses[0];
const spacingTwo = masses[2] - masses[1];
const extrapolated = masses[2] + spacingTwo;

function leastSquares(rows) {
  const n = rows.length;
  const meanS = rows.reduce((sum, row) => sum + row.S, 0) / n;
  const meanM = rows.reduce((sum, row) => sum + row.mass, 0) / n;
  const numerator = rows.reduce(
    (sum, row) => sum + (row.S - meanS) * (row.mass - meanM), 0
  );
  const denominator = rows.reduce(
    (sum, row) => sum + (row.S - meanS) ** 2, 0
  );
  const slope = numerator / denominator;
  const intercept = meanM - slope * meanS;
  const prediction = intercept + slope * -3;
  const rms = Math.sqrt(
    rows.reduce((sum, row) => sum + (row.mass - intercept - slope * row.S) ** 2, 0) / n
  );
  return { slope, intercept, prediction, rms };
}

const fit = leastSquares(source.historical);
close(spacingOne, 147, 0, "Delta to Sigma-star spacing");
close(spacingTwo, 147, 0, "Sigma-star to Xi-star spacing");
close(extrapolated, 1679, 0, "held-out equal-spacing extrapolation");
close(fit.slope, -147, 1e-12, "least-squares slope");
close(fit.intercept, 1238, 1e-12, "least-squares intercept");
close(fit.prediction, 1679, 1e-12, "least-squares held-out prediction");
close(fit.rms, 0, 1e-12, "rounded-input residual RMS");

const xi = source.pdg2026.xiZero;
const kaon = source.pdg2026.chargedKaon;
const omega = source.pdg2026.omega;
const threshold = xi.mass + kaon.mass;
const thresholdSigma = Math.hypot(xi.sigma, kaon.sigma);
const currentGap = threshold - omega.mass;
const currentGapSigma = Math.hypot(thresholdSigma, omega.sigma);
const eventGap = threshold - source.event.mass;
const eventGapSigma = Math.hypot(thresholdSigma, source.event.sigma);
const predictionGap = threshold - extrapolated;
const competingThreshold =
  source.pdg2026.xiMinus.mass + source.pdg2026.neutralKaon.mass;

close(page.expected.spacingOne, spacingOne, 1e-12, "page first spacing");
close(page.expected.spacingTwo, spacingTwo, 1e-12, "page second spacing");
close(page.expected.extrapolated, extrapolated, 1e-12, "page extrapolation");
close(page.expected.threshold, threshold, 1e-12, "page threshold");
close(page.expected.thresholdSigma, thresholdSigma, 1e-12, "page threshold uncertainty");
close(page.expected.currentGap, currentGap, 1e-12, "page current gap");
close(page.expected.currentGapSigma, currentGapSigma, 1e-12, "page current gap uncertainty");
close(page.expected.eventGap, eventGap, 1e-12, "page event gap");
close(page.expected.eventGapSigma, eventGapSigma, 1e-12, "page event gap uncertainty");
close(page.expected.predictionGap, predictionGap, 1e-12, "page prediction gap");

assert(page.expected.thresholdDisplay === `${fixed(threshold, 2)} ± ${fixed(thresholdSigma, 2)}`,
  "threshold display agrees with independently rounded result");
assert(page.expected.currentGapDisplay === `${fixed(currentGap, 2)} ± ${fixed(currentGapSigma, 2)}`,
  "current-gap display agrees with independently rounded result");
assert(page.expected.eventGapDisplay === `${fixed(eventGap, 2)} ± ${fixed(eventGapSigma, 2)}`,
  "event-gap display agrees with independently rounded result");
assert(page.expected.predictionGapDisplay === fixed(predictionGap, 2),
  "prediction-gap display agrees with independently rounded result");

function total(keys, field) {
  return keys.reduce((sum, key) => sum + source.particles[key][field], 0);
}

const vertices = {
  production: {
    incoming: ["kMinus", "proton"],
    outgoing: ["omegaMinus", "kPlus", "kZero"]
  },
  decay: {
    incoming: ["omegaMinus"],
    outgoing: ["xiZero", "piMinus"]
  }
};

for (const [name, vertex] of Object.entries(vertices)) {
  const inQ = total(vertex.incoming, "charge");
  const outQ = total(vertex.outgoing, "charge");
  const inS = total(vertex.incoming, "strangeness");
  const outS = total(vertex.outgoing, "strangeness");
  const inB = total(vertex.incoming, "baryon");
  const outB = total(vertex.outgoing, "baryon");
  assert(inQ === outQ, `${name} conserves charge`);
  assert(inB === outB, `${name} conserves baryon number`);
  if (name === "production") assert(inS === outS, "production conserves strangeness");
  if (name === "decay") assert(outS - inS === 1, "decay changes strangeness by +1");
}

assert(JSON.stringify(page.particles) === JSON.stringify(source.particles),
  "page quantum-number table matches independent ledger");
assert(threshold > extrapolated, "strong-decay threshold exceeds held-out prediction");
assert(threshold > source.event.mass + source.event.sigma,
  "threshold exceeds the first-event central mass plus one quoted sigma");
assert(threshold > omega.mass, "strong-decay threshold exceeds current Omega-minus fit");
assert(threshold < competingThreshold,
  "Xi-zero plus K-minus is lighter than Xi-minus plus neutral antikaon");
assert(page.fitPolicy.omegaIncluded === false, "Omega-minus is excluded from every fit");

const requiredSnippets = [
  "<title>Omega Minus Discovery and the Eightfold Way Mass Prediction</title>",
  'content="https://artwaste.land/strata/omega-minus/"',
  '"datePublished":"2026-07-30"',
  '"dateModified":"2026-07-30"',
  'href="/fonts/fonts.css"',
  'src="/media/home-banner.js" defer',
  'id="the-check"',
  "</script>\n</body>\n</html>"
];
for (const snippet of requiredSnippets) {
  assert(html.includes(snippet), `HTML contains required snippet: ${snippet}`);
}

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

console.log("Omega-minus checks passed");
console.log(`historical spacings: ${spacingOne}, ${spacingTwo} MeV/c^2`);
console.log(`held-out extrapolation: ${extrapolated} MeV/c^2`);
console.log(`paper wording anchor: about ${source.paperPrediction} MeV/c^2`);
console.log(`first event: ${source.event.mass} ± ${source.event.sigma} MeV/c^2`);
console.log(`2026 Omega-minus fit: ${fixed(omega.mass, 2)} ± ${fixed(omega.sigma, 2)} MeV/c^2`);
console.log(`2026 Xi-zero plus charged-kaon threshold: ${fixed(threshold, 2)} ± ${fixed(thresholdSigma, 2)} MeV/c^2`);
console.log(`next ground-state two-body channel: ${fixed(competingThreshold, 3)} MeV/c^2`);
console.log(`threshold gap above current Omega-minus: ${fixed(currentGap, 2)} ± ${fixed(currentGapSigma, 2)} MeV/c^2`);
console.log("production vertex: Q 0 to 0, S -1 to -1");
console.log("decay vertex: Q -1 to -1, S -3 to -2, delta S +1");
