#!/usr/bin/env node
// Verifier for "The Tide the Textbook Got Wrong" — the tides, recomputed from
// primary constants.
//
//   node research/the-tide-textbook-got-wrong/verify.mjs
//
// WHAT THIS PROVES (it computes, it does not assert):
//   • The Sun's direct gravitational pull on Earth is ~179x the Moon's, yet the
//     Moon raises the larger tide — because the tide-raising force is the GRADIENT
//     of gravity and falls off as 1/d^3, not 1/d^2. The solar tide is ~0.46x the
//     lunar one. The clean identity: tide ratio = pull ratio / (how many times
//     farther the Sun is).
//   • The tidal force points OUTWARD on BOTH the near and far sides of Earth — the
//     far-side bulge is real (and only ~5% smaller than the near one), computed
//     exactly from the differential of GM/r^2, with no "centrifugal" hand-waving.
//   • The equilibrium ("two neat bulges") tide is about half a metre. The mean
//     equatorial lunar sweep is ~448 m/s, compared with ~190 m/s for a free
//     shallow-water wave in the stated 3.7 km depth model. This comparison does
//     not solve the tide in a real basin. Real tides are the dynamic response
//     Laplace described, and the Bay of
//     Fundy reaches ~16 m, more than twentyfold the equilibrium prediction.
//
// WHAT IT DOES NOT PROVE: the laws of gravitation themselves; the existence and
// positions of the world's amphidromic points (those come from solving Laplace's
// tidal equations on the real basins / from observation, named honestly on the
// page, not re-derived here); the exact Bay of Fundy record (a cited observation).
//
// PRIMARY CONSTANTS (with sources, all SI):
const G        = 6.67430e-11;       // CODATA 2018 gravitational constant  [m^3 kg^-1 s^-2]
const M_sun    = 1.9884e30;         // NASA Sun fact sheet                 [kg]
// https://nssdc.gsfc.nasa.gov/planetary/factsheet/sunfact.html
const M_moon   = 7.346e22;          // NASA Moon fact sheet                [kg]
// https://nssdc.gsfc.nasa.gov/planetary/factsheet/moonfact.html
const M_earth  = 5.97217e24;        // IAU 2015 / NASA Earth mass          [kg]
const R_earth  = 6.371e6;           // mean (volumetric) Earth radius      [m]
const a_moon   = 3.844e8;           // mean Earth–Moon distance (384 400 km, NASA)  [m]
const a_sun    = 1.495978707e11;    // 1 astronomical unit (IAU 2012, exact defn)   [m]
const g_surf   = 9.80665;           // standard gravity                    [m s^-2]
const T_lunar  = 24 * 3600 + 50.47 * 60; // mean lunar day: 24 h 50.47 min  [s]
// Stewart, Introduction to Physical Oceanography, §17.4, Tidal Frequencies:
// https://geo.libretexts.org/Bookshelves/Oceanography/Introduction_to_Physical_Oceanography_(Stewart)/17%3A_Coastal_Processes_and_Tides/17.4%3A_Theory_of_Ocean_Tides
const H_ocean  = 3700;              // mean ocean depth (~3.7 km, NOAA)    [m]

// OBSERVED (cited, not derived):
const FUNDY_SPRING_RANGE = 16.0;    // Bay of Fundy great spring range ~16 m (Burntcoat Head); NOAA/Canadian Hydrographic Service

