#!/usr/bin/env node

import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { runInNewContext } from 'node:vm';

const HTML_PATH = new URL('../../public/strata/seafloor-magnetic-stripes/index.html', import.meta.url);
const html = readFileSync(HTML_PATH, 'utf8');

let checks = 0;

function assert(condition, message) {
  checks += 1;
  if (!condition) {
    console.error(`FAIL ${checks}: ${message}`);
    process.exitCode = 1;
  } else {
    console.log(`PASS ${checks}: ${message}`);
  }
}

function close(actual, expected, tolerance, message) {
  assert(Math.abs(actual - expected) <= tolerance,
    `${message}, got ${actual}, expected ${expected} within ${tolerance}`);
}

function distanceKm(rateCmYr, ageMyr) {
  return rateCmYr * ageMyr * 10;
}

function mean(values) {
  return values.reduce((sum, value) => sum + value, 0) / values.length;
}

function variance(values) {
  const average = mean(values);
  return values.reduce((sum, value) => sum + (value - average) ** 2, 0) / values.length;
}

function correlation(a, b) {
  const ma = mean(a);
  const mb = mean(b);
  let numerator = 0;
  let da = 0;
  let db = 0;
  for (let i = 0; i < a.length; i += 1) {
    const xa = a[i] - ma;
    const xb = b[i] - mb;
    numerator += xa * xb;
    da += xa * xa;
    db += xb * xb;
  }
  return numerator / Math.sqrt(da * db);
}

function detrend(values) {
  const n = values.length;
  const sx = n * (n - 1) / 2;
  const sxx = n * (n - 1) * (2 * n - 1) / 6;
  let sy = 0;
  let sxy = 0;
  for (let i = 0; i < n; i += 1) {
    sy += values[i];
    sxy += i * values[i];
  }
  const slope = (n * sxy - sx * sy) / (n * sxx - sx * sx);
  const intercept = (sy - slope * sx) / n;
  return values.map((value, i) => value - intercept - slope * i);
}

const sourceSnapshot = {
  pitmanHeirtzlerAbstract:
    'Four magnetic profiles across the Pacific-Antarctic Ridge reveal magnetic anomalies. ' +
    'The geometry accords with known reversals during the last 3.4 million years, indicating ' +
    'a spreading rate of 4.5 centimeters per year. Assuming the spreading rate within 500 ' +
    'kilometers has been constant, reversals during the last 10.0 million years can be determined.',
  coxBoundaryAgesMyr: [1.0, 2.5, 3.4],
  coxBoundaryUncertaintyMyr: [0.05, 0.2, 0.1],
  historicalModel: {
    thicknessKm: 2,
    magnetizationGauss: 5e-3,
    inclinationDegreesUp: 60,
    declinationDegreesEast: 25,
    strikeDegreesEastOfNorth: 41,
    centralBlockMultiplier: 2
  }
};

const abstractNumbers = {
  profiles: Number(sourceSnapshot.pitmanHeirtzlerAbstract.match(/^Four/)[0] === 'Four' ? 4 : NaN),
  calibratedMyr: Number(sourceSnapshot.pitmanHeirtzlerAbstract.match(/last ([0-9.]+) million years/)[1]),
  halfRate: Number(sourceSnapshot.pitmanHeirtzlerAbstract.match(/rate of ([0-9.]+) centimeters/)[1]),
  qualifiedKm: Number(sourceSnapshot.pitmanHeirtzlerAbstract.match(/within ([0-9.]+) kilometers/)[1]),
  extendedMyr: Number([...sourceSnapshot.pitmanHeirtzlerAbstract.matchAll(/last ([0-9.]+) million years/g)][1][1])
};

assert(abstractNumbers.profiles === 4, 'external anchor snapshot says four profiles');
close(abstractNumbers.calibratedMyr, 3.4, 0, 'external anchor calibrated interval');
close(abstractNumbers.halfRate, 4.5, 0, 'external anchor half-spreading rate');
close(abstractNumbers.qualifiedKm, 500, 0, 'external anchor constant-rate qualification');
close(abstractNumbers.extendedMyr, 10.0, 0, 'external anchor inferred extension');

