#!/usr/bin/env node
// The check for /strata/the-day-is-not-86400/.
//
//     node research/the-day-is-not-86400/verify.mjs
//
// What it does, in order of how much it can catch:
//
//   1. LIFT. It reads the shipped page's data.js and engine.js, runs them in
//      node:vm, and compares the engine's answers with an independent
//      recomputation done here from the raw IERS text files in data/. If the page
//      and this file ever disagree, this goes red.
//   2. GROUND TRUTH. It checks the ported IERS Conventions routines against the
//      test vectors printed in the headers of the Fortran sources themselves.
//   3. BYTES. It checks that the series the page ships is the series the IERS
//      published, value for value.
//   4. QUOTES. It checks that the standard's text quoted on the page matches the
//      text extracted from the committed ITU PDF.
//   5. PROSE. It checks the numbers written into the page's own static prose and
//      meta description against what the computation returns.

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

import { readC04, readLeapSeconds, leapStepsSince1972, mjdToDate, dateToMjd } from './lib/eop.mjs';
import { simulate, scoreAgainst } from './lib/leapsim.mjs';
import { checkAgainstIERS, tidalLodMs, rgZont2, mjdToT, TERM_COUNT } from './lib/zonaltide.mjs';
import { zonalTideTables, fundargPolynomials } from './lib/fortran.mjs';

const HERE = dirname(fileURLToPath(import.meta.url));
const PAGE = join(HERE, '..', '..', 'public', 'strata', 'the-day-is-not-86400');

let pass = 0, fail = 0;
function ok(cond, msg, detail) {
  if (cond) { pass++; console.log(`  ok   ${msg}`); }
  else { fail++; console.log(`  FAIL ${msg}${detail ? `\n         ${detail}` : ''}`); }
}
function near(got, want, tol, msg) {
  ok(Math.abs(got - want) <= tol, msg, `got ${got}, want ${want} +/- ${tol}`);
}
function head(t) { console.log(`\n${t}`); }

// ---------------------------------------------------------------- 2. ground truth

head('The ported IERS Conventions routines, against their own published test cases');
for (const c of checkAgainstIERS()) {
  const tol = c.name.startsWith('FUNDARG') ? 1e-10 : Math.max(Math.abs(c.want) * 1e-12, 1e-25);
  ok(c.absdiff <= tol, `${c.name} reproduces the published value (|diff| = ${c.absdiff.toExponential(3)})`);
}
ok(TERM_COUNT === 62, 'the zonal tide model carries all 62 terms of IERS Conventions (2010)');
{
  // The two routines' published test vectors are not mutually consistent at the
  // 1e-11 radian level. Ours matches RG_ZONT2's, which is the one that matters
  // because it is the composite. This pins that observation so it cannot rot.
  const t = 0.07995893223819302;
  const terms = zonalTideTables();
  const ref = [2.291187512612069099, 6.212931111003726414, 3.658025792050572989,
    4.554139562402433228, -0.5167379217231804489];
  let dlod = 0;
  for (const T of terms) {
    let arg = (T.n[0] * ref[0] + T.n[1] * ref[1] + T.n[2] * ref[2] + T.n[3] * ref[3] + T.n[4] * ref[4])
      % 6.283185307179586476925287;
    if (arg < 0) arg += 6.283185307179586476925287;
    dlod += T.lodCos * Math.cos(arg) + T.lodSin * Math.sin(arg);
  }
  const viaHeader = Math.abs(dlod * 1e-5 - 5.035331113978199288e-5);
  const viaOurs = Math.abs(rgZont2(t).dlod - 5.035331113978199288e-5);
  ok(viaOurs < viaHeader,
    'our arguments reproduce RG_ZONT2 better than FUNDARG.F\'s own printed vector does '
    + `(${viaOurs.toExponential(2)} vs ${viaHeader.toExponential(2)} s/day)`);
}

// ---------------------------------------------------------------- the raw data

