#!/usr/bin/env node
// verify-how-old-is-the-bottom-of-an-ice-core.mjs: checks /strata/how-old-is-the-bottom-of-an-ice-core/
// ("Most of the Time Is at the Bottom").
//
//   node verify-how-old-is-the-bottom-of-an-ice-core.mjs            # data, arithmetic, prose
//   node verify-how-old-is-the-bottom-of-an-ice-core.mjs --mutate   # also break the engine on purpose
//   node verify-how-old-is-the-bottom-of-an-ice-core.mjs --files=DIR # test a copy you edited, not the site
//
// Needs only Node 18+. Inside the repository it tests the local files; from an empty directory it
// downloads the page's engine.mjs, data.mjs and index.html from https://artwaste.land into
// ./how-old-is-the-bottom-of-an-ice-core-files/ (the bytes your browser runs). Exit 0 = every check passed.
//
// It also fetches the EDC chronology from PANGAEA itself (doi:10.1594/PANGAEA.824865) and compares
// the page's copy with it row by row. If PANGAEA cannot be reached, that check is reported as
// SKIPPED, never as passed.
//
// What it does NOT check: the quotations and facts from papers (drilling dates, diffusion lengths,
// the oldest-ice reports). Those were read by hand; the page names each source.

import { existsSync, mkdirSync, writeFileSync, readFileSync, mkdtempSync, rmSync } from 'node:fs';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import { tmpdir } from 'node:os';

const here = dirname(fileURLToPath(import.meta.url));
const slug = 'how-old-is-the-bottom-of-an-ice-core';
const FILES = ['engine.mjs', 'data.mjs', 'index.html'];
const MUTATE = process.argv.includes('--mutate');
const filesArg = process.argv.find((a) => a.startsWith('--files='));
let dir = filesArg ? resolve(filesArg.slice(8)) : join(here, 'public/strata', slug);
if (!filesArg && !existsSync(join(dir, 'engine.mjs'))) {
  dir = resolve(`${slug}-files`); mkdirSync(dir, { recursive: true });
  for (const f of FILES) {
    const r = await fetch(`https://artwaste.land/strata/${slug}/${f}`);
    if (!r.ok) throw new Error(`could not download ${f}: ${r.status}`);
    writeFileSync(join(dir, f), Buffer.from(await r.arrayBuffer()));
  }
}
console.error(`files: ${dir}`);
const engineSrc = readFileSync(join(dir, 'engine.mjs'), 'utf8');
const html = readFileSync(join(dir, 'index.html'), 'utf8');
const D = await import(pathToFileURL(join(dir, 'data.mjs')).href);

const near = (a, b, tol) => Math.abs(a - b) <= tol;
const fmt = (x, d = 0) => x.toLocaleString('en-GB', { minimumFractionDigits: d, maximumFractionDigits: d });

// ---- independent helpers, written without the engine ----
// Age at depth by a linear scan (the engine uses bisection).
function scanAge(depth, age, z) {
  for (let i = 1; i < depth.length; i++) if (depth[i] >= z) return age[i - 1] + (z - depth[i - 1]) / (depth[i] - depth[i - 1]) * (age[i] - age[i - 1]);
  return age[age.length - 1];
}
// Depth for an age by fine bisection on scanAge (the engine interpolates age -> depth directly).
function scanDepth(depth, age, t) {
  let lo = depth[0], hi = depth[depth.length - 1];
  for (let k = 0; k < 80; k++) { const m = (lo + hi) / 2; if (scanAge(depth, age, m) < t) lo = m; else hi = m; }
  return (lo + hi) / 2;
}
// A sine of wavelength w convolved numerically with a Gaussian of s.d. s: returns the amplitude kept.
function convolveSine(s, w) {
  const n = 4000, span = 8 * s, h = (2 * span) / n;
  let acc = 0, norm = 0;
  for (let i = 0; i <= n; i++) {
    const u = -span + i * h, g = Math.exp(-(u * u) / (2 * s * s)) * (i === 0 || i === n ? 0.5 : 1);
    acc += g * Math.cos((2 * Math.PI * u) / w); norm += g;
  }
  return acc / norm;
}
// Nye by numerical integration of dt = dz / (a (H - z) / H).
function nyeNumeric(z, H, a) {
  const n = 200000, h = z / n; let t = 0;
  for (let i = 0; i < n; i++) { const zm = (i + 0.5) * h; t += h / ((a * (H - zm)) / H); }
  return t;
}

