#!/usr/bin/env node
// verify.mjs — The gravity tunnel ("fall through the Earth"), checked offline.
//
// Two claims the stratum makes, each recomputed here from first principles:
//
//   (A) UNIFORM-DENSITY EARTH. Gravity inside grows linearly, g(r) = g_s·(r/R),
//       so a ball dropped into any *straight* tunnel undergoes simple harmonic
//       motion. Surface-to-surface transit is a half period,
//           t = pi * sqrt(R^3 / GM)  ~ 42.2 min,
//       and — the surprise — it is *the same for every chord*, no matter how far
//       the tunnel misses the centre. We prove that analytically AND integrate
//       the equation of motion for several chords to confirm one number.
//
//   (B) REALISTIC EARTH (PREM). The real planet has a dense iron core, so g does
//       NOT fall off linearly — it stays near 9.8 m/s^2 through the whole mantle
//       and only drops in the core. Feeding the PREM density profile (Dziewonski
//       & Anderson 1981) through the same machinery gives a *shorter* fall,
//       ~38 min, and the chord-independence BREAKS. We reproduce Klotz (2015),
//       Am. J. Phys. 83, 231, who reported 38.2 min for the diametric tunnel.
//
// Self-checks that guard the PREM model: integrating its density must return
// Earth's mass and mean density, and its surface gravity must be ~9.8 m/s^2.
// If those fail, every downstream time is meaningless — so they run first.
//
// Run: node research/gravity-tunnel/verify.mjs
'use strict';

// ---- physical constants (CODATA / IAU nominal) ----
const G  = 6.67430e-11;      // m^3 kg^-1 s^-2
const R  = 6.371e6;          // mean Earth radius, m
const GM = 3.986004418e14;   // standard gravitational parameter, m^3 s^-2 (defines M)
const M_earth = GM / G;      // kg, implied by GM (5.972e24)

