#!/usr/bin/env node
// verify-wrong-the-same-way-every-day.mjs
//
// Every load-bearing number on /strata/wrong-the-same-way-every-day/ is re-derived
// here from the constants in compute.mjs and asserted against either (a) the value
// declared in facts.json (which carries a citation in SOURCES.md), or (b) the value
// asserted directly in the shipped page HTML (extracted here so a copy-edit that
// silently changes a number fails this verifier).
//
// The page's argument, at one line: a chronometer's LEVEL of error is a red
// herring; its RATE STABILITY is what wins the prize. This verifier turns every
// piece of that argument into an assertion.

import {
  SECONDS_PER_SOLAR_DAY,
  SECONDS_PER_DEG_LON,
  SECONDS_PER_ARC_MIN_LON,
  METERS_PER_NM,
  cosLat,
  timeErrorToLongitudeArcMin,
  timeErrorToLandfallNM,
  landfallNMToTimeError,
  requiredRateStabilitySecondsPerDay,
  residualRateSecondsPerDay,
  PRIZE_TABLE_EQUATOR,
  TYPICAL_PASSAGE_DAYS,
} from './research/wrong-the-same-way-every-day/compute.mjs';
import { readFileSync } from 'node:fs';

const facts = JSON.parse(readFileSync('./research/wrong-the-same-way-every-day/facts.json', 'utf8'));

