#!/usr/bin/env node
// verify.mjs — the checkable spine of "Fifty-Four Years to the Finish Line"
// (/strata/the-fifty-four-year-marathon/).
//
//   node research/the-fifty-four-year-marathon/verify.mjs
//
// Two jobs, like research/carrots-eyesight/verify.mjs:
//  (1) recompute EVERY number the page asserts, from scratch, and check it
//      against the cited record; print each PASS/FAIL; exit non-zero on any fail.
//  (2) read the shipped public/strata/.../index.html and assert it literally
//      carries the same figures and model constants, so the drawing, the model
//      and the numbers cannot silently disagree.
//
// SOURCES for the asserted numbers (see the page's Sources block):
//  - Shizo Kanakuri (Wikipedia): b. 20 Aug 1891, d. 13 Nov 1983; started the
//    14 Jul 1912 Stockholm marathon, DNF; SVT invitation; finished 20 Mar 1967;
//    the CALENDAR rendering "54 years, 8 months, 6 days, 5 hours, 32 minutes,
//    20.3 s"; Hakone Ekiden (1920); Antwerp 1920 (16th) and Paris 1924 (DNF).
//  - Guinness World Records: the record, published with two day-counts that
//    DISAGREE — the record page ("Longest time to complete a marathon") gives
//    "54 years, 249 days, …", while the 2019 feature gives "54 years 246 days …"
//    (three days short of the 20 Mar 1967 finish).
//  - 1912 Men's marathon (Wikipedia): ~32 C heat; 68 started, 36 finished (32 DNF).
//  - Francisco Lázaro (Wikipedia): b. 21 Jan 1888; collapsed ~30 km, core 41 C,
//    died next day; had waxed his skin, impairing sweating; first modern-Olympic
//    competition fatality.
//  - Physiology/handbook constants: latent heat of sweat ~2430 J/g; body specific
//    heat ~3500 J/(kg·K); Du Bois area ~1.8 m^2; sigma = 5.67e-8 W/(m^2 K^4).

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

let pass = 0, fail = 0;
const approx = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;
const ok = (name, cond, extra = '') => {
  if (cond) { pass++; console.log(`  ok    ${name}${extra ? '   ' + extra : ''}`); }
  else { fail++; console.error(`  FAIL  ${name}${extra ? '   ' + extra : ''}`); }
};

console.log('\nFIFTY-FOUR YEARS TO THE FINISH LINE — verifier\n');

// ── the two real dates (the page computes everything from exactly these) ─────
const DAY = 86400000;
const START  = Date.UTC(1912, 6, 14);   // 14 Jul 1912
const FINISH = Date.UTC(1967, 2, 20);   // 20 Mar 1967
const ANNIV  = Date.UTC(1966, 6, 14);   // 14 Jul 1966 (the 54th anniversary)
const iso = (ms) => new Date(ms).toISOString().slice(0, 10);

// ── 1. the span, in every unit the page offers ───────────────────────────────
console.log('— the span between 14 Jul 1912 and 20 Mar 1967 —');
const totalDays = Math.round((FINISH - START) / DAY);
const remDays   = Math.round((FINISH - ANNIV) / DAY);
ok('total span = 19,972 days', totalDays === 19972, `${totalDays}`);
ok('sub-year remainder (14 Jul 1966 → 20 Mar 1967) = 249 days', remDays === 249, `${remDays}`);
ok('total hours = 479,328', totalDays * 24 === 479328);
ok('total minutes = 28,759,680', totalDays * 1440 === 28759680);
ok('total seconds (date span) = 1,725,580,800', totalDays * 86400 === 1725580800);
// leap-day sanity: 54 years hold 13 Feb-29s between the two 14-Julys, so 54*365+13
ok('54 years = 54·365 + 13 leap days = 19,723 days', 54 * 365 + 13 === 19723);
ok('19,723 + 249 = 19,972 (whole span reconstructs)', 19723 + remDays === totalDays);

// ── 2. the calendar breakdown is exact; Guinness's two day-counts disagree ────
console.log('\n— the ceremonial figure, added back onto the start date —');
const calLands = iso(Date.UTC(1966, 6 + 8, 14 + 6));      // +8 months +6 days (Wikipedia's calendar form)
ok('Wikipedia\'s "8 mo 6 d" lands exactly on 1967-03-20 (the finish)', calLands === iso(FINISH), calLands);
const g246 = iso(ANNIV + 246 * DAY);   // Guinness 2019 feature
const g249 = iso(ANNIV + 249 * DAY);   // Guinness record page
ok('Guinness 2019-feature "246 days" lands on 1967-03-17 — three days short', g246 === '1967-03-17', g246);
ok('Guinness record-page "249 days" lands on 1967-03-20 (the finish)', g249 === iso(FINISH), g249);
ok('Guinness\'s own two day-counts (246-day feature vs 249-day record page) differ by 3 days',
   249 - 246 === 3 && g249 !== g246 && remDays === 249);