async function suite(E, { quiet = false } = {}) {
  let pass = 0, fail = 0;
  const check = (name, ok, detail = '') => {
    if (ok) pass++; else fail++;
    if (!quiet) console.log(`${ok ? 'ok  ' : 'FAIL'} ${name}${detail ? `  (${detail})` : ''}`);
  };
  const c = E.prepare(D.EDC), g = E.prepare(D.NGRIP);
  const { depth, age, acc, tf } = D.EDC;

  // --- the data ---
  check('EDC chronology: 1,936 rows, depth and age both strictly increasing',
    depth.length === 1936 && depth.every((z, i) => !i || z > depth[i - 1]) && age.every((t, i) => !i || t > age[i - 1]));
  check('EDC dated core: 0 to 3,192.75 m, oldest age 807,941 years BP, its 1σ 12,371 years',
    depth[0] === 0 && depth.at(-1) === 3192.75 && age.at(-1) === 807941 && D.EDC.sd.at(-1) === 12371);
  // The chronology's own columns agree with each other below the firn: age = integral of dz / (acc * tf).
  let integral = 0;
  for (let i = 1; i < depth.length; i++) {
    if (depth[i - 1] < 150) continue;
    integral += (depth[i] - depth[i - 1]) / (((acc[i] * tf[i]) + (acc[i - 1] * tf[i - 1])) / 2);
  }
  const span150 = age.at(-1) - scanAge(depth, age, depth.find((z) => z >= 150));
  check('below 150 m, the ages equal the integral of 1/(accumulation x thinning) to within 0.5%',
    Math.abs(integral / span150 - 1) < 0.005, `${fmt(integral)} vs ${fmt(span150)} years`);
  check('EDC δD: 5,784 measurements, depths increasing, every age inside the chronology',
    D.EDC_DD.depth.length === 5784 && D.EDC_DD.depth.every((z, i) => !i || z >= D.EDC_DD.depth[i - 1]) &&
    D.EDC_DD.age.every((t) => t >= age[0] - 1 && t <= age.at(-1)));
  let worstDD = 0;
  for (let i = 0; i < D.EDC_DD.depth.length; i += 7) worstDD = Math.max(worstDD, Math.abs(scanAge(depth, age, D.EDC_DD.depth[i]) - D.EDC_DD.age[i]));
  check('the δD file\'s ages are the chronology read at each depth (every 7th row, within 60 years)', worstDD < 60, `worst ${fmt(worstDD)} years`);
  check('NGRIP: dated to 3,082 m and 119,760 years BP', D.NGRIP.depth.at(-1) === 3082 && D.NGRIP.age.at(-1) === 119760);

  // --- the engine against independent code ---
  let worstI = 0;
  for (let k = 0; k <= 400; k++) { const z = (k / 400) * 3192.75; worstI = Math.max(worstI, Math.abs(E.ageAt(c, z) - scanAge(depth, age, z))); }
  check('ageAt equals a linear scan at 401 depths', worstI < 1e-6, `worst ${worstI.toExponential(1)} years`);
  const zHalf = E.depthForTimeFraction(c, 0.5), zHalfB = scanDepth(depth, age, age[0] + 0.5 * (age.at(-1) - age[0]));
  check('the depth that halves the dated time, two ways, agrees to a centimetre', near(zHalf, zHalfB, 0.01), `${zHalf.toFixed(3)} vs ${zHalfB.toFixed(3)} m`);
  const cc = E.cut(c, 1234.5);
  check('cut(): the part above and the part below add up to the whole dated span', near(cc.above + cc.below, age.at(-1) - age[0], 1e-6));
  check('yearsIn() over a metre at 3,000 m equals the scan difference', near(E.yearsIn(c, 3000, 1), scanAge(depth, age, 3000.5) - scanAge(depth, age, 2999.5), 1e-6));
  let worstS = 0;
  for (const [s, w] of [[0.08, 0.05], [0.08, 0.2], [0.3, 1], [0.03, 0.03], [0.5, 4]]) worstS = Math.max(worstS, Math.abs(E.survives(s, w) - convolveSine(s, w)));
  check('the diffusion damping formula matches a numerical convolution (5 cases)', worstS < 1e-6, `worst ${worstS.toExponential(1)}`);
  const P = E.shortestPeriodKept(0.1, 0.002, 0.5);
  check('shortestPeriodKept returns the period whose amplitude is exactly one half', near(E.cycleSurvives(0.1, 0.002, P), 0.5, 1e-12));
  check('Nye\'s closed form equals numerical integration (z = 3,000 of 3,273 m, a = 0.03 m/yr), to 0.01%',
    near(E.nyeAge(3000, 3273, 0.03) / nyeNumeric(3000, 3273, 0.03), 1, 1e-4));

  // --- the headline figures, recomputed here without the engine ---
  const bottom = depth.at(-1), span = age.at(-1) - age[0];
  const halfBelow = bottom - zHalfB;
  const halfLenAge = scanAge(depth, age, bottom / 2);
  const tenthBelow = bottom - scanDepth(depth, age, age[0] + 0.9 * span);
  const b100 = age.at(-1) - scanAge(depth, age, bottom - 100);
  const t100 = scanAge(depth, age, 100) - age[0];
  const H = {
    halfTimeDepth: fmt(zHalfB), halfTimeBelow: fmt(halfBelow), halfTimeBelowPct: fmt((100 * halfBelow) / bottom),
    halfLengthAge: fmt(Math.round(halfLenAge / 100) * 100), halfLengthPct: fmt((100 * (halfLenAge - age[0])) / span),
    tenthTimeBelow: fmt(tenthBelow), bottom100: fmt(Math.round(b100 / 100) * 100), top100: fmt(Math.round(t100)),
    layerTop: fmt(acc[0] * tf[0] * 1000), layerBottom: fmt(acc.at(-1) * tf.at(-1) * 1000, 2),
    ngripBottom: fmt(D.NGRIP.acc.at(-1) * D.NGRIP.tf.at(-1) * 1000), oldest: fmt(Math.round(age.at(-1) / 100) * 100),
    bottom: fmt(bottom, 2), oldestSd: fmt(Math.round(D.EDC.sd.at(-1) / 100) * 100),
    ngripOldest: fmt(Math.round(D.NGRIP.age.at(-1) / 100) * 100), ngripDepth: fmt(D.NGRIP.depth.at(-1)),
    accMin: fmt(100 * Math.min(...acc), 1), accMax: fmt(100 * Math.max(...acc), 1),
  };
  // thinnest year, by a scan of the product columns
  let ti = 0; for (let i = 1; i < acc.length; i++) if (acc[i] * tf[i] < acc[ti] * tf[ti]) ti = i;
  H.thinnest = fmt(acc[ti] * tf[ti] * 1000, 2); H.thinnestDepth = fmt(depth[ti]);
  H.maxPerMetre = fmt(Math.round(1 / (acc[ti] * tf[ti]) / 10) * 10);
  // Nye, by numerical integration, H = 3,275 m, with today's snowfall and the time-weighted mean
  let num = 0, den = 0; for (let i = 1; i < age.length; i++) { num += acc[i] * (age[i] - age[i - 1]); den += age[i] - age[i - 1]; }
  H.nyePresent = fmt(Math.round(nyeNumeric(bottom, 3275, acc[0]) / 100) * 100);
  H.nyeMean = fmt(Math.round(nyeNumeric(bottom, 3275, num / den) / 100) * 100);
  // Every figure the page prints in a data-f span must be the recomputed one.
  const spans = [...html.matchAll(/<span data-f="([a-zA-Z0-9]+)">([^<]*)<\/span>/g)];
  let seen = 0, wrong = [];
  for (const [, key, val] of spans) { if (key in H) { seen++; if (val !== H[key]) wrong.push(`${key}: page ${val}, recomputed ${H[key]}`); } }
  check('every recomputed figure the page prints matches (no-JS text included)', seen >= 20 && Object.keys(H).every((k) => spans.some((m) => m[1] === k)) && wrong.length === 0, wrong.concat(Object.keys(H).filter((k) => !spans.some((m) => m[1] === k)).map((k) => `${k} not printed`)).join('; ') || `${seen} spans`);
  // And the engine, the way the browser uses it, gives the same numbers.
  check('the engine agrees with the recomputation on the half-time depth and the bottom 100 m',
    fmt(E.depthForTimeFraction(c, 0.5)) === H.halfTimeDepth && fmt(Math.round(E.yearsBetween(c, bottom - 100, bottom) / 100) * 100) === H.bottom100);
  check('the thickness of one year falls from the top of EDC to its bottom by more than fifty-fold',
    (E.layerAt(c, 0) / E.layerAt(c, bottom)) > 50, `${(E.layerAt(c, 0) / E.layerAt(c, bottom)).toFixed(1)}x`);
  check('a year at the bottom of NGRIP is thinner than a year at the top of Dome C',
    E.layerAt(g, g.bottom) < E.layerAt(c, 0), `${(E.layerAt(g, g.bottom) * 1000).toFixed(1)} vs ${(E.layerAt(c, 0) * 1000).toFixed(1)} mm`);
  // Prose that states a result of the diffusion arithmetic.
  const z19 = 3170, lay19 = scanAge(depth, age, z19 + 0.5) - scanAge(depth, age, z19 - 0.5);
  const kept1000 = convolveSine(0.31, 1000 / lay19);
  check('prose: at 3,170 m with 31 cm, a thousand-year cycle keeps "less than a tenth" of its swing',
    kept1000 < 0.1 && html.includes('cycle keeps less than a tenth of its swing'), `${(100 * kept1000).toFixed(1)}%`);
  const lay100 = scanAge(depth, acc.map((a, i) => a * tf[i]), 100); // acc x tf at 100 m, by the scan
  // 7.23 cm of firn at close-off (Gkinis et al. 2021, rho_co = 804.3) is 7.23 x 804.3 / 917 cm of ice.
  const sIce = 0.0723 * 804.3 / 917;
  const presetSigma = +((html.match(/data-sigma="([0-9.]+)" data-at="100"/) || [])[1]) / 100;
  check('the firn preset on the page is 7.23 cm of firn converted to ice (6.3 cm)', near(presetSigma, sIce, 0.0005) && /about\s+6\.3 cm/.test(html), `${(100 * sIce).toFixed(2)} cm`);
  const kept10 = convolveSine(presetSigma, 10 * lay100);
  check('prose: at the firn preset (100 m) the one-year bar is gone (<0.5%) and a ten-year cycle keeps "about a third"',
    E.cycleSurvives(presetSigma, E.layerAt(c, 100), 1) < 0.005 && Math.abs(E.cycleSurvives(presetSigma, E.layerAt(c, 100), 10) - 1 / 3) < 0.04 &&
    Math.abs(kept10 - 1 / 3) < 0.04 && html.includes('a ten-year cycle keeps about a third'), `${(100 * kept10).toFixed(1)}%`);
  const ratio = sIce / (acc[0] * tf[0]);
  check('prose: the blur is "about twice" a year of snow (~3 cm of ice)', ratio > 1.8 && ratio < 2.4 && near(acc[0] * tf[0], 0.03, 0.002) && /blur is about twice/.test(html), ratio.toFixed(2));
  check('engine: ice thickness 3,275 m, as the page states', E.EDC_THICKNESS === 3275 && html.includes('about 3,275 m thick'));
  const metaDek = (html.match(/<meta name="description" content="([^"]*)"/) || [])[1];
  const visDek = (html.match(/<p class="dek">([^<]*)<\/p>/) || [])[1];
  check('the meta description is the visible dek, word for word', !!metaDek && metaDek === visDek);
  // The dek carries computed figures too; they must be the recomputed ones.
  const dekFigs = [H.oldest, H.bottom, H.halfLengthAge, H.halfTimeBelow];
  const dekOk = (t) => !!t && [`${H.oldest} years`, `${H.bottom} metres`, `${H.halfLengthAge} years`, `last ${H.halfTimeBelow} metres`].every((n) => t.includes(n));
  const ld = (html.match(/"description":"([^"]*)"/) || [])[1];
  let mdDek = null, mdPlain = null;
  const md = join(here, 'src/content/strata', `${slug}.md`);
  if (existsSync(md)) { const t = readFileSync(md, 'utf8'); mdDek = (t.match(/^dek: "(.*)"$/m) || [])[1]; mdPlain = (t.match(/^plain: "(.*)"$/m) || [])[1]; }
  check('the dek\'s figures (807,900 years, 3,192.75 metres, 121,300 years, last 468 metres) are the recomputed ones, in the meta, the visible dek and the structured data',
    dekOk(metaDek) && dekOk(visDek) && dekOk(ld), dekFigs.join(', '));
  if (mdDek !== null) check('inside the repository: the frontmatter dek matches, and the plain placard says 121,300 years and 468 metres',
    dekOk(mdDek) && mdPlain.includes(`${H.halfLengthAge} years`) && mdPlain.includes(`${H.halfTimeBelow} metres`));
  return { pass, fail };
}