let passed = 0, failed = 0;
const failures = [];
function ok(name, cond, extra = '') {
  if (cond) { passed++; console.log('  ok ' + name + (extra ? '  ' + extra : '')); }
  else { failed++; failures.push(name); console.log('FAIL ' + name + (extra ? '  ' + extra : '')); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;

//---------------------------------------------------------------------------
console.log('\n[1] The definitional arithmetic — Earth rotation to Greenwich time.\n');
//---------------------------------------------------------------------------

ok('86400 s per solar day', SECONDS_PER_SOLAR_DAY === 86400);
ok('360 degrees per rotation', SECONDS_PER_SOLAR_DAY / 240 === 360);
ok('1 degree of longitude = 240 s of time',
   SECONDS_PER_DEG_LON === 240 && 86400 / 360 === 240);
ok('1 arc-minute of longitude = 4 s of time',
   SECONDS_PER_ARC_MIN_LON === 4 && SECONDS_PER_DEG_LON / 60 === 4);
ok('nautical mile = 1852 m (SI-adopted 1929)', METERS_PER_NM === 1852);
ok('cos(0°) = 1',            near(cosLat(0), 1, 1e-15));
ok('cos(60°) = 0.5',         near(cosLat(60), 0.5, 1e-15));
ok('cos(90°) ≈ 0',           near(cosLat(90), 0, 1e-15));

//---------------------------------------------------------------------------
console.log('\n[2] The 1714 Longitude Act — three tiers, three deadlines in time.\n');
//---------------------------------------------------------------------------

for (const tier of facts.act.tiers) {
  const derivedTimeSec = tier.distanceNM * SECONDS_PER_ARC_MIN_LON;
  const eqEntry = PRIZE_TABLE_EQUATOR.find(t => t.prizeGBP === tier.prizeGBP);
  ok(`£${tier.prizeGBP} equator time budget = ${derivedTimeSec} s`,
     eqEntry.timeSeconds === derivedTimeSec);
  const oneDegRatio = tier.distanceNM / 60;
  ok(`£${tier.prizeGBP} = ${tier.fractionOfDegree.toFixed(4)} of a degree`,
     near(oneDegRatio, tier.fractionOfDegree, 1e-9));
}

ok('typical West-Indies passage 42 days', TYPICAL_PASSAGE_DAYS === 42);

// Required-rate-stability table at the equator over the typical passage.
const eqRates42 = PRIZE_TABLE_EQUATOR.map(t => ({
  prize: t.prizeGBP,
  rate: requiredRateStabilitySecondsPerDay({ distanceNM: t.distanceNM, latDeg: 0, days: 42 }),
}));
ok('£20,000 at equator over 42 d ≈ 2.857 s/day', near(eqRates42[0].rate, 2.857, 0.002));
ok('£15,000 at equator over 42 d ≈ 3.810 s/day', near(eqRates42[1].rate, 3.810, 0.002));
ok('£10,000 at equator over 42 d ≈ 5.714 s/day', near(eqRates42[2].rate, 5.714, 0.002));

//---------------------------------------------------------------------------
console.log('\n[3] Trial 1 — Kingston, Jamaica, 1761–62.\n');
//---------------------------------------------------------------------------

const J = facts.jamaica1761;

// Duration reconstruction.
const durDays = J.measuredLegDays + J.measuredLegHours / 24;
ok('81 d 5 h = 81.20833… days', near(durDays, J.measuredLegDecimalDays, 1e-9));

// Going rate.
ok('going rate 24/9 s/day = 2.667 s/day', near(24 / 9, J.goingRateSecondsPerDayLoss, 1e-12));

// Residual → arc-minute → NM chain, at Kingston's latitude.
const kArc = timeErrorToLongitudeArcMin(J.residualErrorAtKingstonSeconds);
ok('5 s residual = 1.25 arc-min of longitude', near(kArc, 1.25, 1e-9));
ok('and the facts.json literal 1.25 arc-min matches',
   near(J.residualErrorLongitudeArcMinutes, 1.25, 1e-9));

const kNM = timeErrorToLandfallNM(J.residualErrorAtKingstonSeconds, J.kingstonLatitudeDeg);
// Wikipedia equates 1.25' of longitude with "approximately one nautical mile"
// (it does not apply cos-latitude). The honest east-west distance at Kingston's
// 18°N is 1.25·cos(18°) = 1.19 nm, which likewise rounds to ~1 nm. We assert the
// cos-scaled value sits between the two readings and rounds to 1.
ok(`5 s at 17.97°N ≈ ${kNM.toFixed(3)} nm (rounds to ≈ 1 nm, per Wikipedia)`,
   kNM > 1.0 && kNM < 1.25 && Math.round(kNM) === 1);

// H4's residual rate — the crown-jewel number.
const jRate = residualRateSecondsPerDay(J.residualErrorAtKingstonSeconds, durDays);
ok(`H4 Jamaica rate residual = ${jRate.toFixed(4)} s/day`,
   near(jRate, 0.0616, 5e-4));

// Compare to £20,000 threshold at Kingston over the actual voyage.
const jThreshTime = landfallNMToTimeError(30, J.kingstonLatitudeDeg);
const jThreshRate = requiredRateStabilitySecondsPerDay({
  distanceNM: 30, latDeg: J.kingstonLatitudeDeg, days: durDays,
});
ok(`£20 000 at Kingston = ${jThreshTime.toFixed(2)} s of time (≈ 126.15 s)`,
   near(jThreshTime, 126.15, 0.05));
ok(`£20 000 rate budget over 81.2 d ≈ 1.553 s/day`, near(jThreshRate, 1.553, 0.003));

// The moat.
const jMoat = jThreshRate / jRate;
ok(`H4 beat the £20 000 rate budget by ≈ ${jMoat.toFixed(1)}× (target: 25×)`,
   near(jMoat, 25, 3));

//---------------------------------------------------------------------------
console.log('\n[4] Trial 2 — Bridgetown, Barbados, 1764.\n');
//---------------------------------------------------------------------------

const B = facts.barbados1764;
const bNM = timeErrorToLandfallNM(B.residualErrorAtBridgetownSeconds, B.bridgetownLatitudeDeg);
ok(`39 s at 13.1°N ≈ ${bNM.toFixed(3)} nm (< 10, per Wikipedia)`,
   near(bNM, 9.5, 0.05));
ok('facts.json residual NM = 9.5', near(B.residualErrorNM, 9.5, 0.05));

// Barbados outbound days.
const bDaysFromDates =
  (Date.parse(B.arrivalDate) - Date.parse(B.departureDate)) / (86400 * 1000);
ok(`outbound 28 Mar → 13 May 1764 = ${bDaysFromDates} d`,
   bDaysFromDates === B.outboundDays);

// Rate stability across the outbound leg.
const bRate = residualRateSecondsPerDay(B.residualErrorAtBridgetownSeconds, B.outboundDays);
ok(`H4 Barbados rate residual ≈ ${bRate.toFixed(3)} s/day (46-day leg)`,
   near(bRate, 0.848, 0.005));

// £20 000 budget at Bridgetown over that leg.
const bThreshRate = requiredRateStabilitySecondsPerDay({
  distanceNM: 30, latDeg: B.bridgetownLatitudeDeg, days: B.outboundDays,
});
ok(`£20 000 rate budget at Bridgetown over 46 d ≈ 2.679 s/day`,
   near(bThreshRate, 2.679, 0.003));
const bMoat = bThreshRate / bRate;
ok(`H4 beat the Bridgetown rate budget by ≈ ${bMoat.toFixed(1)}×`,
   near(bMoat, 3.16, 0.05));

//---------------------------------------------------------------------------
console.log('\n[5] Lunar distance — the alternative and its ceiling.\n');
//---------------------------------------------------------------------------

const L = facts.lunarDistance;
// 1 arc-minute of measured lunar distance = ~2 min = 120 s of Greenwich time.
const lTime = (1 / L.moonAngularMotionArcMinPerHour) * 3600; // seconds of time per arcmin of lunar-distance error
ok(`1 arc-min of lunar distance ≈ ${lTime} s of time`, lTime === 120);
// That maps to a longitude arc of 30 arc-minutes (via /4).
ok('1 arc-min → 30 arc-min of longitude', 120 / SECONDS_PER_ARC_MIN_LON === 30);
// Which is 30 NM at the equator, or 15 NM if the observation is half an arc-min:
const lHalfArcMin = 0.5 * 30; // 15 NM at the equator
ok(`half an arc-min → 15 nm at equator, matching Wikipedia's stated ceiling`,
   lHalfArcMin === L.bestCaseErrorNMEquator);
ok('Nautical Almanac lunar-distance tables 1767–1906',
   L.publishedNauticalAlmanacFrom === 1767 && L.publishedNauticalAlmanacTo === 1906);
const lYears = L.publishedNauticalAlmanacTo - L.publishedNauticalAlmanacFrom;
ok(`the method ran ${lYears} years in the Almanac (≥ 139)`, lYears >= 139);

//---------------------------------------------------------------------------
console.log('\n[6] Cross-check — every load-bearing number on the shipped page.\n');
//---------------------------------------------------------------------------

// This section scans the shipped HTML for the numbers we claim there, and
// asserts each. If a copy-edit ever silently changes a printed number, this
// section fails. Numbers are matched loosely on formatting.

const html = readFileSync('./public/strata/wrong-the-same-way-every-day/index.html', 'utf8');
function has(pattern, name) {
  const re = pattern instanceof RegExp ? pattern : new RegExp(pattern);
  ok(name, re.test(html));
}

has('1714', 'the year 1714 is on the page');
has(/£\s*20[,\s]?000/, '£20,000 is on the page');
has(/£\s*15[,\s]?000/, '£15,000 is on the page');
has(/£\s*10[,\s]?000/, '£10,000 is on the page');
has(/(240|four\s+minutes|4[\s ]*s)/i, '240 s / four minutes / 4 s appears somewhere');
has(/81\s*d(?:ays)?\s*(?:and\s*)?5\s*h(?:ours?)?/i, '81 d 5 h appears');
has(/(5\s*seconds?|five\s*seconds?)/i, 'five seconds appears somewhere');
has(/24\s*[\/⁄]\s*9|2\.66/, '24/9 (or 2.66…) appears');
has(/(39|thirty[-\s]?nine)\s*s(?:ec(?:onds?)?)?\b/i, '39 s appears (Barbados residual)');
has(/(9\.5|9½|nine[-\s]?and[-\s]?a[-\s]?half|less than 10)/i, '9.5 nm (or less-than-10 miles) appears');
has(/2\.\s*86|two[-\s]?point[-\s]?eight[-\s]?six|two seconds and change|2\.857/i,
    '2.86 s/day (£20 000 over 42 d at equator) appears');
has(/25[×x]|twenty[-\s]?five[-\s]?fold|twenty[-\s]?five times/i,
    'the ~25× moat over the £20 000 target appears');
has(/Kingston/, 'Kingston (Jamaica port) appears');
has(/(Bridgetown|Barbados)/, 'Bridgetown / Barbados appears');
has(/(Maskelyne)/, 'Maskelyne appears');
has(/(Harrison)/, 'Harrison appears');
has(/(lunar[-\s]distance|lunars?\b)/i, 'lunar distance appears');
has(/1767/, 'Nautical Almanac start year 1767 appears');
has(/1906/, 'Nautical Almanac end year 1906 appears');

//---------------------------------------------------------------------------
const total = passed + failed;
console.log(`\n${failed === 0 ? 'ALL GREEN' : 'FAIL'} — ${passed}/${total} passed`);
if (failures.length) {
  console.log('\nfailures:');
  for (const f of failures) console.log('  - ' + f);
  process.exit(1);
}
