// verify-short-by-a-hair.mjs — the metrology behind the stratum
// "Short by a Hair" (/strata/short-by-a-hair/).
//
// The claim the page corrects, in two layers:
//
//   LAYER 1 (the textbook fact).  "A metre is one ten-millionth of the distance
//   from the North Pole to the equator." Recompute the meridian quarter against
//   the real (WGS84) Earth and that definition would make the metre slightly
//   LONGER than the legal metre — so the metre we actually use is about
//   0.197 mm SHORT of its own founding definition.
//
//   LAYER 2 (the romantic telling).  Ken Alder's "The Measure of All Things"
//   frames the shortfall around the astronomer Méchain's concealed latitude
//   error. But the documented error budget is ~95% unmodelled vertical
//   deflection of the plumb line, ~3% wrong Earth-flattening, and <2% Delambre
//   & Méchain's own measurement error. Méchain's famous mistake is the smallest
//   sliver. (This split is a scholarly ATTRIBUTION ESTIMATE, flagged as such.)
//
// What this script proves, offline and from scratch:
//   1. The WGS84 meridian quarter Q (equator -> pole) computed two independent
//      ways — composite-Simpson integration of the meridian arc integral, and
//      the third-flattening series (Ivory/Bessel/Helmert) — agree, and land on
//      the published 10,001,965.729 m.
//   2. Q / 10,000,000 - 1 = +0.0001966 m  =>  the metre defined that way would
//      be 0.1966 mm longer, i.e. the legal metre is ~0.197 mm short. Matches
//      Alder 2002 and Wikipedia ("0.197 millimetres shorter").
//   3. The historical ligne values: definitive metre (1799) = 443.296 lignes;
//      provisional metre (1795) = 443.44 lignes; the gap is 0.144 lignes, which
//      converts to ~0.325 mm using the Paris ligne (pied du roi / 144).
//   4. The 1983 SI metre: c = 299792458 m/s exactly; a metre is the distance
//      light travels in 1/c second.
//   5. The error-budget bars (95 / 3 / <2) sum to ~100% and are reproduced as
//      the page displays them (flagged: scholarly attribution, not an exact
//      ledger).
//
//   run:  node research/short-by-a-hair/verify-short-by-a-hair.mjs
//
// No dependencies. Every headline number the page displays is recomputed here.

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`);
};
const approx = (a, b, eps) => Math.abs(a - b) <= eps;

// ── WGS84 defining constants (exact by definition) ──────────────────────────
const a = 6378137.0;            // semi-major axis (m)
const invf = 298.257223563;     // inverse flattening
const f = 1 / invf;             // flattening
const e2 = f * (2 - f);         // first eccentricity squared
const n = f / (2 - f);          // third flattening

// ── 1. Quarter meridian, two independent methods ────────────────────────────
// Meridian arc from equator (0) to pole (pi/2):
//   M(pi/2) = a(1-e2) * integral_0^{pi/2} (1 - e2 sin^2 t)^{-3/2} dt
function quarterMeridian_simpson(N) {
  const A = 0, B = Math.PI / 2, h = (B - A) / N;
  const g = (t) => Math.pow(1 - e2 * Math.sin(t) * Math.sin(t), -1.5);
  let s = g(A) + g(B);
  for (let i = 1; i < N; i++) s += (i % 2 ? 4 : 2) * g(A + i * h);
  return a * (1 - e2) * (h / 3) * s;
}
// Third-flattening series (Ivory):
//   Q = a/(1+n) * (1 + n^2/4 + n^4/64 + n^6/256 + ...) * pi/2
function quarterMeridian_series() {
  const c0 = 1 + n * n / 4 + Math.pow(n, 4) / 64 + Math.pow(n, 6) / 256;
  return (a / (1 + n)) * c0 * Math.PI / 2;
}

const Q_simpson = quarterMeridian_simpson(200000);
const Q_series = quarterMeridian_series();
const Q_PUBLISHED = 10001965.729; // Wikipedia "Meridian arc", WGS84 quarter meridian

console.log('— WGS84 quarter meridian (equator -> pole), two methods —');
console.log(`  Simpson integration : ${Q_simpson.toFixed(4)} m`);
console.log(`  third-flattening    : ${Q_series.toFixed(4)} m`);
console.log(`  published           : ${Q_PUBLISHED.toFixed(3)} m`);
ok('two methods agree to < 1 mm', approx(Q_simpson, Q_series, 0.001),
   `Δ=${Math.abs(Q_simpson - Q_series).toExponential(2)} m`);
ok('lands on published 10,001,965.729 m (< 0.1 mm)',
   approx(Q_simpson, Q_PUBLISHED, 0.1), `Δ=${(Math.abs(Q_simpson - Q_PUBLISHED) * 1000).toFixed(4)} mm`);

const Q = Q_simpson; // use the high-resolution numerical value henceforth

// ── 2. The shortfall ────────────────────────────────────────────────────────
// "1 metre = one ten-millionth of the quarter meridian" would give:
const idealMetre = Q / 1e7;               // metres
const overshoot_mm = (idealMetre - 1) * 1000; // how much LONGER the ideal metre is
console.log('\n— the shortfall —');
console.log(`  ideal metre = Q / 10,000,000 = ${idealMetre.toFixed(10)} m`);
console.log(`  ideal - 1 m = +${overshoot_mm.toFixed(6)} mm  (the ideal metre is longer)`);
console.log(`  => the legal metre is ${overshoot_mm.toFixed(4)} mm SHORTER than its founding definition`);
ok('shortfall is ~0.197 mm (Alder/Wikipedia: 0.197 mm)', approx(overshoot_mm, 0.197, 0.01),
   `${overshoot_mm.toFixed(4)} mm`);
// the page displays "0.197 mm" and "0.1966 mm"; check both roundings
ok('rounds to 0.197 mm (3 dp)', overshoot_mm.toFixed(3) === '0.197', overshoot_mm.toFixed(3));
ok('rounds to 0.1966 mm (4 dp)', overshoot_mm.toFixed(4) === '0.1966', overshoot_mm.toFixed(4));

// ── 3. Historical ligne values ──────────────────────────────────────────────
// 1 pied du roi (Paris foot) = 0.3248406 m; 1 pied = 144 lignes.
const pied = 0.3248406;
const ligne = pied / 144;                 // metres per Paris ligne
const metre_1799 = 443.296;               // lignes, definitive (Mètre des Archives)
const metre_1795 = 443.44;                // lignes, provisional (legislated 7 Apr 1795)
const gap_lignes = metre_1795 - metre_1799;
const gap_mm = gap_lignes * ligne * 1000;
console.log('\n— the historical ligne values —');
console.log(`  1 ligne = ${(ligne * 1000).toFixed(4)} mm  (pied du roi / 144)`);
console.log(`  definitive 1799 = ${metre_1799} lignes -> ${(metre_1799 * ligne).toFixed(7)} m`);
console.log(`  provisional 1795 = ${metre_1795} lignes`);
console.log(`  gap = ${gap_lignes.toFixed(3)} lignes = ${gap_mm.toFixed(4)} mm`);
ok('Paris ligne ≈ 2.2558 mm', approx(ligne * 1000, 2.2558, 0.001), `${(ligne * 1000).toFixed(4)} mm`);
ok('definitive metre 443.296 lignes is essentially 1 m by construction',
   approx(metre_1799 * ligne, 1, 0.0001), `${(metre_1799 * ligne).toFixed(7)} m`);
ok('provisional/definitive gap is 0.144 lignes', approx(gap_lignes, 0.144, 0.0005),
   `${gap_lignes.toFixed(4)} lignes`);
ok('that gap is ~0.32 mm', approx(gap_mm, 0.325, 0.01), `${gap_mm.toFixed(4)} mm`);
// guard against the spec's digit-swap: 0.114 lignes does NOT give 0.32 mm
ok('SANITY: 0.114 lignes would be ~0.257 mm, NOT 0.32 mm (the spec swapped digits)',
   approx(0.114 * ligne * 1000, 0.257, 0.01), `0.114 lignes = ${(0.114 * ligne * 1000).toFixed(4)} mm`);

// ── 4. The 1983 SI metre via the speed of light ─────────────────────────────
const c = 299792458; // m/s, exact
const lightSecondPerMetre = 1 / c;
console.log('\n— the metre cut loose from the Earth (1983) —');
console.log(`  c = ${c} m/s exactly`);
console.log(`  1 m = light's travel in 1/c s = ${lightSecondPerMetre.toExponential(9)} s`);
ok('c is exactly 299,792,458 m/s', c === 299792458);
ok('1/c ≈ 3.3356 ns', approx(lightSecondPerMetre * 1e9, 3.3356, 0.001),
   `${(lightSecondPerMetre * 1e9).toFixed(4)} ns`);