// ── 3. the theatrical precision ──────────────────────────────────────────────
console.log('\n— the 0.3-second tail —');
const ceremExtraSec = 5 * 3600 + 32 * 60 + 20.3;          // 5 h 32 m 20.3 s
const ceremTotalSec = totalDays * 86400 + ceremExtraSec;
ok('ceremonial extra = 5 h 32 m 20.3 s = 19,940.3 s', approx(ceremExtraSec, 19940.3, 1e-9), `${ceremExtraSec}`);
const partInBillions = (ceremTotalSec / 0.3) / 1e9;
ok('0.3 s is ~1 part in 5.8 billion of the span (page prints "5.8")',
   partInBillions.toFixed(1) === '5.8', `${partInBillions.toFixed(3)} bn`);

// ── 4. the whimsy unit ───────────────────────────────────────────────────────
console.log('\n— the "in marathons" unit —');
const marathons2h = (totalDays * 86400) / 7200;
ok('at 2 h each, ≈ 239,664 marathons fit in the span', marathons2h === 239664, `${marathons2h}`);

// ── 5. Kanakuri's ages (born 20 Aug 1891) ────────────────────────────────────
console.log('\n— ages, from birth date 20 Aug 1891 —');
const ageOn = (bY, bM, bD, ms) => {
  const d = new Date(ms); let a = d.getUTCFullYear() - bY;
  if (d.getUTCMonth() < bM || (d.getUTCMonth() === bM && d.getUTCDate() < bD)) a--;
  return a;
};
ok('age 20 at the 1912 start line', ageOn(1891, 7, 20, START) === 20);
ok('age 75 at the 1967 finish line', ageOn(1891, 7, 20, FINISH) === 75);
ok('age 92 at death (13 Nov 1983)', ageOn(1891, 7, 20, Date.UTC(1983, 10, 13)) === 92);

// ── 6. the 1912 heat toll ────────────────────────────────────────────────────
console.log('\n— the 1912 marathon heat toll —');
const STARTED = 68, FINISHED = 36, DNF = 32;
ok('68 started − 36 finished = 32 did not finish', STARTED - FINISHED === DNF);

// ── 7. the heat balance (the model the second instrument draws) ───────────────
console.log('\n— the runner heat balance (representative, but recomputed) —');
const L_SWEAT = 2430, SWEAT_LPH = 1.5;
const E_FULL = (SWEAT_LPH / 3600) * 1000 * L_SWEAT;
ok('latent heat 2430 J/g × 1.5 L/h ⇒ evaporative capacity = 1012.5 W', approx(E_FULL, 1012.5), `${E_FULL} W`);
const BODY_M = 65, BODY_C = 3500, BODY_CAP = BODY_M * BODY_C;
ok('body heat capacity = 65 kg × 3500 = 227,500 J/K', BODY_CAP === 227500);
ok('evaporation (~1 kW) is comparable to the ~1 kW metabolic heat load',
   E_FULL > 900 && E_FULL < 1100);

const AREA = 1.8, H_CONV = 12, EMIS = 0.95, SIGMA = 5.67e-8, T_SKIN = 35, S_MET = 1000;
const convW = (a) => H_CONV * AREA * (T_SKIN - a);
const radW  = (a) => { const ts = T_SKIN + 273.15, ta = a + 273.15;
  return EMIS * SIGMA * AREA * (ts ** 4 - ta ** 4); };
