#!/usr/bin/env node
// verify-ninety-six-per-cent-at-one-frequency.mjs
//
//   node verify-ninety-six-per-cent-at-one-frequency.mjs
//
// The verifier for /strata/ninety-six-per-cent-at-one-frequency/ and
// research/the-earth-pulse-reanalysed/.
//
// This page says a published confidence value does not survive being computed against the
// search that produced it. That is a claim about someone else's work, so the standard of proof
// is higher than usual and the checks are ordered by how badly a failure would matter:
//
//   1. The 89 ages are the paper's 89 ages, and the count the paper states is met.
//   2. The reproduction happened BEFORE the correction. If the paper's own number cannot be
//      recovered, there is nothing of theirs to correct and the page has no standing.
//   3. The pre-registration predates the first p-value, checked against git rather than
//      asserted, and every prediction on the page is marked from the results.
//   4. The browser runs the analysed pipeline, not a lookalike. Checked by recomputing the
//      spectrum here from the shipped module and requiring it to match the Python run bin for
//      bin, over surrogates Python actually drew.
//   5. The correction has power: it finds a planted cycle, and it is calibrated on pure noise.
//   6. No figure on the page is baked into the markup. Every number-bearing span is empty in
//      the shipped file and filled at runtime.
//   7. The page does not overclaim. The fairness paragraphs are present and the words that
//      would turn a statistical result into a geological one are absent.
//
// It ends with mutations, because a verifier never observed failing has no demonstrated power
// to fail.