const ages = sourceSnapshot.coxBoundaryAgesMyr;
const sigmas = sourceSnapshot.coxBoundaryUncertaintyMyr;
const publishedRate = abstractNumbers.halfRate;
const targets = ages.map(age => distanceKm(publishedRate, age));
const targetSigmas = sigmas.map(sigma => distanceKm(publishedRate, sigma));

close(distanceKm(publishedRate, 3.4), 153.0, 1e-12, '4.5 cm/year for 3.4 Myr gives 153.0 km');
close(distanceKm(publishedRate, 10.0), 450.0, 1e-12, '4.5 cm/year for 10.0 Myr gives 450.0 km');
close(publishedRate * 2, 9.0, 1e-12, 'two 4.5 cm/year flanks give 9.0 cm/year full separation');
assert(targets.join(',') === '45,112.5,153', 'three calibrated target distances are 45, 112.5, and 153 km');
assert(targetSigmas.join(',') === '2.25,9,4.5', 'projected distance uncertainties are 2.25, 9.0, and 4.5 km');

const modelBlocks = [
  { start: 0, end: 1.0, polarity: 1 },
  { start: 1.0, end: 2.5, polarity: -1 },
  { start: 2.5, end: 3.4, polarity: 1 }
];

function blockSignal(distance, rate) {
  const smoothing = 8;
  return modelBlocks.reduce((sum, block) => {
    const left = distanceKm(rate, block.start);
    const right = distanceKm(rate, block.end);
    const response = Math.atan((distance - left) / smoothing) -
      Math.atan((distance - right) / smoothing);
    return sum + 390 * block.polarity * response / Math.PI;
  }, 0);
}

function profileAt(x) {
  const d = Math.abs(x);
  const base = blockSignal(d, publishedRate);
  if (x < 0) {
    return base + 58 * Math.sin(d / 11.2) + 31 * Math.cos(d / 23.5) +
      18 * Math.sin(d / 3.8) + 0.24 * d - 27;
  }
  return base + 54 * Math.sin((d + 1.1) / 11.2) +
    34 * Math.cos((d - 2.0) / 23.5) +
    20 * Math.sin((d + 0.6) / 3.8) - 0.11 * d + 16;
}

function foldSeries(axis, windowKm, removeTrend) {
  const start = Math.ceil((Math.abs(axis) + 4) / 2) * 2;
  let left = [];
  let right = [];
  const distances = [];
  for (let d = start; d <= windowKm; d += 2) {
    left.push(profileAt(axis - d));
    right.push(profileAt(axis + d));
    distances.push(d);
  }
  if (removeTrend) {
    left = detrend(left);
    right = detrend(right);
  }
  return { left, right, distances };
}

function foldMetrics(series) {
  const r = correlation(series.left, series.right);
  const squareError = series.left.reduce((sum, value, i) =>
    sum + (value - series.right[i]) ** 2, 0);
  const pooled = Math.sqrt((variance(series.left) + variance(series.right)) / 2);
  const nrmse = Math.sqrt(squareError / series.left.length) / pooled;
  const n = series.right.length;
  const exclusion = Math.ceil(n * 0.1);
  let nullBelow = 0;
  let tested = 0;
  for (let shift = exclusion; shift <= n - exclusion; shift += 1) {
    const shifted = series.right.slice(shift).concat(series.right.slice(0, shift));
    if (correlation(series.left, shifted) <= r) nullBelow += 1;
    tested += 1;
  }
  return { r, nrmse, percentile: 100 * nullBelow / tested, tested };
}

function rateRmse(rate) {
  const squareError = ages.reduce((sum, age, i) => {
    const difference = distanceKm(rate, age) - targets[i];
    return sum + difference ** 2;
  }, 0);
  return Math.sqrt(squareError / ages.length);
}

const defaultFold = foldMetrics(foldSeries(23, 160, true));
const zeroFold = foldMetrics(foldSeries(0, 160, true));
const missedFold = foldMetrics(foldSeries(25, 160, true));
const defaultRateRmse = rateRmse(3.2);

assert(zeroFold.r > defaultFold.r, 'published model axis scores above the default displaced crease');
assert(zeroFold.r > missedFold.r, 'published model axis scores above a 25 km miss');
assert(zeroFold.nrmse < defaultFold.nrmse, 'published model axis has lower mismatch than default');
close(rateRmse(4.5), 0, 1e-12, 'derived target error is zero at 4.5 cm/year');
assert(rateRmse(4.4) > 0 && rateRmse(4.6) > 0, 'rate errors on both sides of 4.5 are positive');