// ---- PANGAEA, the source itself ----
async function againstPangaea() {
  let txt;
  try {
    const r = await fetch('https://doi.pangaea.de/10.1594/PANGAEA.824865?format=textfile', { signal: AbortSignal.timeout(30000) });
    if (!r.ok) throw new Error(`HTTP ${r.status}`);
    txt = await r.text();
  } catch (e) { console.log(`SKIPPED the page's data against PANGAEA (could not fetch: ${e.message})`); return null; }
  const lines = txt.split('\n'); const end = lines.findIndex((l) => l.startsWith('*/'));
  const rows = lines.slice(end + 2).filter((l) => l.trim()).map((l) => l.split('\t'));
  const E = D.EDC; let bad = 0;
  if (rows.length !== E.depth.length) bad++;
  rows.forEach((r, i) => {
    if (+r[0] !== E.depth[i]) bad++;
    if (Math.abs(+r[1] * 1000 - E.age[i]) > 1e-6) bad++;
    if (+r[5] !== E.acc[i] || +r[6] !== E.tf[i]) bad++;
  });
  const ok = bad === 0;
  console.log(`${ok ? 'ok  ' : 'FAIL'} the page's EDC chronology equals PANGAEA's, row by row (${rows.length} rows${ok ? '' : `, ${bad} differences`})`);
  return ok;
}

