#!/usr/bin/env node
// research/watch-the-earth-turn/verify.mjs
// Recompute — in front of you — every physical and numeric claim the stratum
// "Watch the Earth Turn" (the Foucault pendulum) makes.
//
// The whole piece rests on ONE number, the rate at which the swing plane turns,
// arrived at THREE independent ways that must agree:
//
//   A. The closed form.  In the rotating frame the small-oscillation equations
//      z̈ + 2iω ż + ω₀² z = 0 (z = x+iy, ω = Ω·sinφ, ω₀=√(g/L)) carry an exact
//      factor e^{-iωt}: the swing pattern precesses at rate ω = Ω·sinφ relative
//      to the ground, whatever the pendulum's own frequency ω₀.
//   B. The simulation.  We do NOT assume A — we RK4-integrate the equations,
//      detect the turning points of the bob, track the azimuth of the swing
//      line, and MEASURE its drift. It comes out ω = Ω·sinφ, independent of ω₀.
//   C. The geometry.  Forget forces. The swing direction is a tangent vector
//      parallel-transported (Levi-Civita) around the circle of latitude as the
//      Earth carries the pendulum around once a day. We transport it numerically.
//      Read relative to the ground you stand on (the local east/north frame) it
//      comes back rotated by exactly 2π·sinφ — the observed precession itself,
//      the holonomy of the tangent cone unrolled flat. Its complement to a full
//      turn, 2π − 2π·sinφ = 2π(1 − sinφ), is the solid angle of the cap above
//      latitude φ: the same plane's rotation measured against the fixed stars.
//
//   And the honest reconciliation (D): per Earth-turn the ground-relative
//   precession 2π·sinφ (A,B) and the star-relative holonomy 2π(1−sinφ) (C) are
//   complementary — they sum to 2π, one whole turn of the Earth. Neither is
//   "the" answer; they are the same turn, split by latitude.
//
//   Then (E) the real Paris numbers, straight from the law.
//
//   node research/watch-the-earth-turn/verify.mjs
//
// Pure Node, no deps. Exit code is nonzero if any check fails.

const g = 9.80665;                 // standard gravity, m/s^2
const T_SIDEREAL = 86164.0905;     // sidereal day, seconds (23h 56m 04.0905s)
const OMEGA = (2 * Math.PI) / T_SIDEREAL; // Earth's rotation rate, rad/s

let fails = 0;
const approx = (a, b, tol = 1e-9) =>
  Math.abs(a - b) <= tol * Math.max(1, Math.abs(a), Math.abs(b));
const ok = (name, cond, extra = "") => {
  if (!cond) fails++;
  console.log(`${cond ? "  ok" : "FAIL"}  ${name}${extra ? "   " + extra : ""}`);
};
const sec = (t) => console.log("\n" + t);
const deg = (r) => (r * 180) / Math.PI;
const rad = (d) => (d * Math.PI) / 180;

// ==========================================================================
sec("A. The closed form — the precession factor is e^{-iωt}, ω = Ω·sinφ");

// z̈ + 2iω ż + ω₀² z = 0 has solution z = e^{-iωt}(C₁e^{iω'} + C₂e^{-iω'}),
// ω' = √(ω₀²+ω²). The bracket is a plane oscillation; e^{-iωt} rotates it at
// rate ω. So the plane precesses at exactly ω = Ω·sinφ, whatever ω₀. We verify
// the ansatz satisfies the ODE symbolically-by-sampling: plug it in and confirm
// the residual is zero to machine precision at many t.
{
  const omega = 0.017; // any ω
  const w0 = 0.4;      // any pendulum frequency
  const wp = Math.sqrt(w0 * w0 + omega * omega);
  // z(t) = e^{-iωt}(cos(ω't))  [C1=C2=1/2] — a line-swing, released from rest
  const C = (t) => {
    const e = { re: Math.cos(-omega * t), im: Math.sin(-omega * t) };
    const b = Math.cos(wp * t);
    return { re: e.re * b, im: e.im * b };
  };
  // numerical 2nd derivative
  const h = 1e-5;
  let maxres = 0;
  for (const t of [0.3, 1.1, 2.7, 5.0, 9.9]) {
    const zp = C(t + h), zm = C(t - h), z0 = C(t);
    const zdd = { re: (zp.re - 2 * z0.re + zm.re) / (h * h), im: (zp.im - 2 * z0.im + zm.im) / (h * h) };
    const zd = { re: (zp.re - zm.re) / (2 * h), im: (zp.im - zm.im) / (2 * h) };
    // residual = z̈ + 2iω ż + ω₀² z  (i·w means rotate by +90°: i*(a+bi)= -b + ai)
    const i_zd = { re: -zd.im, im: zd.re };
    const res = {
      re: zdd.re + 2 * omega * i_zd.re + w0 * w0 * z0.re,
      im: zdd.im + 2 * omega * i_zd.im + w0 * w0 * z0.im,
    };
    maxres = Math.max(maxres, Math.hypot(res.re, res.im));
  }
  ok(`e^{-iωt}·cos(ω't) solves z̈ + 2iω ż + ω₀² z = 0 (residual ≈ 0)`, maxres < 1e-4,
     `max|res|=${maxres.toExponential(2)}`);
  ok(`precession rate = ω = Ω·sinφ is independent of ω₀ (ω' only shifts the swing frequency)`,
     approx(wp, Math.sqrt(w0 * w0 + omega * omega), 1e-12));
}