function htmlData(name) {
  const match = html.match(new RegExp(`data-${name}="([^"]+)"`));
  assert(Boolean(match), `HTML exposes ${name}`);
  return match ? Number(match[1]) : NaN;
}

close(htmlData('default-axis-r'), Number(defaultFold.r.toFixed(6)), 5e-7,
  'HTML default fold r agrees with independent implementation');
close(htmlData('default-axis-nrmse'), Number(defaultFold.nrmse.toFixed(6)), 5e-7,
  'HTML default fold mismatch agrees with independent implementation');
close(htmlData('default-axis-null'), Number(defaultFold.percentile.toFixed(6)), 5e-7,
  'HTML default null percentile agrees with independent implementation');
close(htmlData('zero-axis-r'), Number(zeroFold.r.toFixed(6)), 5e-7,
  'HTML zero-axis r agrees with independent implementation');
close(htmlData('axis25-r'), Number(missedFold.r.toFixed(6)), 5e-7,
  'HTML 25 km miss r agrees with independent implementation');
close(htmlData('default-rate-rmse'), Number(defaultRateRmse.toFixed(6)), 5e-7,
  'HTML default rate RMSE agrees with independent implementation');

const inlineScripts = [...html.matchAll(/<script([^>]*)>([\s\S]*?)<\/script>/g)]
  .filter(match => !match[1].includes('src=') && !match[1].includes('application/ld+json'));
assert(inlineScripts.length === 1, 'page has one executable inline script');

function fakeElement(id = '') {
  const listeners = {};
  const context = {
    setTransform() {}, clearRect() {}, fillRect() {}, beginPath() {}, moveTo() {},
    lineTo() {}, stroke() {}, fillText() {}, setLineDash() {}, arc() {}, fill() {}
  };
  return {
    id,
    value: '',
    checked: false,
    textContent: '',
    innerHTML: '',
    clientWidth: 900,
    width: 900,
    height: 360,
    children: [],
    listeners,
    getContext() { return context; },
    getBoundingClientRect() { return { left: 0, width: 900 }; },
    addEventListener(type, handler) {
      if (!listeners[type]) listeners[type] = [];
      listeners[type].push(handler);
    },
    appendChild(child) { this.children.push(child); },
    setAttribute(name, value) { this[name] = value; },
    setPointerCapture() {}
  };
}

const browserElements = new Map();
function element(id) {
  if (!browserElements.has(id)) browserElements.set(id, fakeElement(id));
  return browserElements.get(id);
}

element('axisCtl').value = '23';
element('windowCtl').value = '160';
element('detrendCtl').checked = true;
element('rateCtl').value = '3.2';

const fakeDocument = {
  getElementById(id) { return element(id); },
  createElement() { return fakeElement(); }
};
const fakeWindow = {
  devicePixelRatio: 1,
  innerWidth: 900,
  matchMedia() { return { matches: true }; },
  addEventListener() {}
};

runInNewContext(inlineScripts[0][2], {
  window: fakeWindow,
  document: fakeDocument,
  Math,
  Number,
  String,
  Array,
  Object
});

function browserText(id) {
  return element(id).textContent;
}

function trigger(id, type) {
  const handlers = element(id).listeners[type] || [];
  assert(handlers.length > 0, `${id} has a ${type} handler`);
  handlers.forEach(handler => handler({}));
}

assert(browserText('corrOut') === `r = ${defaultFold.r.toFixed(3)}`,
  'visible default fold correlation matches independent result');
assert(browserText('nrmseOut') === defaultFold.nrmse.toFixed(3),
  'visible default fold mismatch matches independent result');
assert(browserText('nullOut') === `${defaultFold.percentile.toFixed(1)}%`,
  'visible default fold null rank matches independent result');
assert(browserText('axisNow') === '+23 km' && browserText('windowNow') === '160 km',
  'visible default fold controls match their input values');
assert(browserText('rateOut') === 'hidden' && browserText('rateNow') === 'hidden',
  'default trial rate remains blind');
assert(browserText('rateErrOut') === `${defaultRateRmse.toFixed(1)} km`,
  'visible default rate error matches independent result');
