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 root = path.resolve(here, "../..");
const htmlPath = path.join(root, "public/strata/meselson-stahl/index.html");
const html = fs.readFileSync(htmlPath, "utf8");

let checks = 0;

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

function check(condition, message) {
  if (!condition) fail(message);
  checks += 1;
}

function near(actual, expected, tolerance, label) {
  check(Number.isFinite(actual), `${label} is not finite`);
  check(Math.abs(actual - expected) <= tolerance,
    `${label}: expected ${expected}, got ${actual}`);
}

function extractJson(label, pattern) {
  const match = html.match(pattern);
  check(Boolean(match), `found ${label} in page source`);
  try {
    return JSON.parse(match[1]);
  } catch (error) {
    fail(`${label} is not valid JSON: ${error.message}`);
  }
}

function extractFunction(name) {
  const pattern = new RegExp(
    `\\/\\/ verifier:${name}-start\\n([\\s\\S]*?)\\n\\s*\\/\\/ verifier:${name}-end`
  );
  const match = html.match(pattern);
  check(Boolean(match), `found page function ${name}`);
  try {
    return vm.runInNewContext(`(${match[1]})`, Object.create(null), {
      timeout: 1000
    });
  } catch (error) {
    fail(`could not evaluate page function ${name}: ${error.message}`);
  }
}

const external = Object.freeze({
  sourceGenerations: [0, 0.3, 0.7, 1, 1.5, 1.9, 2.5, 3, 4.1],
  generationHours: [0.81, 0.85],
  hybridPosition: 0.5,
  hybridPositionError: 0.02,
  nativeDensitySeparation: 0.014,
  centrifugeHours: 20,
  centrifugeRpm: 44770,
  centrifugeG: 140000,
  heatC: 100,
  heatMinutes: 30,
  heatDensitySeparation: 0.015,
  heatMolecularWeightRatio: 0.5
});

const pagePublished = extractJson(
  "published anchor object",
  /var PUBLISHED = Object\.freeze\((\{[^\n]+\})\);/
);

for (const [key, expected] of Object.entries(external)) {
  const actual = pagePublished[key];
  if (Array.isArray(expected)) {
    check(Array.isArray(actual), `${key} is an array`);
    check(actual.length === expected.length, `${key} length is ${expected.length}`);
    actual.forEach((value, index) => near(value, expected[index], 1e-12,
      `${key}[${index}]`));
  } else {
    near(actual, expected, 1e-12, key);
  }
}

console.log("Published anchors:");
console.log(`  source generations: ${external.sourceGenerations.join(", ")}`);
console.log(`  generation times: ${external.generationHours.join(" h, ")} h`);
console.log(`  native reference separation: ${external.nativeDensitySeparation.toFixed(3)} g/cm3`);
console.log(`  hybrid position: ${(100 * external.hybridPosition).toFixed(0)} plus or minus ${(100 * external.hybridPositionError).toFixed(0)}%`);
console.log(`  Figure 4 run: ${external.centrifugeHours} h, ${external.centrifugeRpm.toLocaleString("en-US")} rpm, about ${external.centrifugeG.toLocaleString("en-US")} times g`);
console.log(`  heat: ${external.heatC} C for ${external.heatMinutes} min`);
console.log(`  heated separation: ${external.heatDensitySeparation.toFixed(3)} g/cm3`);
console.log(`  published apparent-molecular-weight ratio: about ${external.heatMolecularWeightRatio}`);

function histogram(molecules) {
  const map = new Map();
  for (const molecule of molecules) {
    const fraction = molecule.kind === "duplex"
      ? (molecule.strands.filter((strand) => strand === "H").length / 2)
      : molecule.heavyFraction;
    const key = fraction.toFixed(12);
    map.set(key, (map.get(key) || 0) + 1);
  }
  const total = molecules.length;
  return [...map.entries()]
    .map(([key, count]) => ({ x: Number(key), w: count / total }))
    .sort((a, b) => a.x - b.x);
}

function nextGeneration(model, molecules) {
  const daughters = [];
  for (const molecule of molecules) {
    if (model === "conservative") {
      daughters.push({
        kind: "duplex",
        strands: molecule.strands.slice()
      });
      daughters.push({ kind: "duplex", strands: ["L", "L"] });
    } else if (model === "semiconservative") {
      daughters.push({ kind: "duplex", strands: [molecule.strands[0], "L"] });
      daughters.push({ kind: "duplex", strands: [molecule.strands[1], "L"] });
    } else if (model === "dispersive") {
      daughters.push({ kind: "mosaic", heavyFraction: molecule.heavyFraction / 2 });
      daughters.push({ kind: "mosaic", heavyFraction: molecule.heavyFraction / 2 });
    } else {
      fail(`unknown enumerator model ${model}`);
    }
  }
  return daughters;
}

function enumerate(model, generation) {
  let molecules = model === "dispersive"
    ? [{ kind: "mosaic", heavyFraction: 1 }]
    : [{ kind: "duplex", strands: ["H", "H"] }];
  for (let n = 0; n < generation; n += 1) {
    molecules = nextGeneration(model, molecules);
  }
  return { molecules, species: histogram(molecules) };
}

function compareSpecies(actual, expected, label) {
  check(Array.isArray(actual), `${label} returns an array`);
  check(actual.length === expected.length,
    `${label} species count ${actual.length} equals ${expected.length}`);
  const sorted = actual.slice().sort((a, b) => a.x - b.x);
  for (let i = 0; i < expected.length; i += 1) {
    near(sorted[i].x, expected[i].x, 1e-12, `${label} center ${i}`);
    near(sorted[i].w, expected[i].w, 1e-12, `${label} weight ${i}`);
  }
  near(sorted.reduce((sum, species) => sum + species.w, 0), 1, 1e-12,
    `${label} total weight`);
}