// ==========================================================================
sec("B. The simulation — integrate the bob, MEASURE the drift of the swing line");

// RK4 on the real system:  ẍ = -ω₀²x + 2ω ẏ ,  ÿ = -ω₀²y - 2ω ẋ .
// Released from rest at (A,0). We detect turning points (speed minima) and read
// the azimuth of the swing line there; its steady drift is the precession rate.
// To keep the drift measurable in a short run we use an exaggerated Ω_test — the
// LAW rate = Ω·sinφ holds for any Ω, and Part E uses the real Ω.
function simulatePrecession(phiDeg, w0, OmegaTest, nTurns = 400) {
  const omega = OmegaTest * Math.sin(rad(phiDeg));
  const deriv = (s) => {
    const [x, y, vx, vy] = s;
    return [vx, vy, -w0 * w0 * x + 2 * omega * vy, -w0 * w0 * y - 2 * omega * vx];
  };
  const rk4 = (s, dt) => {
    const k1 = deriv(s);
    const k2 = deriv(s.map((v, i) => v + (dt / 2) * k1[i]));
    const k3 = deriv(s.map((v, i) => v + (dt / 2) * k2[i]));
    const k4 = deriv(s.map((v, i) => v + dt * k3[i]));
    return s.map((v, i) => v + (dt / 6) * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]));
  };
  let s = [1, 0, 0, 0];
  const period = (2 * Math.PI) / w0;
  const dt = period / 2000;
  const turns = []; // {t, azimuth}
  let prevSpeed = Infinity, speedWasFalling = false, t = 0;
  const tMax = nTurns * (period / 2) * 1.2;
  let pprev = null, prev = null;
  while (turns.length < nTurns && t < tMax) {
    const sNext = rk4(s, dt);
    const speed = Math.hypot(sNext[2], sNext[3]);
    // turning point = local minimum of speed (bob momentarily near the end of a swing)
    if (prev !== null && pprev !== null) {
      const sp0 = Math.hypot(pprev[2], pprev[3]);
      const sp1 = Math.hypot(prev[2], prev[3]);
      const sp2 = speed;
      if (sp1 < sp0 && sp1 < sp2) {
        // azimuth of the swing line at the turning point (position direction), mod π
        let az = Math.atan2(prev[1], prev[0]);
        turns.push({ t: t, az });
      }
    }
    pprev = prev; prev = sNext; s = sNext; t += dt;
  }
  // unwrap azimuth mod π (a line has period π), then linear-fit slope vs time
  const uw = [];
  let off = 0;
  for (let i = 0; i < turns.length; i++) {
    let a = turns[i].az;
    if (i > 0) {
      let d = a + off - uw[i - 1];
      while (d > Math.PI / 2) { off -= Math.PI; d = a + off - uw[i - 1]; }
      while (d < -Math.PI / 2) { off += Math.PI; d = a + off - uw[i - 1]; }
    }
    uw.push(a + off);
  }
  // least-squares slope
  const n = turns.length;
  let st = 0, sa = 0, stt = 0, sta = 0;
  for (let i = 0; i < n; i++) { st += turns[i].t; sa += uw[i]; stt += turns[i].t * turns[i].t; sta += turns[i].t * uw[i]; }
  const slope = (n * sta - st * sa) / (n * stt - st * st);
  return { measured: slope, expected: -omega }; // e^{-iωt} ⇒ azimuth drifts at -ω
}
{
  const OmegaTest = 0.03; // exaggerated Earth-rate so drift is measurable fast
  for (const [phi, w0] of [[48.8566, 0.383], [30, 0.383], [60, 0.9], [45, 0.383]]) {
    const r = simulatePrecession(phi, w0, OmegaTest);
    const predicted = -OmegaTest * Math.sin(rad(phi));
    ok(`φ=${phi}°, ω₀=${w0}: measured drift ${r.measured.toExponential(4)} rad/s ≈ -Ω·sinφ = ${predicted.toExponential(4)}`,
       approx(r.measured, predicted, 3e-3),
       `ratio=${(r.measured / predicted).toFixed(4)}`);
  }
  // independence of ω₀: two frequencies at the same latitude give the same rate
  const a1 = simulatePrecession(45, 0.383, OmegaTest);
  const a2 = simulatePrecession(45, 1.2, OmegaTest);
  ok(`same latitude, different ω₀ (0.383 vs 1.2) → same precession rate`,
     approx(a1.measured, a2.measured, 3e-3), `${a1.measured.toExponential(4)} vs ${a2.measured.toExponential(4)}`);
}