let pass = 0, fail = 0;
const results = [];
function check(name, got, want, tol, unit = '') {
  const ok = Math.abs(got - want) <= tol;
  ok ? pass++ : fail++;
  results.push({ name, got, want, tol, unit, ok });
  const g = typeof got === 'number' ? got.toPrecision(7) : got;
  const w = typeof want === 'number' ? want.toPrecision(7) : want;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}\n        got ${g}${unit}  want ${w}±${tol}${unit}`);
}

// =====================================================================
// (A) UNIFORM-DENSITY EARTH
// =====================================================================
console.log('\n=== (A) Uniform-density Earth ===\n');

// Analytic half-period (surface to surface) = pi * sqrt(R^3 / GM).
const t_uniform_analytic = Math.PI * Math.sqrt(R ** 3 / GM);
console.log(`analytic half-period  pi*sqrt(R^3/GM) = ${t_uniform_analytic.toFixed(2)} s`
          + `  = ${(t_uniform_analytic / 60).toFixed(3)} min`);

// RK4 integrator for a straight tunnel, uniform density.
// Coordinate x = signed distance along the chord from its midpoint.
// Distance from centre r = sqrt(d^2 + x^2), d = impact parameter (centre->chord).
// g(r) = (GM/R^3)*r toward centre; component along chord = (GM/R^3)*x  (d cancels!).
function transitUniform(d) {
  const xmax = Math.sqrt(Math.max(R * R - d * d, 0)); // entry point on surface
  const K = GM / R ** 3;
  // a(x) = -K * x  (independent of d). Integrate x from +xmax (v=0) to x=0, double.
  const accel = (x) => -K * x;
  return 2 * halfTransit(xmax, accel);
}

// Integrate a symmetric oscillator from rest at x0 down to x=0 (a quarter... no:
// from a surface entry to the midpoint of the chord) and return that time.
// RK4 in (x, v); stop when x crosses 0, interpolate the crossing linearly in t.
function halfTransit(x0, accel) {
  let x = x0, v = 0, t = 0;
  const dt = 0.02;
  for (let i = 0; i < 100_000_000; i++) {
    const x1 = x, v1 = v, a1 = accel(x1);
    const x2 = x + 0.5 * dt * v1, v2 = v + 0.5 * dt * a1, a2 = accel(x2);
    const x3 = x + 0.5 * dt * v2, v3 = v + 0.5 * dt * a2, a3 = accel(x3);
    const x4 = x + dt * v3,       v4 = v + dt * a3,       a4 = accel(x4);
    const xn = x + (dt / 6) * (v1 + 2 * v2 + 2 * v3 + v4);
    const vn = v + (dt / 6) * (a1 + 2 * a2 + 2 * a3 + a4);
    if (![a1, a2, a3, a4, xn, vn].every(Number.isFinite))
      throw new Error('halfTransit: non-finite state');
    if (xn <= 0) {                     // crossed the midpoint this step
      const frac = x / (x - xn);       // linear interp of the zero crossing
      return t + frac * dt;
    }
    x = xn; v = vn; t += dt;
  }
  throw new Error('halfTransit did not converge');
}

const t_uniform_num = transitUniform(0); // diametric
check('uniform diametric transit (numeric RK4 vs analytic)',
      t_uniform_num, t_uniform_analytic, 0.05, ' s');
check('uniform diametric transit ~= 42.2 min',
      t_uniform_num / 60, 42.2, 0.1, ' min');

// The surprise: chord independence. Tunnels at impact parameters from 0 (through
// the centre) to 0.95R (a shallow chord, London-ish to a nearby city) must all
// give the SAME surface-to-surface time.
console.log('\n-- chord independence (uniform): every straight tunnel, one clock --');
const chordTimes = [0, 0.25, 0.5, 0.75, 0.95].map((f) => {
  const t = transitUniform(f * R) / 60;
  console.log(`   impact parameter ${(f).toFixed(2)}R  ->  ${t.toFixed(4)} min`);
  return t;
});
const spread = Math.max(...chordTimes) - Math.min(...chordTimes);
check('uniform chord independence: spread across d=0..0.95R is ~0',
      spread, 0, 0.01, ' min');

// =====================================================================
// (B) REALISTIC EARTH — PREM density profile
// =====================================================================
console.log('\n=== (B) Realistic Earth (PREM, Dziewonski & Anderson 1981) ===\n');

// PREM density (g/cm^3) as a function of x = r / 6371 km, piecewise by radius.
// Coefficients from Dziewonski & Anderson (1981), Phys. Earth Planet. Inter. 25, 297.
const R_PREM = 6371e3; // PREM's own normalising radius, m
function rhoPREM(r) {          // r in metres -> density in kg/m^3
  const rk = r / 1000;        // km
  const x = r / R_PREM;       // normalised radius
  let rho;                    // g/cm^3
  if (rk < 1221.5)      rho = 13.0885 - 8.8381 * x * x;
  else if (rk < 3480.0) rho = 12.5815 - 1.2638 * x - 3.6426 * x * x - 5.5281 * x ** 3;
  else if (rk < 5701.0) rho = 7.9565 - 6.4761 * x + 5.5283 * x * x - 3.0807 * x ** 3;
  else if (rk < 5771.0) rho = 5.3197 - 1.4836 * x;
  else if (rk < 5971.0) rho = 11.2494 - 8.0298 * x;
  else if (rk < 6151.0) rho = 7.1089 - 3.8045 * x;
  else if (rk < 6346.6) rho = 2.6910 + 0.6924 * x;
  else if (rk < 6356.0) rho = 2.9000;
  else if (rk < 6368.0) rho = 2.6000;
  else                  rho = 1.0200;   // ocean
  return rho * 1000;          // g/cm^3 -> kg/m^3
}

// Cumulative enclosed mass M(r) = ∫_0^r 4π s^2 ρ(s) ds on a fine radial grid.
const NGRID = 200_000;
const dr = R_PREM / NGRID;
const Menc = new Float64Array(NGRID + 1);
for (let i = 1; i <= NGRID; i++) {
  const s0 = (i - 1) * dr, s1 = i * dr, sm = (s0 + s1) / 2; // Simpson on each cell
  const f0 = 4 * Math.PI * s0 * s0 * rhoPREM(s0);
  const fm = 4 * Math.PI * sm * sm * rhoPREM(sm);
  const f1 = 4 * Math.PI * s1 * s1 * rhoPREM(s1);
  Menc[i] = Menc[i - 1] + (dr / 6) * (f0 + 4 * fm + f1);
}
function massBelow(r) {        // interpolate cumulative mass at radius r (m)
  if (r <= 0) return 0;
  if (r >= R_PREM) return Menc[NGRID];
  const idx = r / dr, i0 = Math.min(NGRID - 1, Math.floor(idx)), frac = idx - i0;
  return Menc[i0] + frac * (Menc[i0 + 1] - Menc[i0]);
}
function gPREM(r) {            // gravitational acceleration at radius r (m/s^2)
  if (r <= 0) return 0;
  return G * massBelow(r) / (r * r);
}

// --- self-checks on the PREM model (guard everything downstream) ---
const M_prem = Menc[NGRID];
const meanRho = M_prem / ((4 / 3) * Math.PI * R_PREM ** 3);
const g_surface = gPREM(R_PREM);
check('PREM integrated mass = Earth mass', M_prem, 5.972e24, 6e21, ' kg');
check('PREM mean density ~ 5514 kg/m^3', meanRho, 5514, 25, ' kg/m^3');
check('PREM surface gravity ~ 9.8 m/s^2', g_surface, 9.81, 0.1, ' m/s^2');

// g through the mantle stays near-constant (Klotz's key observation) — sample it.
console.log('\n-- g(r) through a PREM Earth (why the fall is faster) --');
for (const f of [0.15, 0.3, 0.545, 0.7, 0.85, 1.0]) {
  const r = f * R_PREM;
  console.log(`   r = ${(f).toFixed(3)}R  (${(r/1000).toFixed(0)} km):  g = ${gPREM(r).toFixed(3)} m/s^2`);
}

// --- diametric fall through PREM ---
function transitPREM(d) {
  const xmax = Math.sqrt(Math.max(R_PREM * R_PREM - d * d, 0));
  const accel = (x) => {
    const r = Math.hypot(d, x);
    if (r === 0) return 0;
    return -gPREM(r) * (x / r); // along-chord component toward the low point
  };
  return 2 * halfTransit(xmax, accel);
}
const t_prem = transitPREM(0);
console.log('');
check('PREM diametric transit ~ 38 min (Klotz 2015: 38.2 min)',
      t_prem / 60, 38.2, 0.5, ' min');

// --- chord dependence in PREM: shallow tunnels are now SLOWER, not equal ---
console.log('\n-- chord DEPENDENCE (PREM): the tautochrone spell is broken --');
const premChord = [0, 0.3, 0.6, 0.9].map((f) => {
  const t = transitPREM(f * R_PREM) / 60;
  console.log(`   impact parameter ${(f).toFixed(2)}R  ->  ${t.toFixed(3)} min`);
  return t;
});
const premSpread = Math.max(...premChord) - Math.min(...premChord);
check('PREM chord dependence: spread is NON-trivial (independence broken)',
      premSpread > 0.5 ? 1 : 0, 1, 0, '');

// =====================================================================
console.log('\n=== summary ===');
console.log(`uniform-density diametric fall : ${(t_uniform_num / 60).toFixed(2)} min  (every chord identical)`);
console.log(`realistic (PREM) diametric fall: ${(t_prem / 60).toFixed(2)} min  (chords differ)`);
console.log(`\n${pass}/${pass + fail} checks passed.`);
process.exit(fail ? 1 : 0);
