import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';

const here = dirname(fileURLToPath(import.meta.url));
const htmlPath = resolve(here, '../../public/strata/chicxulub-iridium/index.html');
const mdPath = resolve(here, '../../src/content/strata/chicxulub-iridium.md');
const html = readFileSync(htmlPath, 'utf8');
const markdown = readFileSync(mdPath, 'utf8');

let checks = 0;
function assert(condition, message) {
  checks += 1;
  if (!condition) {
    console.error(`FAIL ${checks}: ${message}`);
    process.exitCode = 1;
  }
}
function close(actual, expected, tolerance, label) {
  assert(Math.abs(actual - expected) <= tolerance, `${label}: ${actual} != ${expected}`);
}
function sci(value, digits) {
  return value.toExponential(digits).replace('e+', 'e');
}

const source = Object.freeze({
  gubbio: Object.freeze({
    boundaryPpb: 9.1,
    backgroundCapPpb: 0.3,
    wholeRockPpb: 6.3,
    crustCapPpb: 0.1,
    fluenceGPerCm2: 8e-9
  }),
  m0077: Object.freeze({
    bandCm: 15,
    bandFloorPpb: 0.3,
    peakFloorPpb: 1.0,
    backgroundPpb: 0.05,
    dryDensityGPerCm3: 2.53,
    publishedFluenceNgPerCm2: 20,
    highTopMbsf: 616.55,
    highBottomMbsf: 616.60
  }),
  alvarez: Object.freeze({
    iridiumFraction: 0.5e-6,
    depositionFraction: 0.22,
    densityGPerCm3: 2.2,
    preliminaryMassG: 7.4e16,
    printedCorrectedMassG: 3.4e17,
    printedDiameterKm: 6.6
  }),
  exact: Object.freeze({
    earthRadiusKm: 6371
  })
});

const expected = Object.freeze({
  enrichment: 30.333333333333332,
  m0077FloorNgPerCm2: 9.4875,
  correctedCarryMassG: 3.3636363636363635e17,
  carriedDiameterKm: 6.634312307929023,
  earthAreaCm2: 5.100644719097883e18,
  exactPreliminaryMassG: 8.161031550556613e16,
  exactMassG: 3.7095597957075514e17,
  exactDiameterKm: 6.854361797428229,
  exactGlobalIrG: 4.0805157752783066e10,
  coreMassG: 9.273899489268878e17,
  coreDiameterKm: 9.302800206727156,
  floorMassG: 4.399306070222e17,
  floorDiameterKm: 7.25528190374301,
  areaResidualPercent: 10.284210142657,
  cubeUp: 1.2599210498948732,
  cubeDown: 0.7937005259840998
});

function diameterKm(massG, densityGPerCm3) {
  return Math.cbrt((6 * massG) / (Math.PI * densityGPerCm3)) / 1e5;
}
function areaCm2(radiusKm) {
  return 4 * Math.PI * Math.pow(radiusKm * 1e5, 2);
}
function massFromFluence(fluenceGPerCm2, area, fraction, efficiency) {
  return (fluenceGPerCm2 * area) / (fraction * efficiency);
}

const enrichment = source.gubbio.boundaryPpb / source.gubbio.backgroundCapPpb;
close(enrichment, expected.enrichment, 1e-12, 'Gubbio enrichment');
assert(enrichment > 30, 'Gubbio enrichment must exceed 30');

const m0077Floor =
  (source.m0077.bandFloorPpb - source.m0077.backgroundPpb) *
  source.m0077.dryDensityGPerCm3 *
  source.m0077.bandCm;
close(m0077Floor, expected.m0077FloorNgPerCm2, 1e-12, 'M0077 textual fluence floor');
assert(m0077Floor < source.m0077.publishedFluenceNgPerCm2, 'M0077 floor must remain below published full-profile fluence');
close(source.m0077.highBottomMbsf - source.m0077.highTopMbsf, 0.05, 1e-10, 'M0077 highest-enrichment interval width');