const pageSpeciesFor = extractFunction("speciesFor");
for (const model of ["conservative", "semiconservative", "dispersive"]) {
  for (let generation = 0; generation <= 4; generation += 1) {
    const enumerated = enumerate(model, generation);
    check(enumerated.molecules.length === 2 ** generation,
      `${model} generation ${generation} has ${2 ** generation} molecules`);
    compareSpecies(
      pageSpeciesFor(model, generation),
      enumerated.species,
      `${model} generation ${generation}`
    );
  }
}

console.log("Independent molecule enumeration:");
for (let generation = 0; generation <= 4; generation += 1) {
  const species = enumerate("semiconservative", generation).species;
  console.log(`  semiconservative n=${generation}: ${species.map((s) =>
    `x=${s.x.toFixed(3)}, w=${s.w.toFixed(3)}`).join(" | ")}`);
}

const source = extractJson(
  "source structural transcription",
  /var SOURCE = Object\.freeze\((\[[^\n]+\])\);/
);
check(source.length === external.sourceGenerations.length,
  "source transcription has every reported sample");

const expectedCenters = [
  [1],
  [0.5, 1],
  [0.5, 1],
  [0.5],
  [0, 0.5],
  [0, 0.5],
  [0, 0.5],
  [0, 0.5],
  [0, 0.5]
];

source.forEach((sample, index) => {
  near(sample.g, external.sourceGenerations[index], 1e-12,
    `source sample ${index} generation label`);
  const centers = sample.bands.map((band) => band.x).sort((a, b) => a - b);
  check(centers.length === expectedCenters[index].length,
    `source sample ${sample.g} band count`);
  centers.forEach((center, bandIndex) => near(
    center,
    expectedCenters[index][bandIndex],
    1e-12,
    `source sample ${sample.g} band ${bandIndex}`
  ));
  near(sample.bands.reduce((sum, band) => sum + band.a, 0), 1, 1e-12,
    `source sample ${sample.g} chosen display amplitudes normalize`);
});

const pageHeatSpecies = extractFunction("heatSpecies");
const heated = pageHeatSpecies(true);
compareSpecies(heated, [{ x: 0, w: 0.5 }, { x: 1, w: 0.5 }],
  "heated first-generation hybrid");
compareSpecies(pageHeatSpecies(false), [{ x: 0.5, w: 1 }],
  "unheated first-generation hybrid");

const densitySeparation = Math.abs(heated[1].x - heated[0].x)
  * external.heatDensitySeparation;
near(densitySeparation, 0.015, 5e-13, "heated density separation");

function gaussian(x, mean, sigma) {
  return Math.exp(-0.5 * ((x - mean) / sigma) ** 2)
    / (sigma * Math.sqrt(2 * Math.PI));
}

function integrateSpecies(species, sigma, steps = 200000) {
  const lo = -0.5;
  const hi = 1.5;
  const dx = (hi - lo) / steps;
  let area = 0;
  for (let i = 0; i < steps; i += 1) {
    const x = lo + (i + 0.5) * dx;
    for (const band of species) {
      area += band.w * gaussian(x, band.x, sigma) * dx;
    }
  }
  return area;
}

const sigmaMatch = html.match(/var DISPLAY_SIGMA = ([0-9.]+);/);
check(Boolean(sigmaMatch), "found page display sigma");
const sigmaIntact = Number(sigmaMatch[1]);
near(sigmaIntact, 0.055, 1e-12, "fixed display sigma");
const sigmaSingle = sigmaIntact * Math.SQRT2;
const widthDerivedRatio = (sigmaIntact / sigmaSingle) ** 2;
near(widthDerivedRatio, 0.5, 1e-12,
  "display width-squared apparent-molecular-weight ratio");
near(integrateSpecies(heated, sigmaSingle), 1, 1e-10,
  "numerically integrated heated trace area");
near(heated[0].w / heated[1].w, 1, 1e-12,
  "heated heavy-to-light area ratio");

console.log("Heat operation:");
console.log(`  species: x=${heated[0].x.toFixed(3)}, w=${heated[0].w.toFixed(3)} | x=${heated[1].x.toFixed(3)}, w=${heated[1].w.toFixed(3)}`);
console.log(`  area ratio: ${(heated[0].w / heated[1].w).toFixed(3)}`);
console.log(`  separation: ${densitySeparation.toFixed(3)} g/cm3`);
console.log(`  width-squared display ratio: ${widthDerivedRatio.toFixed(3)}`);

check(html.includes("Generation 0 is calibration only"),
  "page names the generation 0 vacuous setting");
check(html.includes("generation 1 cannot separate semiconservative from simple dispersive copying"),
  "page names the generation 1 tie");
check(html.includes("not a standard deviation"),
  "page names the 2 percent uncertainty correctly");
check(html.includes("not a pixel digitization"),
  "page labels the structural redraw honestly");
check(html.includes("Nitrogen-15 is stable"),
  "page does not imply a radioactive tracer");
check(!html.includes("was a radioactive tracer"),
  "page never calls nitrogen-15 radioactive");

for (const slug of ["luria-delbruck", "more-data-wrong-tree", "neutrino-endpoint"]) {
  check(fs.existsSync(path.join(root, `src/content/strata/${slug}.md`)),
    `relation target exists: ${slug}`);
}

check(html.trimEnd().endsWith("</html>"), "HTML ends with closing html tag");
check(/<\/script>\s*<\/body>\s*<\/html>\s*$/.test(html),
  "load-bearing closing tags are present");
check(!html.includes(String.fromCodePoint(0x2014)),
  "HTML contains no em dash character");

console.log(`PASS: ${checks} checks`);