let n = 0, pass = 0;
const approx = (a, b, rel) => Math.abs(a - b) <= rel * Math.abs(b);
const ok = (name, cond, extra = '') => { n++; if (cond) pass++; console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   — ' + extra : ''}`); };
const fmt = (x, d = 3) => x.toExponential(d);

console.log('\n— The Tide the Textbook Got Wrong — checks from primary constants —\n');

// ─────────────────────────────────────────────────────────────────────────────
// I · The pull: the Sun crushes the Moon, ~179 to 1   (force ∝ M / d^2)
// ─────────────────────────────────────────────────────────────────────────────
const pull_sun  = M_sun  / a_sun  ** 2;     // ∝ acceleration of Earth toward Sun
const pull_moon = M_moon / a_moon ** 2;     // ∝ acceleration of Earth toward Moon
const pullRatio = pull_sun / pull_moon;
ok('the Sun pulls Earth ~179x harder than the Moon (M/d^2 ratio)',
   approx(pullRatio, 179, 0.01), `ratio = ${pullRatio.toFixed(1)}`);
// sanity: the absolute solar pull on Earth's centre is ~5.9e-3 m/s^2
ok('absolute solar pull on Earth ≈ 5.9e-3 m/s^2', approx(G * pull_sun, 5.93e-3, 0.01), `${fmt(G*pull_sun)} m/s^2`);

// ─────────────────────────────────────────────────────────────────────────────
// II · The tide: the Moon wins   (tide-raising force ∝ M / d^3)
// ─────────────────────────────────────────────────────────────────────────────
const tide_sun  = M_sun  / a_sun  ** 3;
const tide_moon = M_moon / a_moon ** 3;
const tideRatio = tide_sun / tide_moon;     // solar tide as a fraction of the lunar tide
ok('the solar tide is ~0.46x the lunar tide (M/d^3 ratio)',
   approx(tideRatio, 0.46, 0.02), `ratio = ${tideRatio.toFixed(3)}`);
ok('so the Moon, not the Sun, dominates the tides (tideRatio < 1)', tideRatio < 1);

// THE IDENTITY that is the whole point: the one extra power of distance flips it.
const distRatio = a_sun / a_moon;           // how many times farther the Sun is (~389)
ok('the Sun is ~389x farther than the Moon', approx(distRatio, 389, 0.01), `${distRatio.toFixed(0)}x`);
ok('IDENTITY  tideRatio = pullRatio / distRatio  (179 / 389 ≈ 0.46)',
   approx(tideRatio, pullRatio / distRatio, 1e-9),
   `${pullRatio.toFixed(1)} / ${distRatio.toFixed(0)} = ${(pullRatio/distRatio).toFixed(3)}`);

// ─────────────────────────────────────────────────────────────────────────────
// III · Two bulges, both real, both OUTWARD — exact differential, no fudge
//   residual at a point = (its gravity toward the body) − (Earth-centre's gravity)
//   near side (d−R): residual points TOWARD the body  = outward from Earth centre
//   far  side (d+R): residual points AWAY from the body = outward from Earth centre
// ─────────────────────────────────────────────────────────────────────────────
function bulges(M, d) {
  const GM = G * M;
  const aCentre = GM / d ** 2;
  const aNear   = GM / (d - R_earth) ** 2;          // stronger pull → net toward body
  const aFar    = GM / (d + R_earth) ** 2;          // weaker pull → net away from body
  const resNear = aNear - aCentre;                  // > 0, outward from centre (toward body)
  const resFar  = aCentre - aFar;                   // > 0, outward from centre (away from body)
  const approx2 = 2 * GM * R_earth / d ** 3;        // the textbook 2GMR/d^3
  return { resNear, resFar, approx2 };
}
const moonB = bulges(M_moon, a_moon);
ok('near-side lunar tidal accel ≈ 1.13e-6 m/s^2 (outward)', approx(moonB.resNear, 1.13e-6, 0.02), `${fmt(moonB.resNear)}`);
ok('FAR-side lunar tidal accel ≈ 1.07e-6 m/s^2 (also OUTWARD — the far bulge is real)',
   approx(moonB.resFar, 1.07e-6, 0.02), `${fmt(moonB.resFar)}`);
ok('both bulges point outward from Earth\'s centre (both residuals > 0)',
   moonB.resNear > 0 && moonB.resFar > 0);
ok('the far bulge is only ~5% smaller than the near one (NOT absent, NOT half)',
   approx(moonB.resFar / moonB.resNear, 0.951, 0.01), `far/near = ${(moonB.resFar/moonB.resNear).toFixed(3)}`);
ok('the 2GMR/d^3 textbook value sits between near and far (it is the symmetric approximation)',
   moonB.approx2 < moonB.resNear && moonB.approx2 > moonB.resFar, `${fmt(moonB.approx2)}`);

// ─────────────────────────────────────────────────────────────────────────────
// IV · The equilibrium tide: about half a metre   (Newton's static bulge)
//   high-tide elevation  ζ0 = (M/M_earth)(R/d)^3 R   ;  low at 90° = −ζ0/2
//   equilibrium range (high − low) = (3/2) ζ0
// ─────────────────────────────────────────────────────────────────────────────
function equilHigh(M, d) { return (M / M_earth) * (R_earth / d) ** 3 * R_earth; }
const hMoon = equilHigh(M_moon, a_moon);
const hSun  = equilHigh(M_sun,  a_sun);
ok('equilibrium lunar high tide ≈ 0.36 m above mean', approx(hMoon, 0.357, 0.02), `${hMoon.toFixed(3)} m`);
ok('equilibrium solar high tide ≈ 0.16 m above mean',  approx(hSun, 0.164, 0.02), `${hSun.toFixed(3)} m`);
ok('solar/lunar equilibrium amplitude ratio = the same 0.46 (consistency with §II)',
   approx(hSun / hMoon, tideRatio, 1e-9), `${(hSun/hMoon).toFixed(3)}`);
const rangeSpring = 1.5 * (hMoon + hSun);   // aligned (full/new Moon), high−low
const rangeNeap   = 1.5 * (hMoon - hSun);   // opposed (quarter Moon)
ok('combined equilibrium SPRING range ≈ 0.78 m', approx(rangeSpring, 0.78, 0.03), `${rangeSpring.toFixed(2)} m`);
ok('combined equilibrium NEAP range ≈ 0.29 m',   approx(rangeNeap, 0.29, 0.03), `${rangeNeap.toFixed(2)} m`);
ok('spring tide is ~2.7x the neap (the fortnightly beat)', approx(rangeSpring/rangeNeap, 2.7, 0.05), `${(rangeSpring/rangeNeap).toFixed(1)}x`);

// ─────────────────────────────────────────────────────────────────────────────
// V · THE WALL: a mean-depth comparison (Laplace, dynamic theory)
//   Mean lunar hour-angle sweep at the equator versus a free shallow-water
//   wave (c = sqrt(gH)); this comparison is not a basin-dynamics solution.
// ─────────────────────────────────────────────────────────────────────────────
const vSubLunar = 2 * Math.PI * R_earth / T_lunar; // mean equatorial sweep of lunar forcing
const cWave     = Math.sqrt(g_surf * H_ocean);      // shallow-water (tidal) wave speed
ok('the mean equatorial lunar sweep is ~448 m/s (~1610 km/h)',
   approx(vSubLunar, 448, 0.002), `${vSubLunar.toFixed(0)} m/s`);
ok('a free shallow-water wave at 3.7 km depth travels ~190 m/s (~690 km/h)',
   approx(cWave, 190, 0.02), `${cWave.toFixed(0)} m/s`);
ok('THE WALL: mean equatorial forcing exceeds free-wave speed in the 3.7 km model (448 > 190)',
   vSubLunar > cWave, `speed ratio = ${(vSubLunar/cWave).toFixed(1)}`);

// The observed proof of dynamic amplification: the Bay of Fundy beats equilibrium 20x+
const amplification = FUNDY_SPRING_RANGE / rangeSpring;
ok('the Bay of Fundy spring range (~16 m) exceeds the equilibrium prediction more than twentyfold',
   amplification > 20, `${amplification.toFixed(0)}x the equilibrium ${rangeSpring.toFixed(2)} m`);

// ─────────────────────────────────────────────────────────────────────────────
console.log(`\n${pass}/${n} checks passed.\n`);
if (pass !== n) process.exit(1);

// Emit the canonical figures the page must quote verbatim (drift guard source).
const FIG = {
  pullRatio:  +pullRatio.toFixed(1),
  tideRatio:  +tideRatio.toFixed(3),
  distRatio:  +distRatio.toFixed(0),
  resNear:    +moonB.resNear.toExponential(2),
  resFar:     +moonB.resFar.toExponential(2),
  farOverNear:+(moonB.resFar / moonB.resNear).toFixed(3),
  hMoon:      +hMoon.toFixed(2),
  hSun:       +hSun.toFixed(2),
  rangeSpring:+rangeSpring.toFixed(2),
  rangeNeap:  +rangeNeap.toFixed(2),
  vSubLunar:  +vSubLunar.toFixed(0),
  cWave:      +cWave.toFixed(0),
  fundy:      FUNDY_SPRING_RANGE,
  amplification: +amplification.toFixed(0),
};
console.log('canonical figures for the page:');
console.log(JSON.stringify(FIG, null, 2));
