#!/usr/bin/env node
// verify.mjs — checks the relativistic clock engine the tool actually runs.
//
// Imports the SAME module the browser page imports
// (public/strata/the-time-traveler/engine.js), so a green run here certifies the
// numbers a visitor sees. Anchors: the engineered GPS offset, the measured ISS
// offset (and Scott Kelly's year), the Hafele–Keating east/west asymmetry, and
// the low-speed / null limits.
//
// Run:  node research/time-dilation/verify.mjs

import { CONST, relativeRate, potential, orbitalSpeed,
         gpsPerDay, issPerDay, hafeleKeating, lifetime }
  from '../../public/strata/the-time-traveler/engine.js';

let pass = 0, fail = 0;
const ok = (c, m) => { if (c) pass++; else { fail++; console.error('  FAIL:', m); } };
const near = (x, lo, hi, m) => ok(x >= lo && x <= hi, `${m}  (got ${x.toExponential ? x.toFixed(4) : x})`);

console.log('The Time Traveler — relativistic clock engine, verifier\n');

// ── 0. constants are the published values, not drifted ───────────────────────
console.log('0. constants');
ok(CONST.c === 299792458, 'c is the exact SI value');
near(CONST.mu, 3.9860044e14, 3.9860045e14, 'μ = GM_⊕ is the IERS value');
near(CONST.mu / (CONST.c ** 2) * 1000, 4.43, 4.44, 'μ/c² ≈ 4.435 mm (≈ half Earth’s Schwarzschild radius)');

// ── 1. null & monotonicity limits (the physics has the right shape) ──────────
console.log('1. limits');
{
  const z = relativeRate({ r: CONST.R_E, v: 100 }, { r: CONST.R_E, v: 100 });
  ok(Math.abs(z.total) < 1e-30, 'identical states tick identically (rate 0)');
  const higher = relativeRate({ r: CONST.R_E + 1000, v: 0 }, { r: CONST.R_E, v: 0 });
  ok(higher.gr > 0 && higher.sr === 0, 'altitude alone ⇒ faster (gr>0)');
  const faster = relativeRate({ r: CONST.R_E, v: 300 }, { r: CONST.R_E, v: 0 });
  ok(faster.sr < 0 && faster.gr === 0, 'speed alone ⇒ slower (sr<0)');
  // the gh/c² near-surface approximation matches exact −μ/r to <0.1% at 1 km
  const exact = (potential(CONST.R_E + 1000) - potential(CONST.R_E)) / CONST.c ** 2;
  const approx = CONST.g0 * 1000 / CONST.c ** 2;
  // g₀ (standard gravity, 9.80665) differs from μ/R_E² (≈9.82) by ~0.14%, so the
  // gh approximation lands within ~0.2% of the exact potential difference at 1 km.
  near(Math.abs(exact - approx) / approx, 0, 0.003, 'gh/c² agrees with exact −μ/r at 1 km (<0.3%)');
}

// ── 2. GPS: the engineered offset, +38 µs/day (+45 GR, −7 SR) ────────────────
console.log('2. GPS satellite clock vs the geoid');
{
  const g = gpsPerDay();
  near(g.vSat, 3850, 3900, 'GPS orbital speed ≈ 3.87 km/s');
  near(g.gr, 45.0, 46.5, 'GR (altitude) ≈ +45.7 µs/day');
  near(g.sr, -7.4, -7.0, 'SR (speed) ≈ −7.2 µs/day');
  near(g.net, 38.0, 39.0, 'net ≈ +38 µs/day (the famous figure GPS is corrected for)');
}

// ── 3. ISS: measured offset is NEGATIVE; reproduce Scott Kelly's year ────────
console.log('3. ISS clock vs the geoid (and the Kelly twins)');
{
  const i = issPerDay(408);
  near(i.vIss, 7600, 7700, 'ISS orbital speed ≈ 7.67 km/s');
  ok(i.net < 0, 'ISS net is negative — astronauts age slower (SR beats GR at low orbit)');
  near(i.net, -27, -24, 'ISS net ≈ −25 µs/day');
  // Scott Kelly: 340 days aboard. Published "~8.6 ms younger".
  const kellyMs = i.net * 340 * 1e-3; // µs/day × days → µs → ×1e-3 → ms
  near(kellyMs, -9.5, -8.0, 'Scott Kelly’s 340 days ⇒ ≈ −8.6 ms (he aged ms less)');
}

// ── 4. Hafele–Keating: the east/west asymmetry, signs + scale (not exact) ────
console.log('4. Hafele–Keating, simplified circumnavigation');
{
  const e = hafeleKeating({ direction: 'E' });
  const w = hafeleKeating({ direction: 'W' });
  ok(e.net < 0, 'eastward leg: net NEGATIVE (clock loses) — matches H&K predicted −40 / observed −59 ns');
  ok(w.net > 0, 'westward leg: net POSITIVE (clock gains) — matches H&K predicted +275 / observed +273 ns');
  ok(w.net > e.net, 'westward > eastward (the rotation asymmetry, the heart of the experiment)');
  near(Math.abs(e.net), 20, 400, 'eastward magnitude is tens–hundreds of ns');
  near(w.net, 50, 500, 'westward magnitude is tens–hundreds of ns');
  // the asymmetry is purely kinematic: GR is identical on both legs
  near(Math.abs(e.gr - w.gr), 0, 1e-6, 'GR term identical east vs west (same altitude/time)');
  ok(e.sr < 0 && w.sr > 0, 'the SR term flips sign with direction — the whole asymmetry');
}

// ── 5. your life: signs, scale, and that flights mostly ADD time ─────────────
console.log('5. a life vs a sea-level stay-at-home twin');
{
  // Denver, 1609 m, lived 40 years, no flights → you age MORE (altitude).
  const denver = lifetime({ home: { altitudeM: 1609, latDeg: 39.7, years: 40 } });
  ok(denver.totalMicros > 0, 'a mile-high life ⇒ you age MORE than the sea-level twin');
  near(denver.totalMicros, 150, 320, 'Denver, 40 y ⇒ a few hundred µs older');
  ok(Math.abs(denver.srMicros) < Math.abs(denver.grMicros), 'for slow living, altitude (GR) dominates speed (SR)');

  // A pilot: sea-level home + 20 000 hours at altitude. Subsonic flight ADDS time
  // (altitude beats speed), so the net is positive and dominated by the flights.
  const pilot = lifetime({
    home: { altitudeM: 0, latDeg: 0, years: 40 },
    flights: [{ hours: 20000, altitudeKm: 11, speedKmh: 880, heading: 'NS' }],
  });
  ok(pilot.totalMicros > 0, 'a subsonic career aloft ⇒ net positive (altitude wins for jets)');
  near(pilot.totalMicros, 2, 80, '20 000 flight-hours ⇒ tens of µs, the right scale');

  // sanity: total = gr + sr exactly
  ok(Math.abs(pilot.totalSeconds - (pilot.grSeconds + pilot.srSeconds)) < 1e-30, 'total = GR + SR exactly');
  // a stay-at-home sea-level twin vs itself is ~0
  const home0 = lifetime({ home: { altitudeM: 0, latDeg: 0, years: 80 } });
  ok(Math.abs(home0.totalMicros) < 1e-6, 'sea-level life vs sea-level twin ≈ 0');
}

console.log(`\n${pass} checks passed, ${fail} failed.`);
process.exit(fail ? 1 : 0);