head('The committed IERS files');
const c04 = readC04();
const leaps = leapStepsSince1972();
ok(c04.n > 23000, `C04 parses ${c04.n} consecutive daily values`);
ok(mjdToDate(c04.mjd[0]) === '1962-01-01', 'the series starts on 1962-01-01');
ok(leaps.length === 27, `27 leap seconds since 1972 (${leaps[0].label} to ${leaps.at(-1).label})`);
ok(readLeapSeconds().at(-1).taiUtc === 37, 'TAI-UTC stands at 37 s');
{
  const bulletin = readFileSync(join(HERE, 'data', 'bulletinc.dat'), 'utf8');
  ok(/NO leap second will be introduced/.test(bulletin),
    'Bulletin C confirms no leap second at the next opportunity');
  ok(/UTC-TAI = -37 s/.test(bulletin), 'Bulletin C confirms UTC-TAI = -37 s');
}

// ------------------------------------------------- 1. lift the page and compare

head('The shipped page, lifted and run');
const dataSrc = readFileSync(join(PAGE, 'data.js'), 'utf8');
const engineSrc = readFileSync(join(PAGE, 'engine.js'), 'utf8');
const html = readFileSync(join(PAGE, 'index.html'), 'utf8');
const ctx = vm.createContext({ console });
vm.runInContext(dataSrc.replace(/^window\./m, 'globalThis.'), ctx, { filename: 'data.js' });
vm.runInContext(engineSrc, ctx, { filename: 'engine.js' });
const E = ctx.AW86400, D = ctx.AW86400_DATA;
ok(!!E && !!D, 'data.js and engine.js execute in node:vm and expose their globals');

// 3. bytes
head('The series the page ships is the series the IERS published');
{
  let worstLod = 0, worstU = 0;
  for (let i = 0; i < c04.n; i++) {
    worstLod = Math.max(worstLod, Math.abs(D.lodTenthUs[i] * 1e-7 - c04.lod[i]));
    worstU = Math.max(worstU, Math.abs(D.ut1TenUs[i] * 1e-5 - c04.ut1utc[i]));
  }
  ok(D.n === c04.n, `the page carries all ${c04.n} days`);
  ok(D.mjd0 === c04.mjd[0], 'the page starts on the same day as the file');
  ok(worstLod < 6e-8, `length of day is carried losslessly (worst deviation ${worstLod.toExponential(2)} s)`);
  ok(worstU < 6e-6, `UT1-UTC is carried to better than 10 us (worst ${worstU.toExponential(2)} s)`);
  ok(D.leaps.length === leaps.length && D.leaps.every((l, i) => l.mjd === leaps[i].mjd),
    'the page carries the same 27 leap-second epochs as the IERS table');
  ok(D.tideTerms.length === 62, 'the page carries all 62 tidal terms');
  const terms = zonalTideTables();
  const same = terms.every((t, i) => {
    const p = D.tideTerms[i];
    return t.n.every((v, k) => v === p[k])
      && p[5] === t.dutSin && p[6] === t.dutCos && p[7] === t.lodCos && p[8] === t.lodSin;
  });
  ok(same, 'every tidal coefficient on the page equals the one lifted from RG_ZONT2.F');
  const poly = fundargPolynomials();
  ok(['L', 'LP', 'F', 'D', 'OM'].every((k) => poly[k].every((v, i) => v === D.fundarg[k][i])),
    'the five argument polynomials on the page equal those lifted from FUNDARG.F');
}