const carriedMass = source.alvarez.preliminaryMassG / source.alvarez.depositionFraction;
close(carriedMass, expected.correctedCarryMassG, 1e3, '1980 carried corrected mass');
close(Number(carriedMass.toExponential(1)), source.alvarez.printedCorrectedMassG, 1e3, '1980 printed corrected mass');

const carriedDiameter = diameterKm(carriedMass, source.alvarez.densityGPerCm3);
close(carriedDiameter, expected.carriedDiameterKm, 1e-12, '1980 carried diameter');
close(Number(carriedDiameter.toFixed(1)), source.alvarez.printedDiameterKm, 1e-12, '1980 printed diameter');

const exactArea = areaCm2(source.exact.earthRadiusKm);
const exactPreliminary =
  source.gubbio.fluenceGPerCm2 * exactArea / source.alvarez.iridiumFraction;
const exactMass = massFromFluence(
  source.gubbio.fluenceGPerCm2,
  exactArea,
  source.alvarez.iridiumFraction,
  source.alvarez.depositionFraction
);
const exactDiameter = diameterKm(exactMass, source.alvarez.densityGPerCm3);
const exactGlobalIr = source.gubbio.fluenceGPerCm2 * exactArea;
const residualPercent =
  ((exactPreliminary / source.alvarez.preliminaryMassG) - 1) * 100;

close(exactArea, expected.earthAreaCm2, 1e4, 'exact Earth area');
close(exactPreliminary, expected.exactPreliminaryMassG, 1e3, 'exact preliminary mass');
close(exactMass, expected.exactMassG, 1e3, 'exact corrected mass');
close(exactDiameter, expected.exactDiameterKm, 1e-12, 'exact diameter');
close(exactGlobalIr, expected.exactGlobalIrG, 1e-5, 'exact global iridium mass');
close(residualPercent, expected.areaResidualPercent, 1e-10, '1980 versus declared-area residual');

const coreMass = massFromFluence(
  source.m0077.publishedFluenceNgPerCm2 * 1e-9,
  exactArea,
  source.alvarez.iridiumFraction,
  source.alvarez.depositionFraction
);
const coreDiameter = diameterKm(coreMass, source.alvarez.densityGPerCm3);
const floorMass = massFromFluence(
  m0077Floor * 1e-9,
  exactArea,
  source.alvarez.iridiumFraction,
  source.alvarez.depositionFraction
);
const floorDiameter = diameterKm(floorMass, source.alvarez.densityGPerCm3);
close(coreMass, expected.coreMassG, 1e3, 'M0077 published-fluence mass');
close(coreDiameter, expected.coreDiameterKm, 1e-12, 'M0077 published-fluence diameter');
close(floorMass, expected.floorMassG, 1e4, 'M0077 floor mass');
close(floorDiameter, expected.floorDiameterKm, 1e-12, 'M0077 floor diameter');

const baseD = diameterKm(exactMass, source.alvarez.densityGPerCm3);
const doubleFluenceD = diameterKm(exactMass * 2, source.alvarez.densityGPerCm3);
const doubleFractionD = diameterKm(exactMass / 2, source.alvarez.densityGPerCm3);
const doubleEfficiencyD = diameterKm(exactMass / 2, source.alvarez.densityGPerCm3);
const doubleDensityD = diameterKm(exactMass, source.alvarez.densityGPerCm3 * 2);
close(doubleFluenceD / baseD, expected.cubeUp, 1e-12, 'double fluence sensitivity');
close(doubleFractionD / baseD, expected.cubeDown, 1e-12, 'double iridium fraction sensitivity');
close(doubleEfficiencyD / baseD, expected.cubeDown, 1e-12, 'double efficiency sensitivity');
close(doubleDensityD / baseD, expected.cubeDown, 1e-12, 'double density sensitivity');

