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/oklo-reactor/index.html');

let checks = 0;
function pass(message) {
  checks += 1;
  console.log(`PASS ${message}`);
}
function assert(condition, message) {
  if (!condition) {
    console.error(`FAIL ${message}`);
    process.exit(1);
  }
  pass(message);
}
function close(actual, expected, tolerance, message) {
  assert(Number.isFinite(actual) && Math.abs(actual - expected) <= tolerance,
    `${message}: ${actual}`);
}
function rounded(value, places) {
  return Number(value.toFixed(places));
}
function arrayClose(actual, expected, tolerance, message) {
  assert(actual.length === expected.length, `${message}, length ${actual.length}`);
  actual.forEach((value, index) => {
    close(value, expected[index], tolerance, `${message} [${index}]`);
  });
}

const published = Object.freeze({
  assay: Object.freeze({
    gabon: 0.7171,
    historicalReference: 0.7202
  }),
  halfLivesGa: Object.freeze({
    u235: 0.70381,
    u238: 4.4683
  }),
  agesGa: Object.freeze({
    oreFormation: 1.78,
    criticality: 1.968,
    criticalitySigma: 0.050
  }),
  neodymium: Object.freeze({
    masses: Object.freeze([142, 143, 144, 145, 146, 148, 150]),
    natural: Object.freeze([27.11, 12.17, 23.85, 8.30, 17.22, 5.73, 5.62]),
    okloM: Object.freeze([1.38, 22.1, 32.0, 17.7, 15.6, 8.01, 3.40]),
    u235Fission: Object.freeze([0.00, 28.8, 26.5, 18.9, 14.4, 8.26, 3.12])
  }),
  ruthenium: Object.freeze({
    masses: Object.freeze([99, 101, 102, 104]),
    A: Object.freeze({
      calculated: Object.freeze([1.55, 1.29, 1.00, 0.463]),
      observed: Object.freeze([1.05, 1.15, 0.855, 0.424]),
      publishedRatios: Object.freeze([0.677, 0.891, 0.855, 0.916])
    }),
    SF29: Object.freeze({
      calculated: Object.freeze([0.204, 0.170, 0.139, 0.0608]),
      observed: Object.freeze([0.168, 0.165, 0.141, 0.0609]),
      publishedRatios: Object.freeze([0.82, 0.97, 1.01, 1.00])
    })
  }),
  alpha: Object.freeze({
    damourDyson: Object.freeze({ low: -0.9e-7, high: 1.2e-7, confidence: 95 }),
    davisHamdan: Object.freeze({ absolute: 1.1e-8, confidence: 95 })
  })
});

function pastU235Percent(nowAtomPercent, ageGa) {
  const ratioNow = nowAtomPercent / (100 - nowAtomPercent);
  const lambdaDifference =
    Math.log(2) / published.halfLivesGa.u235 -
    Math.log(2) / published.halfLivesGa.u238;
  const ratioPast = ratioNow * Math.exp(lambdaDifference * ageGa);
  return 100 * ratioPast / (1 + ratioPast);
}

function neodymiumResult() {
  const nd = published.neodymium;
  const naturalScale = nd.okloM[0] / nd.natural[0];
  const residual = nd.okloM.map((value, index) =>
    value - naturalScale * nd.natural[index]);
  const residualTotal = residual.reduce((sum, value) => sum + value, 0);
  const normalized = residual.map(value => 100 * value / residualTotal);
  const fissionTotal = nd.u235Fission.reduce((sum, value) => sum + value, 0);
  const fissionNormalized = nd.u235Fission.map(value => 100 * value / fissionTotal);
  const groups = [[1, 2], [3, 4], [5], [6]];
  const group = values => groups.map(indices =>
    indices.reduce((sum, index) => sum + values[index], 0));
  const observedGroups = group(normalized);
  const fissionGroups = group(fissionNormalized);
  const residuals = observedGroups.map((value, index) => value - fissionGroups[index]);
  const singleResiduals = normalized.slice(1).map((value, index) =>
    value - fissionNormalized[index + 1]);
  return {
    naturalScale,
    residual,
    residualTotal,
    normalized,
    fissionNormalized,
    observedGroups,
    fissionGroups,
    residuals,
    singleMaximumMismatch: Math.max(...singleResiduals.map(Math.abs)),
    maximumMismatch: Math.max(...residuals.map(Math.abs))
  };
}

function rutheniumRatios(sample) {
  return sample.observed.map((value, index) => value / sample.calculated[index]);
}

console.log('External anchors first: published source-table values');
assert(published.assay.gabon === 0.7171 &&
  published.assay.historicalReference === 0.7202,
  'Dozol 2023 assay anchors are present');
arrayClose(
  rutheniumRatios(published.ruthenium.SF29).map(value => rounded(value, 2)),
  published.ruthenium.SF29.publishedRatios,
  1e-12,
  'Hidaka et al. 1992 Table 7 SF-29 ratios reproduced'
);

console.log('\nDerived assay check');
const deficitPoints =
  published.assay.historicalReference - published.assay.gabon;
const deficitRelative =
  100 * deficitPoints / published.assay.historicalReference;
close(deficitPoints, 0.0031, 1e-12, 'absolute deficit in percentage points');
close(rounded(deficitRelative, 4), 0.4304, 1e-12, 'relative deficit percent');