head('The page engine against an independent recomputation');
{
  // the tide model
  let worst = 0;
  for (let m = 41317; m < c04.mjd.at(-1); m += 37) {
    worst = Math.max(worst, Math.abs(E.zonalTide(D, m).dlod * 1000 - tidalLodMs(m)));
  }
  ok(worst < 1e-12, `the page's tide model matches lib/zonaltide.mjs everywhere (worst ${worst.toExponential(2)} ms)`);
  ok(Math.abs(E.zonalTide(D, 54465).dut - 7.983287678576557467e-2) < 1e-15,
    'the page reproduces the RG_ZONT2 test case for the effect on UT1');

  // the leap-second reconstruction, at both thresholds the page names
  for (const th of [0.9, 0.682]) {
    const mine = simulate(c04, { threshold: th });
    const theirs = E.simulate(D, th);
    const sMine = scoreAgainst(mine.steps, leaps);
    const sTheirs = E.score(D, theirs.steps);
    ok(mine.steps.length === theirs.steps.length && sMine.hits === sTheirs.hits
       && mine.steps.every((s, i) => s.mjd === theirs.steps[i].mjd),
      `at a tolerance of ${th} s the page and this file fire the same ${theirs.steps.length} steps `
      + `and score the same ${sTheirs.hits}/${sTheirs.total}`);
  }

  // the integration, on both eras the page reports
  for (const [iso, tol] of [['1972-01-01', 3], ['1998-01-01', 1]]) {
    const it = E.integrate(D, E.isoToMjd(iso));
    ok(Math.abs(it.finalResidual * 1000) < tol,
      `integrating from ${iso} lands within ${tol} ms of the published UT1-UTC `
      + `(${(it.finalResidual * 1000).toFixed(3)} ms, worst ${(it.worst * 1000).toFixed(3)} ms)`);
  }

  // the fast spectrum against the obvious one
  const i0 = E.isoToMjd('2000-01-01') - D.mjd0;
  const lod = E.lodSeconds(D), tide = E.tideSeries(D);
  const obs = [], res = [];
  for (let i = i0; i < D.n; i++) { obs.push(lod[i] * 1000); res.push((lod[i] - tide[i]) * 1000); }
  const probe = [13.661, 27.555, 60, 182.621, 365.26];
  const fast = E.spectrum(obs, probe), slow = E.direct(obs, probe);
  ok(probe.every((_, i) => Math.abs(fast[i] - slow[i]) < 1e-9),
    'the page\'s fast spectrum agrees with the plain double loop to 1e-9 ms');

  // and the physics claim the spectrum is there to make
  const PER = [];
  for (let k = 0; k < 9000; k++) PER.push(8 * Math.pow(50, k / 8999));
  const A = E.spectrum(obs, PER), B = E.spectrum(res, PER);
  const shown = [
    ['Mf', 13.661, 0.90], ['Mm', 27.555, 0.85],
  ];
  for (const [name, per, minRemoved] of shown) {
    const a = E.peakNear(PER, A, per, 0.02), b = E.peakNear(PER, B, per, 0.02);
    const removed = 1 - b.amp / a.amp;
    ok(Math.abs(a.period - per) < per * 0.005 && removed > minRemoved,
      `${name}: the measured peak sits at ${a.period.toFixed(3)} d against a predicted ${per} d, `
      + `and the a-priori model removes ${(100 * removed).toFixed(1)}% of it`);
  }
  for (const [name, per, maxRemoved] of [['Ssa', 182.621, 0.5], ['Sa', 365.26, 0.5]]) {
    const a = E.peakNear(PER, A, per, 0.02), b = E.peakNear(PER, B, per, 0.02);
    const removed = 1 - b.amp / a.amp;
    ok(removed < maxRemoved,
      `${name}: the model removes only ${(100 * removed).toFixed(1)}% of the solar line, `
      + 'as the page says, because the atmosphere owns that frequency');
  }
}

// ---------------------------------------------------------------- 4. the quotes

head('The standard, quoted verbatim');
{
  const rules = readFileSync(join(HERE, 'data', 'TF460-6-rules.txt'), 'utf8')
    .replace(/\s+/g, ' ');
  const quoted = [
    'The departure of UTC from UT1 should not exceed ± 0.9 s',
    'A positive or negative leap-second should be the last second of a UTC month, but first preference should be given to the end of December and June, and second preference to the end of March and September.',
    'a safeguard for the IERS against unpredictable changes in the rate of rotation of the Earth',
  ];
  for (const q of quoted) {
    ok(rules.includes(q), `the page's quotation appears verbatim in ITU-R TF.460-6: "${q.slice(0, 52)}…"`);
  }
  const pageText = html.replace(/&plusmn;/g, '±').replace(/&minus;/g, '−')
    .replace(/&nbsp;/g, ' ').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ');
  ok(pageText.includes('The departure of UTC from UT1 should not exceed ± 0.9 s'),
    'and that quotation is on the page');
  ok(pageText.includes('first preference should be given to the end of December and June'),
    'and so is the leap-second preference rule');
}

// ---------------------------------------------------------------- 5. the prose