// ==========================================================================
sec("C. The geometry — parallel transport around the latitude circle");

// Transport a unit tangent vector around latitude φ on the unit sphere by the
// exact geodesic (minimal-rotation) step between neighbouring points, and read
// off its net rotation relative to the local east/north geographic frame (the
// ground you stand on). That rotation is the holonomy of the tangent cone
// unrolled flat, and it comes out to exactly 2π·sinφ — the observed Foucault
// precession per Earth-turn. Its complement, 2π − 2π·sinφ = 2π(1 − sinφ), is
// the solid angle of the cap above φ (the same plane's rotation vs. the stars).
function rotateAbout(v, axis, ang) {
  // Rodrigues' rotation of v about unit `axis` by `ang`
  const [ax, ay, az] = axis, [vx, vy, vz] = v;
  const c = Math.cos(ang), s = Math.sin(ang);
  const dot = ax * vx + ay * vy + az * vz;
  const cx = ay * vz - az * vy, cy = az * vx - ax * vz, cz = ax * vy - ay * vx;
  return [
    vx * c + cx * s + ax * dot * (1 - c),
    vy * c + cy * s + ay * dot * (1 - c),
    vz * c + cz * s + az * dot * (1 - c),
  ];
}
function holonomy(phiDeg, N = 200000) {
  const phi = rad(phiDeg);
  const cf = Math.cos(phi), sf = Math.sin(phi);
  const P = (lam) => [cf * Math.cos(lam), cf * Math.sin(lam), sf];         // point on sphere
  const east = (lam) => [-Math.sin(lam), Math.cos(lam), 0];               // local east
  const north = (lam) => [-sf * Math.cos(lam), -sf * Math.sin(lam), cf];  // local north
  // start: V = local east at λ=0
  let V = east(0);
  let psiPrev = 0, psiTotal = 0;
  for (let k = 1; k <= N; k++) {
    const lam0 = (2 * Math.PI * (k - 1)) / N;
    const lam1 = (2 * Math.PI * k) / N;
    const a = P(lam0), b = P(lam1);
    // minimal rotation carrying normal a→b (great-circle step), applied to V
    let axis = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
    const an = Math.hypot(axis[0], axis[1], axis[2]);
    if (an > 1e-15) {
      axis = axis.map((c) => c / an);
      const ang = Math.acos(Math.max(-1, Math.min(1, a[0] * b[0] + a[1] * b[1] + a[2] * b[2])));
      V = rotateAbout(V, axis, ang);
    }
    // angle of V in the geographic frame at lam1
    const e = east(lam1), n = north(lam1);
    const ve = V[0] * e[0] + V[1] * e[1] + V[2] * e[2];
    const vn = V[0] * n[0] + V[1] * n[1] + V[2] * n[2];
    let psi = Math.atan2(vn, ve);
    // unwrap
    let d = psi - psiPrev;
    while (d > Math.PI) d -= 2 * Math.PI;
    while (d < -Math.PI) d += 2 * Math.PI;
    psiTotal += d;
    psiPrev = psi;
  }
  return psiTotal; // net rotation of V relative to the geographic (ground) frame over one loop
}
{
  for (const phi of [15, 30, 45, 48.8566, 60, 80]) {
    const groundTurn = Math.abs(holonomy(phi));           // rotation vs. the ground
    const ground = 2 * Math.PI * Math.sin(rad(phi));      // predicted Foucault precession / turn
    const solid = 2 * Math.PI * (1 - Math.sin(rad(phi))); // solid angle of the cap above phi
    // (1) parallel transport read against the ground gives the observed precession, 2*pi*sin(phi)
    ok(`phi=${phi}deg: transport vs. ground = ${deg(groundTurn).toFixed(3)}deg ~ 2pi*sinphi = ${deg(ground).toFixed(3)}deg (the precession)`,
       approx(groundTurn, ground, 2e-3), `d=${deg(Math.abs(groundTurn - ground)).toExponential(2)}deg`);
    // (2) its complement to a full turn is the cap's solid angle, 2*pi*(1-sin phi) — vs. the stars
    ok(`   complement 2pi - ${deg(groundTurn).toFixed(2)}deg = ${deg(2 * Math.PI - groundTurn).toFixed(3)}deg ~ solid angle 2pi(1-sinphi) = ${deg(solid).toFixed(3)}deg (vs. stars)`,
       approx(2 * Math.PI - groundTurn, solid, 2e-3));
  }
  // the equator is a geodesic: read against the ground the vector never turns —
  // no precession at the equator, exactly as 2*pi*sin(0) = 0 demands.
  const hEq = Math.abs(holonomy(0.0001));
  ok(`equator is a geodesic: transport vs. ground ~ 0deg -> no precession there (2pi*sin0 = 0)`,
     hEq < 2e-3, `${deg(hEq).toFixed(4)}deg`);
}