// ── 5. The error budget (scholarly attribution estimate) ────────────────────
// Wikipedia "Arc measurement of Delambre and Méchain", citing geodetic analyses:
//   ~95% unmodelled vertical deflection; ~3% wrong flattening; <2% measurement.
const budget = { 'vertical deflection': 95, 'wrong flattening': 3, 'D&M measurement': 2 };
const sum = Object.values(budget).reduce((s, v) => s + v, 0);
console.log('\n— error budget (attribution estimate, not an exact ledger) —');
for (const [k, v] of Object.entries(budget)) {
  // each percentage applied to the 0.197 mm shortfall:
  console.log(`  ${k.padEnd(20)} ${String(v).padStart(2)}%  ≈ ${(overshoot_mm * v / 100 * 1000).toFixed(1)} µm of the shortfall`);
}
ok('budget bars sum to ~100%', approx(sum, 100, 0.5), `sum=${sum}%`);
ok('vertical deflection dominates (>= 90%)', budget['vertical deflection'] >= 90);
ok("Méchain's measurement error is the smallest sliver (< flattening, < deflection)",
   budget['D&M measurement'] < budget['wrong flattening'] &&
   budget['D&M measurement'] < budget['vertical deflection']);

// ── pinned page values: exactly what the HTML must display ───────────────────
console.log('\n— page-display values (must match index.html) —');
const PAGE = {
  Q_m: '10,001,965.7',          // headline quarter meridian, 1 dp
  shortfall_mm: '0.197',         // headline shortfall
  shortfall_mm4: '0.1966',       // precise shortfall
  idealMetre_m: '1.0001966',     // ideal metre to 7 dp
  ligne_mm: '2.2558',
  gap_lignes: '0.144',
  gap_mm: '0.32',
  c: '299792458',
  pct: [95, 3, 2],
};
ok('Q displays as 10,001,965.7 m', Q.toFixed(1).replace(/\B(?=(\d{3})+(?!\d))/g, ',') === PAGE.Q_m,
   Q.toFixed(1));
ok('shortfall displays as 0.197 mm', overshoot_mm.toFixed(3) === PAGE.shortfall_mm);
ok('shortfall displays as 0.1966 mm', overshoot_mm.toFixed(4) === PAGE.shortfall_mm4);
ok('ideal metre displays as 1.0001966 m', idealMetre.toFixed(7) === PAGE.idealMetre_m, idealMetre.toFixed(7));
ok('ligne displays as 2.2558 mm', (ligne * 1000).toFixed(4) === PAGE.ligne_mm);
ok('gap displays as 0.144 lignes', gap_lignes.toFixed(3) === PAGE.gap_lignes);
ok('gap displays as ~0.32 mm', gap_mm.toFixed(2) === PAGE.gap_mm, gap_mm.toFixed(2));

console.log(`\n${fails === 0 ? 'ALL CHECKS PASSED' : fails + ' CHECK(S) FAILED'}\n`);
process.exit(fails === 0 ? 0 : 1);