console.log('\nTwo-isotope backward clock');
const referenceClock = {
  ore: pastU235Percent(published.assay.historicalReference, published.agesGa.oreFormation),
  low: pastU235Percent(
    published.assay.historicalReference,
    published.agesGa.criticality - published.agesGa.criticalitySigma
  ),
  critical: pastU235Percent(
    published.assay.historicalReference,
    published.agesGa.criticality
  ),
  high: pastU235Percent(
    published.assay.historicalReference,
    published.agesGa.criticality + published.agesGa.criticalitySigma
  )
};
close(rounded(referenceClock.ore, 2), 3.08, 1e-12,
  '0.7202 reference at 1.78 Ga');
close(rounded(referenceClock.critical, 2), 3.58, 1e-12,
  '0.7202 reference at 1.968 Ga');
close(rounded(referenceClock.low, 2), 3.44, 1e-12,
  'criticality lower age endpoint');
close(rounded(referenceClock.high, 2), 3.73, 1e-12,
  'criticality upper age endpoint');
const anomalousClock = [
  pastU235Percent(published.assay.gabon, published.agesGa.oreFormation),
  pastU235Percent(published.assay.gabon, published.agesGa.criticality)
];
arrayClose(anomalousClock.map(value => rounded(value, 2)), [3.07, 3.57], 1e-12,
  '0.7171 anomalous assay clock choices');

console.log('\nNeodymium holdout');
const nd = neodymiumResult();
close(nd.naturalScale, 1.38 / 27.11, 1e-15,
  '142Nd alone fixes natural-pattern scale');
close(rounded(100 * nd.naturalScale, 4), 5.0904, 1e-12,
  'natural-pattern scale printed as percent');
close(nd.residual[0], 0, 1e-12, '142Nd residual is fitted and excluded');
close(rounded(nd.singleMaximumMismatch, 2), 6.22, 1e-12,
  'maximum ungrouped mismatch before capture pairing');
arrayClose(
  nd.observedGroups.map(value => rounded(value, 2)),
  [54.96, 33.65, 8.12, 3.27],
  1e-12,
  'corrected Oklo M capture-preserving groups'
);
arrayClose(
  nd.fissionGroups.map(value => rounded(value, 2)),
  [55.31, 33.31, 8.26, 3.12],
  1e-12,
  'normalized uranium-235 fission groups'
);
close(rounded(nd.maximumMismatch, 2), 0.35, 1e-12,
  'maximum held-out grouped mismatch in percentage points');

console.log('\nRuthenium independent holdout');
arrayClose(
  rutheniumRatios(published.ruthenium.A).map(value => rounded(value, 3)),
  published.ruthenium.A.publishedRatios,
  1e-12,
  'sample A observed/calculated ratios'
);
arrayClose(
  rutheniumRatios(published.ruthenium.SF29).map(value => rounded(value, 2)),
  [0.82, 0.97, 1.01, 1.00],
  1e-12,
  'SF-29 observed/calculated ratios shown on page'
);

console.log('\nShipped-page drift guard');
assert(fs.existsSync(htmlPath), 'HTML exists');
const html = fs.readFileSync(htmlPath, 'utf8');
const dataMatch = html.match(
  /<script type="application\/json" id="source-data">([\s\S]*?)<\/script>/
);
assert(Boolean(dataMatch), 'page contains machine-readable source data');
let pageData;
try {
  pageData = JSON.parse(dataMatch[1]);
} catch (error) {
  console.error(`FAIL source-data JSON parses: ${error.message}`);
  process.exit(1);
}
assert(JSON.stringify(pageData) === JSON.stringify(published),
  'page source inputs equal independent verifier anchors');
assert(html.includes('0.0031 percentage points') && html.includes('0.4304% relative'),
  'assay result is printed to verified precision');
assert(html.includes('3.08%') && html.includes('3.58%') &&
  html.includes('3.44 to 3.73%'),
  'reference-clock anchors are printed to verified precision');
assert(html.includes('54.96, 33.65, 8.12, 3.27') &&
  html.includes('55.31, 33.31, 8.26, 3.12'),
  'neodymium group results are printed to verified precision');
assert(html.includes('6.22 percentage points'),
  'ungrouped neodymium mismatch is printed to verified precision');
assert(html.includes('0.82, 0.97, 1.01, 1.00'),
  'SF-29 ruthenium ratios are printed to verified precision');
assert(html.includes('-0.9 × 10<sup>-7</sup>') &&
  html.includes('1.1 × 10<sup>-8</sup>'),
  'published alpha model outputs are transcribed');
assert(html.includes('</script>\n</body>\n</html>'),
  'load-bearing closing tags are present');

console.log(`\n${checks} checks passed.`);
console.log(
  `Checked numbers: deficit ${deficitPoints.toFixed(4)} points, ` +
  `${deficitRelative.toFixed(4)}% relative; clock ` +
  `${referenceClock.ore.toFixed(2)}%, ${referenceClock.critical.toFixed(2)}% ` +
  `(${referenceClock.low.toFixed(2)} to ${referenceClock.high.toFixed(2)}%); ` +
  `Nd groups ${nd.observedGroups.map(value => value.toFixed(2)).join(', ')} ` +
  `versus ${nd.fissionGroups.map(value => value.toFixed(2)).join(', ')}, ` +
  `max mismatch ${nd.maximumMismatch.toFixed(2)} points; SF-29 Ru ` +
  `${rutheniumRatios(published.ruthenium.SF29)
    .map(value => value.toFixed(2)).join(', ')}.`
);