head('The numbers written into the page\'s static prose');
{
  const bestScan = [];
  for (let t = 0.30; t <= 1.2001; t += 0.001) {
    const s = simulate(c04, { threshold: +t.toFixed(3) });
    const sc = scoreAgainst(s.steps, leaps);
    if (s.steps.length === leaps.length) bestScan.push({ t: +t.toFixed(3), hits: sc.hits });
  }
  const bestHits = Math.max(...bestScan.map((x) => x.hits));
  const band = bestScan.filter((x) => x.hits === bestHits).map((x) => x.t);
  const mid = (Math.min(...band) + Math.max(...band)) / 2;
  ok(bestHits === 23, `the best score really is ${bestHits} of 27`);
  near(mid, 0.682, 0.01, 'the best-fitting tolerance really is about 0.68 s');
  ok(/23 of them on the exact\s+announced day/.test(html) || /23 of them on the exact announced day/.test(html.replace(/\s+/g, ' ')),
    'the dek says 23 of 27, and 23 is what the computation gives');
  ok(html.replace(/\s+/g, ' ').includes('The tolerance that record implies is 0.68 s'),
    'the dek says 0.68 s, and 0.68 s is what the computation gives');

  const days = c04.n;
  ok(html.replace(/\s+/g, ' ').includes(`${days.toLocaleString('en-US')} daily measurements`),
    `the dek's day count (${days.toLocaleString('en-US')}) matches the file`);

  const yrs = (c04.mjd.at(-1) - leaps.at(-1).mjd) / 365.25;
  ok(yrs > 9 && yrs < 10 && /Nine and a half years of silence/.test(html),
    `the section heading matches the gap, which is ${yrs.toFixed(2)} years`);
  const gaps = [];
  for (let i = 1; i < leaps.length; i++) gaps.push((leaps[i].mjd - leaps[i - 1].mjd) / 365.25);
  ok(yrs > Math.max(...gaps),
    `and that gap really is the longest in UTC's history (previous record ${Math.max(...gaps).toFixed(2)} years)`);

  // the secular claim: the sign is wrong, and the eclipse figure is quoted right
  const xs = [], ys = [];
  for (let i = 0; i < c04.n; i++) { xs.push(i / 36525); ys.push(c04.lod[i] * 1000); }
  const mx = xs.reduce((a, b) => a + b) / xs.length, my = ys.reduce((a, b) => a + b) / ys.length;
  let a = 0, b = 0;
  for (let k = 0; k < xs.length; k++) { a += (xs[k] - mx) * (ys[k] - my); b += (xs[k] - mx) ** 2; }
  const perCentury = a / b;
  ok(perCentury < 0,
    `a straight line through the whole record gives ${perCentury.toFixed(2)} ms per century, `
    + 'the opposite sign to the millennial +1.78');
  ok(html.includes('+1.78 &plusmn; 0.03 ms per century') && html.includes('+2.3 ms per century'),
    'the page quotes Stephenson, Morrison and Hohenkerk\'s figures as +1.78 +/- 0.03 and +2.3 ms/century');

  // the negative-leap arithmetic
  const cur = c04.ut1utc.at(-1);
  const daysTo = dateToMjd('2029-12-31') - c04.mjd.at(-1);
  const req = (-(0.9 - cur) * 1000) / daysTo;
  const worstYear = (() => {
    const by = new Map();
    for (let i = 0; i < c04.n; i++) {
      if (!by.has(c04.year[i])) by.set(c04.year[i], []);
      by.get(c04.year[i]).push(c04.lod[i] * 1000);
    }
    let w = null;
    for (const [y, v] of by) {
      if (v.length < 300) continue;
      const m = v.reduce((p, q) => p + q, 0) / v.length;
      if (!w || m < w.m) w = { y, m };
    }
    return w;
  })();
  ok(req < worstYear.m,
    `a negative leap second by end-2029 needs a sustained ${req.toFixed(3)} ms/day, which is beyond `
    + `the most negative year on record (${worstYear.y}, ${worstYear.m.toFixed(3)} ms/day)`);
  ok(html.includes('will require a negative discontinuity by 2029'),
    'the page quotes Agnew\'s conclusion as published');
  ok(html.includes('13 to 15 October 2026'), 'the page states the 28th CGPM dates');
}

head(`${pass} passed, ${fail} failed`);
process.exit(fail === 0 ? 0 : 1);