// ==========================================================================
sec("D. The reconciliation — ground-relative + star-relative = one Earth turn");

// Per sidereal day the swing plane turns 2π·sinφ relative to the ground (A,B)
// and 2π(1−sinφ) relative to the stars (C). They are complementary: their sum
// is 2π — exactly one turn of the Earth. Neither is the whole answer.
{
  let allSum = true;
  for (const phi of [0, 15, 30, 45, 48.8566, 60, 75, 90]) {
    const ground = 2 * Math.PI * Math.sin(rad(phi));      // Foucault precession / day
    const stars = 2 * Math.PI * (1 - Math.sin(rad(phi))); // holonomy / day
    if (!approx(ground + stars, 2 * Math.PI, 1e-12)) allSum = false;
  }
  ok(`for every latitude:  2π·sinφ (ground)  +  2π(1−sinφ) (stars)  =  2π  (one Earth turn)`, allSum);
  // the two clean poles of the split
  ok(`  pole (φ=90°): ground 360°/day (full precession), stars 0° (plane fixed among the stars)`,
     approx(2 * Math.PI * Math.sin(rad(90)), 2 * Math.PI) && approx(2 * Math.PI * (1 - Math.sin(rad(90))), 0));
  ok(`  equator (φ=0°): ground 0° (no precession), stars 360°/day (plane rides around with the Earth)`,
     approx(2 * Math.PI * Math.sin(rad(0)), 0) && approx(2 * Math.PI * (1 - Math.sin(rad(0))), 2 * Math.PI));
}

// ==========================================================================
sec("E. The real numbers — Foucault's Paris pendulum, straight from the law");

{
  // Earth's rotation rate
  ok(`Earth's sidereal rotation rate Ω = 2π/(23h56m04s) = ${OMEGA.toExponential(5)} rad/s`,
     approx(OMEGA, 7.2921e-5, 1e-3), `${OMEGA.toExponential(6)}`);

  const phiParis = 48.8566; // Panthéon, Paris
  const rateRadPerS = OMEGA * Math.sin(rad(phiParis));
  const rateDegPerHr = deg(rateRadPerS) * 3600;
  ok(`Paris (φ=48.857°N): precession rate = Ω·sinφ = ${rateDegPerHr.toFixed(2)}°/hour ≈ 11.3°/hr`,
     approx(rateDegPerHr, 11.3, 0.02), `${rateDegPerHr.toFixed(3)}°/hr`);

  const fullTurnHr = 360 / rateDegPerHr;
  const viaFormula = (T_SIDEREAL / Math.sin(rad(phiParis))) / 3600;
  ok(`Paris full-turn "pendulum day" = 360/(11.3°/hr) = ${fullTurnHr.toFixed(2)} h ≈ 31.8 h`,
     approx(fullTurnHr, 31.8, 0.02), `${fullTurnHr.toFixed(3)} h`);
  ok(`  and equals sidereal-day / sinφ = ${viaFormula.toFixed(3)} h (same number two ways)`,
     approx(fullTurnHr, viaFormula, 1e-6));

  // pole and equator limits
  const poleHr = (T_SIDEREAL / Math.sin(rad(90))) / 3600;
  ok(`North Pole: pendulum day = one sidereal day = ${poleHr.toFixed(3)} h (≈ 23.93 h)`,
     approx(poleHr, 23.934, 1e-3));
  ok(`Equator: sinφ = 0 → precession period infinite (the plane never turns)`,
     Math.sin(rad(0)) === 0);

  // the Panthéon pendulum's own swing period, L ≈ 67 m
  const L = 67;
  const swing = 2 * Math.PI * Math.sqrt(L / g);
  ok(`Panthéon wire L=67 m → swing period 2π√(L/g) = ${swing.toFixed(2)} s (≈ 16.4 s)`,
     approx(swing, 16.42, 0.02), `${swing.toFixed(3)} s`);
}

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