const E = await import(pathToFileURL(join(dir, 'engine.mjs')).href);
const { pass, fail } = await suite(E);
const pg = await againstPangaea();
console.log(`\n${pass + (pg ? 1 : 0)} passed, ${fail + (pg === false ? 1 : 0)} failed${pg === null ? ', 1 skipped' : ''}`);
let bad = fail > 0 || pg === false;

if (MUTATE) {
  const mutants = [
    ['diffusion with pi instead of pi squared', [/2 \* Math\.PI \*\* 2 \* sigma \*\* 2/, '2 * Math.PI * sigma ** 2']],
    ['interpolation reads the wrong neighbour', [/return ys\[lo\] \+ t \* \(ys\[hi\] - ys\[lo\]\);/, 'return ys[hi] + t * (ys[hi] - ys[lo]);']],
    ['one year taken as accumulation alone, no thinning', [/const layer = core\.acc\.map\(\(a, i\) => a \* core\.tf\[i\]\);/, 'const layer = core.acc.map((a) => a);']],
    ['time fraction measured from zero, not from the youngest ice', [/depthAt\(c, c\.youngest \+ f \* \(c\.oldest - c\.youngest\)\)/, 'depthAt(c, f * c.oldest)']],
    ['Nye with a base-10 logarithm', [/\(H \/ a\) \* Math\.log\(H \/ \(H - z\)\)/, '(H / a) * Math.log10(H / (H - z))']],
    ['the half-amplitude period without the square root', [/\(layer \* Math\.sqrt\(-Math\.log\(r\)\)\)/, '(layer * -Math.log(r))']],
    ['a metre of core measured as two', [/const a = Math\.max\(c\.top, z - len \/ 2\), b = Math\.min\(c\.bottom, z \+ len \/ 2\);/, 'const a = Math.max(c.top, z - len), b = Math.min(c.bottom, z + len);']],
  ];
  console.log('\n--mutate: each planted fault must turn at least one check red');
  const mdir = mkdtempSync(join(tmpdir(), 'icecore-mutants-'));
  let k = 0;
  for (const [name, [re, rep]] of mutants) {
    if (!re.test(engineSrc)) { console.log(`FAIL mutant "${name}": pattern not found in engine`); bad = true; continue; }
    const f = join(mdir, `engine-${k++}.mjs`);
    writeFileSync(f, engineSrc.replace(re, rep));
    const M = await import(pathToFileURL(f).href);
    const res = await suite(M, { quiet: true });
    const caught = res.fail > 0;
    console.log(`${caught ? 'ok  ' : 'FAIL'} mutant caught: ${name}  (${res.fail} checks red)`);
    if (!caught) bad = true;
  }
  rmSync(mdir, { recursive: true, force: true });
}
process.exit(bad ? 1 : 0);