const balance = (wax, a) => {
  const E = (1 - wax) * E_FULL, C = convW(a), R = radW(a);
  const stored = Math.max(0, S_MET - (E + C + R));
  return { E, C, R, stored, rateHr: (stored / BODY_CAP) * 3600 };
};
// default (no wax, 32 C): cooling just covers metabolic heat → body holds
{
  const b = balance(0, 32);
  ok('at 32 C with sweat running, convection ≈ 64.8 W', approx(b.C, 64.8, 1e-6), `${b.C.toFixed(2)}`);
  ok('at 32 C, radiation ≈ 33.6 W', approx(b.R, 33.6, 0.1), `${b.R.toFixed(2)}`);
  ok('with evaporation free, net heat storage ≈ 0 (body holds steady)', b.stored === 0, `${b.stored.toFixed(1)} W`);
}
// fully waxed (32 C): evaporation gone → ~900 W pours into the body
{
  const b = balance(1, 32);
  ok('fully waxed at 32 C ⇒ ~900 W of unshed heat', approx(b.stored, 901.65, 1), `${b.stored.toFixed(0)} W`);
  ok('…driving core temperature up ~14 °C/hr in this bare model', approx(b.rateHr, 14.26, 0.1), `${b.rateHr.toFixed(1)} °C/hr`);
  ok('sealing evaporation flips storage from 0 to strongly positive', balance(0, 32).stored === 0 && b.stored > 500);
}
// the reversal: above skin temperature, convection and radiation change sign
{
  const b = balance(0, 38);   // air hotter than 35 C skin
  ok('above skin temp (38 C air), convection is negative — the air heats you', b.C < 0, `${b.C.toFixed(1)} W`);
  ok('above skin temp (38 C air), radiation is negative too', b.R < 0, `${b.R.toFixed(1)} W`);
}

// ── 8. cross-check: the shipped page carries these exact figures ─────────────
console.log('\n— the shipped page states the same figures —');
const here = path.dirname(fileURLToPath(import.meta.url));
const pagePath = path.resolve(here, '../../public/strata/the-fifty-four-year-marathon/index.html');
if (fs.existsSync(pagePath)) {
  const raw = fs.readFileSync(pagePath, 'utf8');
  const norm = raw.replace(/&nbsp;/g, ' ').replace(/&thinsp;/g, ' ');
  const has = (re, label) => ok(`page states ${label}`, re.test(norm));
  // dates & span
  has(/14 Jul 1912/, 'the 14 Jul 1912 start');
  has(/20 Mar 1967/, 'the 20 Mar 1967 finish');
  has(/54 years, 8 months, 6 days/, 'Wikipedia\'s calendar rendering "54 years, 8 months, 6 days"');
  has(/246 days/, 'Guinness\'s 2019-feature "246 days" rendering');
  has(/249 days/, 'Guinness\'s record-page "249 days" rendering');
  has(/17 March/, 'the 17 March mislanding of the 246-day feature figure');
  has(/1 part in/, 'the "1 part in … billion" precision line');
  has(/20\.3/, 'the theatrical 20.3-second tail');
  // the model constants live in the inline script (drawing ⇄ numbers)
  has(/Date\.UTC\(1912, 6, 14\)/, 'the START = Date.UTC(1912, 6, 14) anchor');
  has(/Date\.UTC\(1967, 2, 20\)/, 'the FINISH = Date.UTC(1967, 2, 20) anchor');
  has(/L_SWEAT = 2430/, 'the latent-heat constant 2430 J/g');
  has(/SWEAT_LPH = 1\.5/, 'the 1.5 L/h sweat rate');
  has(/S_MET = 1000/, 'the ~1 kW metabolic heat load');
  has(/BODY_M = 65, BODY_C = 3500/, 'body mass 65 kg and specific heat 3500 J/(kg·K)');
  has(/AREA = 1\.8, H_CONV = 12, EMIS = 0\.95, SIGMA = 5\.67e-8, T_SKIN = 35/, 'the area/convection/emissivity/sigma/skin constants');
  has(/7200/, 'the 2-hour-marathon divisor');
  // race & people
  has(/68/, 'the 68 starters');
  has(/36/, 'the 36 finishers');
  has(/41 ?°C/, 'Lázaro\'s 41 °C core temperature');
  has(/30 ?km/, 'the ~30 km collapse point');
  has(/21 January 1888/, 'Lázaro\'s birth date (Wikipedia)');
  has(/Antwerp 1920/, 'the correct Antwerp 1920 (not Paris)');
  has(/Paris 1924/, 'the correct Paris 1924');
  has(/Hakone Ekiden/, 'the Hakone Ekiden');
  has(/Kanakuri Prize/, 'the Kanakuri Prize (since 2004)');
  has(/DNF/, 'that the 1912 result was a DNF, not a time');
  has(/missing[- ]person/i, 'the honest hedge on the "missing-persons" flourish');
} else {
  ok('shipped page present for cross-check', false, pagePath);
}

console.log(`\n${fail === 0 ? 'PASS' : 'FAIL'} — ${pass}/${pass + fail} checks\n`);
process.exit(fail === 0 ? 0 : 1);