import { readFileSync, existsSync, writeFileSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import path from 'node:path';

const ROOT = path.resolve(import.meta.dirname);
const SLUG = 'ninety-six-per-cent-at-one-frequency';
const R = path.join(ROOT, 'research', 'the-earth-pulse-reanalysed');
const PUB = path.join(ROOT, 'public', 'strata', SLUG);

let pass = 0;
const fails = [];
const ok = (name, cond, detail = '') => {
  if (cond) { pass++; console.log(`  ok   ${name}${detail ? '  ' + detail : ''}`); }
  else { fails.push(name + (detail ? ': ' + detail : '')); console.error(`  FAIL ${name}${detail ? '  ' + detail : ''}`); }
};
const sha256 = (p) => createHash('sha256').update(readFileSync(p)).digest('hex');
const readJson = (p) => JSON.parse(readFileSync(p, 'utf8'));
const near = (a, b, tol) => Math.abs(a - b) <= tol;

const html = readFileSync(path.join(PUB, 'index.html'), 'utf8');
// Prose in the markup is hard-wrapped, so a phrase that reads as one sentence has newlines and
// indentation inside it. Matching against the raw file made a check for a sentence that IS
// present go red. Prose assertions run against this; structural ones against the raw file.
const prose = html.replace(/\s+/g, ' ');
const D = readJson(path.join(PUB, 'data.json'));
const AN = D.analysis;
const EV = readJson(path.join(R, 'data', 'events.json'));
const PRIMARY = AN.bands['10-60 (pre-registered primary)'];

console.log('\n1. the 89 ages are the paper\'s 89 ages');
ok('the paper PDF is present', existsSync(path.join(R, 'data', 'rampino2021.pdf')));
ok('the extraction recorded the PDF digest',
  /^[0-9a-f]{64}$/.test(EV.source.pdf_sha256 || ''));
ok('the shipped digest is the extraction\'s digest', D.source.pdf_sha256 === EV.source.pdf_sha256);
ok('the PDF on disk still hashes to it',
  sha256(path.join(R, 'data', 'rampino2021.pdf')) === EV.source.pdf_sha256);
ok('89 events, as the paper states', D.ages.length === 89 && EV.n_events === 89);
ok('the shipped ages are the extracted ages',
  JSON.stringify(D.ages) === JSON.stringify(EV.events.map((e) => e.age_ma)));
ok('every age lies inside the record the paper describes',
  D.ages.every((a) => a >= 0 && a <= 260), `${Math.min(...D.ages)} to ${Math.max(...D.ages)} Ma`);
ok('the ages are sorted, so the surrogate gaps are the record\'s gaps',
  D.ages.every((a, i) => i === 0 || a >= D.ages[i - 1]));
ok('the per-column disagreement with the paper\'s prose is carried, not hidden',
  Array.isArray(D.columns_differing) && D.columns_differing.length === 5,
  `${D.columns_differing?.length} columns`);
ok('and the page prints it', /five of the seven columns differ/i.test(html));

console.log('\n2. their result is reproduced before it is corrected');
ok('the peak lands on the published 27.5 Myr',
  near(PRIMARY.observed_peak_period_myr, 27.5, 0.001),
  `${PRIMARY.observed_peak_period_myr} Myr`);
ok('their own test returns something near their stated ~4%',
  PRIMARY.p_fixed_period > 0.02 && PRIMARY.p_fixed_period < 0.07,
  PRIMARY.p_fixed_period.toFixed(4));
ok('the reproducing setting is inside the grid the paper says it searched',
  AN.pipeline.tukey_myr >= 5 && AN.pipeline.tukey_myr <= 10
  && AN.pipeline.pad >= 0 && AN.pipeline.pad <= 40,
  `Tukey ${AN.pipeline.tukey_myr} Myr, ${AN.pipeline.pad} paddings`);
ok('the surrogate count is the paper\'s own 100,000',
  PRIMARY.n_surrogates === 100000);
ok('the declared grid is the paper\'s 6 x 41', AN.declared_grid.n_settings === 246);
ok('the grid moves the peak by more than 5 Myr',
  AN.declared_grid.max_peak_myr - AN.declared_grid.min_peak_myr > 5,
  `${AN.declared_grid.min_peak_myr.toFixed(2)} to ${AN.declared_grid.max_peak_myr.toFixed(2)}`);
ok('the corrected p is above 0.05 in the pre-registered band',
  PRIMARY.p_band_maximum > 0.05, PRIMARY.p_band_maximum.toFixed(4));
ok('every band is reported, not just the most favourable',
  Object.keys(AN.bands).length === 4);
// The period asked for and the period actually scored are not always the same, because only
// the bins the transform has exist. The main result needs no caveat and the 8.9 Myr one does,
// and both facts have to stay visible.
ok('the main result is scored at a period that IS on the grid',
  near(PRIMARY.scored_at_grid_period_myr, PRIMARY.scored_at_period_myr, 1e-9),
  `${PRIMARY.scored_at_grid_period_myr}`);
ok('the 8.9 Myr test records the grid period it actually scored',
  AN.secondary_8_9.scored_at_grid_period_myr
  && Math.abs(AN.secondary_8_9.scored_at_grid_period_myr - 8.9) < 0.05
  && AN.secondary_8_9.scored_at_grid_period_myr !== 8.9,
  `${AN.secondary_8_9.scored_at_grid_period_myr}`);
ok('and the page prints that distinction rather than rounding it away',
  /id="p89-grid"/.test(html) && /275 periods and 8\.9 is/.test(prose));
ok('the narrowest band is reported even though it is the least favourable',
  '15-40' in AN.bands, `p ${AN.bands['15-40']?.p_band_maximum}`);

console.log('\n3. the pre-registration predates the first p-value');
{
  const preg = path.join(R, 'PREREGISTRATION.md');
  ok('the pre-registration exists', existsSync(preg));
  const git = (args) => execFileSync('git', args, { cwd: ROOT, encoding: 'utf8' }).trim();
  // The claim is about ORDER, so it is checked against history rather than against the file's
  // own assertion that it came first. A file can say anything; a commit graph cannot.
  const pregCommit = git(['log', '--format=%H', '--diff-filter=A', '--', preg]).split('\n').pop();
  ok('the pre-registration was committed', /^[0-9a-f]{7,}$/.test(pregCommit || ''), pregCommit);
  let analyseCommit = '';
  try {
    analyseCommit = git(['log', '--format=%H', '--diff-filter=A', '--',
      path.join(R, 'analyse.py')]).split('\n').pop();
  } catch { /* not yet committed, which is itself fine: it cannot precede anything */ }
  if (analyseCommit) {
    const order = git(['rev-list', '--ancestry-path', `${pregCommit}..${analyseCommit}`]);
    ok('the analysis was committed after the pre-registration, in the same line of history',
      order.length > 0, `${pregCommit.slice(0, 9)} -> ${analyseCommit.slice(0, 9)}`);
  } else {
    ok('the analysis is not yet committed, so it cannot precede the pre-registration', true);
  }
  const preg_txt = readFileSync(preg, 'utf8');
  ok('the pre-registered primary band is the one reported as primary',
    /10 to 60/.test(preg_txt) && '10-60 (pre-registered primary)' in AN.bands);
  ok('kill criteria were written down', /## Kill criteria/.test(preg_txt));
  ok('the pre-registration names what will NOT be claimed',
    /## What will not be claimed/.test(preg_txt));
}
ok('six predictions were scored', AN.scorecard.length === 6);
ok('each scorecard entry carries the number that decided it',
  AN.scorecard.every((s) => s.outcome && /\d/.test(s.outcome)));
{
  // The marks must be DERIVED. Recompute the three that are checkable from other fields here,
  // by different code than bundle.py used, and require agreement.
  const s3 = AN.scorecard.find((s) => s.n === 3);
  ok('prediction 3 is marked from the number it is about',
    s3.held === (PRIMARY.p_band_maximum > 0.05));
  const s5 = AN.scorecard.find((s) => s.n === 5);
  ok('prediction 5 is marked from the numbers it is about',
    s5.held === (AN.distinct_rounded_ages < 65
      && AN.collapsed_to_distinct.p_band_maximum > PRIMARY.p_band_maximum));
  const s6 = AN.scorecard.find((s) => s.n === 6);
  const ps = Object.values(AN.bands).map((b) => b.p_band_maximum);
  ok('prediction 6 is marked from every band, not the primary one',
    s6.held === (ps.every((p) => p > 0.05) || ps.every((p) => p <= 0.05)));
}

console.log('\n4. the browser runs the analysed pipeline');
{
  const mod = await import(path.join(PUB, 'pulse.js'));
  const cc = path.join(R, 'out', 'crosscheck.json');
  ok('the cross-check fixture exists (run emit_crosscheck.py)', existsSync(cc));
  if (existsSync(cc)) {
    const F = readJson(cc);
    const { tukey_myr: W, pad: PAD, band_myr: BAND } = F.settings;
    const obs = mod.spectrumBins(mod.series(F.ages), W, PAD, BAND);
    ok('the browser finds the same number of bins in the band',
      obs.power.length === F.python.n_bins, `${obs.power.length} vs ${F.python.n_bins}`);
    let wp = 0, wq = 0;
    for (let i = 0; i < F.python.n_bins; i++) {
      wp = Math.max(wp, Math.abs(obs.period[i] - F.python.band_period[i]));
      wq = Math.max(wq, Math.abs(obs.power[i] - F.python.band_power[i])
        / Math.max(1e-12, F.python.band_power[i]));
    }
    ok('every bin sits at the same period', wp < 1e-9, wp.toExponential(2));
    ok('every bin carries the same power', wq < 1e-9, wq.toExponential(2));
    // The p-values are integer counts over surrogates numpy actually drew, shared with the
    // browser rather than merely drawn from the same distribution. So the tolerance is zero.
    let geAt = 0, geMax = 0;
    const obsMax = F.python.observed_max_power;
    for (const sa of F.surrogates) {
      const sp = mod.spectrumBins(mod.series(sa), W, PAD, BAND).power;
      if (sp[F.python.peak_index] > obsMax) geAt++;
      let mx = -Infinity; for (const v of sp) if (v > mx) mx = v;
      if (mx > obsMax) geMax++;
    }
    ok('p at the fixed period agrees exactly, over numpy\'s own surrogates',
      geAt / F.surrogates.length === F.python.p_fixed,
      `${geAt / F.surrogates.length} vs ${F.python.p_fixed}`);
    ok('p corrected for the search agrees exactly, over numpy\'s own surrogates',
      geMax / F.surrogates.length === F.python.p_corrected,
      `${geMax / F.surrogates.length} vs ${F.python.p_corrected}`);
  }

  // Independently of the fixture: the browser's own end-to-end run must land on the reference.
  const live = mod.runTests(D.ages, { widthMyr: 6, pad: 14, band: [10, 60], nSur: 20000,
                                      seed: 99001 });
  ok('the browser\'s own run reproduces the published peak',
    near(live.peakPeriod, 27.5, 1e-6), `${live.peakPeriod} Myr`);
  ok('the browser\'s own p at the fixed period lands on the reference',
    near(live.pFixed, PRIMARY.p_fixed_period, 0.02),
    `${live.pFixed} vs ${PRIMARY.p_fixed_period}`);
  ok('the browser\'s own corrected p lands on the reference',
    near(live.pCorrected, PRIMARY.p_band_maximum, 0.03),
    `${live.pCorrected} vs ${PRIMARY.p_band_maximum}`);
  ok('the two tests are computed from ONE set of surrogates, so they are comparable',
    live.surAt.length === live.surMax.length && live.surAt.length === live.nSur);
  // The whole argument is that the band maximum is not the value at a fixed period. If those
  // two ever coincided for every surrogate, the correction would be doing nothing.
  let differ = 0;
  for (let i = 0; i < live.nSur; i++) if (live.surMax[i] > live.surAt[i]) differ++;
  ok('for most surrogates the band maximum exceeds the value at 27.5 Myr, which is the point',
    differ / live.nSur > 0.8, `${(100 * differ / live.nSur).toFixed(0)}%`);

  // Round-half-to-even is load-bearing: it is what makes the browser agree with numpy.
  ok('the browser rounds halves to even, as Python does',
    mod.roundHalfEven(36.5) === 36 && mod.roundHalfEven(37.5) === 38
    && mod.roundHalfEven(-0.5) === 0 && mod.roundHalfEven(2.4) === 2
    && mod.roundHalfEven(2.6) === 3);
  ok('the rounding tie-break is reported rather than hidden',
    AN.tie_break && AN.tie_break.half_integer_ages.length === 4);
  ok('and it does not change the verdict',
    Object.values(AN.tie_break.variants).every((v) => v.p_corrected > 0.05),
    Object.values(AN.tie_break.variants).map((v) => v.p_corrected.toFixed(4)).join(' '));

  console.log('\n5. the correction has power, and is calibrated');
  ok('the power control is monotone enough to mean something',
    AN.power_control.find((d) => d.periodic_fraction === 0).p_corrected > 0.05
    && AN.power_control.find((d) => d.periodic_fraction === 0.75).p_corrected < 0.01,
    AN.power_control.map((d) => d.p_corrected.toFixed(4)).join(' '));
  ok('a fully planted cycle is found',
    AN.power_control.find((d) => d.periodic_fraction === 1).p_corrected < 0.01);
  ok('the null control is calibrated, not merely quiet',
    AN.null_control.frac_below_0_05 < 0.20 && AN.null_control.median_p > 0.2,
    `median ${AN.null_control.median_p}, ${AN.null_control.frac_below_0_05} below 0.05`);
  // Recomputed here, in the browser's own module rather than from the stored figure: a planted
  // cycle must come back significant or the corrected verdict on the real record is worthless.
  const rnd = mod.mulberry32(4242);
  const planted = mod.mixed(D.ages, 27.5, 0.9, rnd);
  const pr = mod.runTests(planted, { widthMyr: 6, pad: 14, band: [10, 60], nSur: 4000,
                                     seed: 4243 });
  ok('recomputed here: a 90% planted cycle comes back significant',
    pr.pCorrected < 0.01, `p ${pr.pCorrected}`);
  ok('and it is found at the period that was planted', near(pr.peakPeriod, 27.5, 0.6),
    `${pr.peakPeriod.toFixed(2)} Myr`);
}

console.log('\n6. no figure is baked into the markup');
{
  // Every span the page fills at runtime must ship EMPTY, so a stale number cannot survive an
  // edit to the analysis. Checked by id against the ids page.js actually writes to.
  const js = readFileSync(path.join(PUB, 'page.js'), 'utf8');
  const filled = [...js.matchAll(/\$\("([a-z0-9-]+)"\)\.(?:textContent|innerHTML)\s*=/g)]
    .map((m) => m[1]);
  ok('page.js fills a meaningful number of spans', filled.length >= 15, String(filled.length));

  // Two kinds of runtime-filled element are legitimately not empty in the shipped file, and a
  // check that bans both is broader than the claim it is defending. It is worth naming them
  // rather than loosening the rule, because the rule is what stops a stale figure surviving an
  // edit to the analysis.
  //   MIRRORS echo a control's own starting value, so they must ship showing exactly that.
  //   PROSE panels carry standing explanation that the run replaces; a figure inside one would
  //   be a claim, so those are checked for a bare p-value instead.
  const MIRRORS = { 'w-val': 'w', 'pad-val': 'pad', 'frac-val': 'frac' };
  const PROSE = new Set(['power-verdict', 'spec-verdict', 'test-verdict', 'grid-caption',
    'events-key', 'grid-key', 'hist-key', 'peak-out', 'p-fixed', 'p-corr']);
  const baked = [];
  for (const id of new Set(filled)) {
    if (id in MIRRORS || PROSE.has(id)) continue;
    const m = html.match(new RegExp(`id="${id}"[^>]*>([^<]*)<`));
    if (m && /\d/.test(m[1])) baked.push(`${id}="${m[1].trim()}"`);
  }
  ok('no runtime-filled span ships with a figure in it', baked.length === 0, baked.join(' '));

  const wrong = [];
  for (const [id, input] of Object.entries(MIRRORS)) {
    const shown = html.match(new RegExp(`id="${id}"[^>]*>([^<]*)<`))?.[1]?.trim();
    const val = html.match(new RegExp(`id="${input}"[^>]*?value="([^"]*)"`))?.[1];
    if (shown !== val) wrong.push(`${id} shows ${shown}, ${input} starts at ${val}`);
  }
  ok('each control mirror ships showing its control\'s actual starting value',
    wrong.length === 0, wrong.join('; '));

  const claimy = [];
  for (const id of PROSE) {
    const m = html.match(new RegExp(`id="${id}"[^>]*>([\\s\\S]*?)</`));
    if (m && /\bp\s*=?\s*0\.\d/.test(m[1])) claimy.push(id);
  }
  ok('no standing explanatory panel ships with a p-value in it',
    claimy.length === 0, claimy.join(' '));

  // The stored reference figures the prose quotes must come from data.json, not be typed in,
  // which is exactly what these ids are for.
  for (const id of ['ref-fixed', 'ref-corr', 'ref-corr-pct', 'd-min', 'd-max', 'p89',
                    'distinct', 'collapsed', 'null-med', 'null-frac', 'tiebreak']) {
    ok(`${id} is filled at runtime, not typed`, js.includes(`$("${id}")`)
      && !/\d/.test(html.match(new RegExp(`id="${id}"[^>]*>([^<]*)<`))?.[1] ?? ''));
  }
  ok('the page loads its numbers from data.json rather than inlining them',
    /fetch\("\.\/data\.json"\)/.test(js));
  ok('data.json holds no NaN or Infinity',
    !/\b(NaN|Infinity|-Infinity)\b/.test(readFileSync(path.join(PUB, 'data.json'), 'utf8')));
}

console.log('\n7. the page does not overclaim');
{
  const fair = [
    [/not a claim that the events are randomly scattered/i, 'clustering is not disputed'],
    [/not a claim that there is no 27\.5 Myr cycle/i, 'absence of evidence is not evidence of absence'],
    [/What is refuted is one number/i, 'the scope of the refutation is stated'],
    [/not our idea/i, 'the correction is not claimed as original'],
    [/authors disclosed the search/i, 'the authors are credited for disclosing the search'],
  ];
  for (const [re, what] of fair) ok(`the page says: ${what}`, re.test(prose));
  ok('Vaughan, Bailey and Smith are cited for the prior argument',
    /Vaughan/.test(prose) && /10\.1029\/2011PA002195/.test(html));
  ok('the paper being re-examined is cited with its DOI',
    /10\.1016\/j\.gsf\.2021\.101245/.test(html));
  ok('the paper is described as open access, which it is',
    /Open access/i.test(prose));

  // Words that would turn a statistical result into a geological one.
  //
  // The first version of this check banned the phrase "there is no cycle" outright and went red
  // on the page's own disclaimer, which is the sentence "This is not a claim that there is no
  // 27.5 Myr cycle." A check broader than the claim it defends is worse than no check, because
  // the obvious way to make it pass is to delete the disclaimer. So the list holds only terms
  // that cannot be rescued by their context, and the disclaimer is asserted PRESENT above.
  const overclaim = /\b(debunk\w*|disprov\w*|hoax|fraudulent|pseudoscien\w*|junk science)\b/i;
  const m = prose.match(overclaim);
  ok('the page makes no geological claim it has not earned', !m, m ? m[0] : '');
  ok('the surrogate construction is endorsed, not attacked',
    /exactly the right null/i.test(prose) && /uses it unchanged/i.test(prose));
  ok('and the page says outright that the objection is not to the surrogates',
    /objection is not to the surrogates/i.test(prose));
  ok('the Fig. 2 caption discrepancy is reported neutrally',
    /editing slip/i.test(prose) && !/misleading|deliberate/i.test(prose));
  ok('the dek names the size of the search rather than only the verdict',
    /246 combinations/.test(prose));
}

console.log('\n8. mutations: the checks above must be able to go red');
{
  // Built by regex against whatever the markup currently is, not against a literal that goes
  // stale the moment the page is edited. A mutation that fails to mutate proves nothing, so
  // each one asserts that it actually changed something before asserting what it catches.
  const mutated = html.replace(/(id="p89"[^>]*>)([^<]*)</, '$1' + '0.9999' + '<');
  ok('the mutation actually changed the page', mutated !== html);
  const m = mutated.match(/id="p89"[^>]*>([^<]*)</);
  ok('a figure typed into a runtime-filled span would be caught', /\d/.test(m[1]));
}
{
  const stripped = html.replace(/not a claim that there is no 27\.5 Myr cycle/i, 'XX');
  ok('removing a fairness paragraph actually changes the page', stripped !== html);
  ok('and it would be caught', !/not a claim that there is no 27\.5 Myr cycle/i.test(stripped));
}
{
  const p = path.join(PUB, 'data.json');
  const orig = readFileSync(p);
  try {
    const d = JSON.parse(orig);
    d.analysis.bands['10-60 (pre-registered primary)'].p_band_maximum = 0.001;
    writeFileSync(p, JSON.stringify(d));
    const re = readJson(p);
    ok('mutating the corrected p breaks the assertion that it exceeds 0.05',
      !(re.analysis.bands['10-60 (pre-registered primary)'].p_band_maximum > 0.05));
  } finally { writeFileSync(p, orig); }
  ok('data.json restored', sha256(p) === createHash('sha256').update(orig).digest('hex'));
}
{
  const p = path.join(R, 'out', 'crosscheck.json');
  if (existsSync(p)) {
    const orig = readFileSync(p);
    try {
      const F = JSON.parse(orig);
      F.python.band_power[3] *= 1.05;
      writeFileSync(p, JSON.stringify(F));
      const mod = await import(path.join(PUB, 'pulse.js') + '?mut');
      const re = readJson(p);
      const obs = mod.spectrumBins(mod.series(re.ages), re.settings.tukey_myr,
        re.settings.pad, re.settings.band_myr);
      const rel = Math.abs(obs.power[3] - re.python.band_power[3]) / re.python.band_power[3];
      ok('a 5% change in one Python bin breaks the bin-for-bin agreement', rel > 1e-9,
        rel.toExponential(2));
    } finally { writeFileSync(p, orig); }
    ok('crosscheck.json restored', sha256(p) === createHash('sha256').update(orig).digest('hex'));
  }
}

console.log(`\n${pass} checks passed, ${fails.length} failed`);
if (fails.length) { for (const f of fails) console.error('  - ' + f); process.exit(1); }