const requiredHtml = [
  '9.1 ppb',
  '30.33',
  '9.4875 ng/cm²',
  '8 ng/cm²',
  'about 20 ng/cm²',
  '7.4 × 10<sup>16</sup> g',
  '3.4 × 10<sup>17</sup> g',
  '6.6 km',
  '5.1006 × 10<sup>18</sup> cm²',
  '8.161 × 10<sup>16</sup> g',
  '3.710 × 10<sup>17</sup> g',
  '6.854 km',
  '4.081 × 10<sup>10</sup> g',
  '10.28%',
  '"datePublished":"2026-07-30"',
  '"dateModified":"2026-07-30"',
  '<title>Chicxulub Iridium Layer and the Dinosaur Extinction</title>',
  '<link rel="canonical" href="https://artwaste.land/strata/chicxulub-iridium/" />',
  '{ fluence:20, fractionPpm:0.5, eta:0.22, density:2.2 }',
  '{ fluence:9.4875, fractionPpm:0.5, eta:0.22, density:2.2 }',
  '</script>\n</body>\n</html>'
];
for (const fragment of requiredHtml) {
  assert(html.includes(fragment), `HTML is missing checked fragment: ${fragment}`);
}

const forbiddenDash = String.fromCodePoint(0x2014);
assert(!html.includes(forbiddenDash), 'HTML contains a forbidden long dash');
assert(!markdown.includes(forbiddenDash), 'content markdown contains a forbidden long dash');
assert(html.includes('<script src="/media/home-banner.js" defer></script>'), 'home banner script is missing');
assert(html.includes('<link rel="stylesheet" href="/fonts/fonts.css" />'), 'font stylesheet is missing');
assert(!/<script\b[^>]*\bsrc=["']https?:\/\//i.test(html), 'page contains a third-party script load');
assert(!/<img\b[^>]*\bsrc=["']https?:\/\//i.test(html), 'page contains a third-party image load');
assert(!/<link\b[^>]*rel=["']stylesheet["'][^>]*href=["']https?:\/\//i.test(html), 'page contains a third-party stylesheet load');

const relateSlugs = [...markdown.matchAll(/^\s+- to: ([a-z0-9-]+)$/gm)].map((match) => match[1]);
assert(relateSlugs.length === 4, 'frontmatter must contain four relation edges');
for (const slug of relateSlugs) {
  const path = resolve(here, `../../src/content/strata/${slug}.md`);
  try {
    readFileSync(path, 'utf8');
    assert(true, `related slug exists: ${slug}`);
  } catch {
    assert(false, `related slug does not exist: ${slug}`);
  }
}

console.log(`Gubbio: 9.1 / 0.3 = ${enrichment.toFixed(6)} times background cap`);
console.log(`M0077 prose-derived fluence floor: ${m0077Floor.toFixed(4)} ng/cm2`);
console.log(`1980 carry: ${sci(carriedMass, 6)} g, ${carriedDiameter.toFixed(6)} km`);
console.log(`Declared-radius Earth area: ${sci(exactArea, 6)} cm2`);
console.log(`Exact-area replay: ${sci(exactPreliminary, 6)} g preliminary, ${sci(exactMass, 6)} g corrected, ${exactDiameter.toFixed(6)} km`);
console.log(`M0077 published-fluence replay: ${sci(coreMass, 6)} g, ${coreDiameter.toFixed(6)} km`);
console.log(`M0077 prose-floor replay: ${sci(floorMass, 6)} g, ${floorDiameter.toFixed(6)} km`);
console.log(`Printed-chain area residual: ${residualPercent.toFixed(6)} percent`);
console.log(`Cube-root ratios: up ${expected.cubeUp.toFixed(9)}, down ${expected.cubeDown.toFixed(9)}`);

if (process.exitCode) {
  console.error(`${checks} checks run, failures above`);
  process.exit(1);
}
console.log(`PASS: ${checks} checks`);