assert(browserText('edgeOut') === `${distanceKm(3.2, 3.4).toFixed(1)} km`,
  'visible default 3.4 Myr edge matches independent result');

const rows = element('boundaryTable').children;
assert(rows.length === 3, 'browser builds three boundary rows');
assert(rows.map(row => row.innerHTML).join('').includes('45.0 km') &&
  rows.map(row => row.innerHTML).join('').includes('112.5 km') &&
  rows.map(row => row.innerHTML).join('').includes('153.0 km'),
'browser boundary table displays all independently derived targets');

trigger('foldBtn', 'click');
assert(browserText('corrOut') === `r = ${zeroFold.r.toFixed(3)}` &&
  browserText('nrmseOut') === zeroFold.nrmse.toFixed(3),
'Fold button displays the independently checked zero-axis result');

trigger('missBtn', 'click');
assert(browserText('corrOut') === `r = ${missedFold.r.toFixed(3)}` &&
  browserText('nrmseOut') === missedFold.nrmse.toFixed(3),
'Miss button displays the independently checked 25 km result');

trigger('publishedBtn', 'click');
trigger('revealBtn', 'click');
assert(element('rateCtl').value === '4.5', 'published preset assigns the exact constant in script');
assert(browserText('rateOut') === '4.50 cm/year' &&
  browserText('rateErrOut') === '0.0 km' &&
  browserText('edgeOut') === '153.0 km',
'published preset displays the independently checked rate, error, and edge');

for (const literal of [
  '153.0 km', '450.0 km', '9.0 cm/year', '2.25, 9.0, and 4.5 km',
  '2 km', '5 × 10<sup>-3</sup> gauss', '60 degrees upward',
  '25 degrees E', 'N41 degrees E'
]) {
  assert(html.includes(literal), `page contains checked display literal: ${literal}`);
}

assert(html.includes('not Eltanin-19 data'), 'synthetic fold is explicitly not labelled as measured data');
assert(html.includes('dimensional identity, not an independent recovery'),
  'rate minimum is explicitly labelled tautological');
assert(html.includes('No measured Eltanin correlation, sample count, file hash, or fitted rate is claimed'),
  'missing empirical outputs are named');
assert(!html.includes('fetch(') && !html.includes('https://cdn'),
  'page makes no scripted third-party request');

const htmlHash = createHash('sha256').update(html).digest('hex');
console.log('');
console.log('Checked numbers');
console.log(`  Published anchors: ${abstractNumbers.profiles} profiles; ${abstractNumbers.calibratedMyr} Myr; ${publishedRate} cm/year; ${abstractNumbers.qualifiedKm} km; ${abstractNumbers.extendedMyr.toFixed(1)} Myr`);
console.log(`  Derived distances: ${targets.join(', ')} km; 10.0 Myr = ${distanceKm(publishedRate, 10).toFixed(1)} km`);
console.log(`  Distance uncertainties: ${targetSigmas.join(', ')} km`);
console.log(`  Synthetic default axis: r=${defaultFold.r.toFixed(6)}, NRMSE=${defaultFold.nrmse.toFixed(6)}, null=${defaultFold.percentile.toFixed(6)}%, n=${defaultFold.tested}`);
console.log(`  Synthetic axis 0: r=${zeroFold.r.toFixed(6)}, NRMSE=${zeroFold.nrmse.toFixed(6)}`);
console.log(`  Synthetic axis 25: r=${missedFold.r.toFixed(6)}, NRMSE=${missedFold.nrmse.toFixed(6)}`);
console.log(`  Default rate 3.2: RMSE=${defaultRateRmse.toFixed(6)} km`);
console.log(`  Historical model constants: ${sourceSnapshot.historicalModel.thicknessKm} km, ${sourceSnapshot.historicalModel.magnetizationGauss} gauss, ${sourceSnapshot.historicalModel.inclinationDegreesUp} degrees up, ${sourceSnapshot.historicalModel.declinationDegreesEast} degrees E, N${sourceSnapshot.historicalModel.strikeDegreesEastOfNorth} degrees E`);
console.log(`  HTML sha256: ${htmlHash}`);
console.log('');

if (process.exitCode) {
  console.error(`${checks} checks run, at least one failed.`);
  process.exit(1);
}

console.log(`${checks} checks passed.`);
