#!/usr/bin/env node
// THE LEVEL AND THE RATE — verifier
//
// A portal across four physics misconceptions (P3 combine). The load-bearing
// claim none of the four member pages states alone:
//
//   The everyday name picks out a LEVEL (a zeroth-order quantity — a temperature,
//   a balance, a force, a motion). But in each case the physics that matters is a
//   RATE: a derivative of something. Read the level where the truth is the rate and
//   you get the famous wrong intuition.
//
//   metal "cold"     = a FLUX,     dE/dt through skin   (q = e·ΔT/√(πt))   — a time-rate
//   Moon "held up"   = an ACCEL,   a = μ/r², never zero                    — a 2nd time-rate
//   the Sun's "tide" = a GRADIENT, dg/dr, differencing 1/r² into 1/r³       — a space-rate
//   the wheel's spin = a SAMPLE,   the aliased fold of dθ/dt                — a sampled rate
//
// This file re-derives the unifying numbers from primary constants, independent of
// the member pages, and asserts the one identity that pins the whole thesis:
//   the level and its derivative are DIFFERENT functions of distance.
// Run: node research/the-level-and-the-rate/verify.mjs   (exit 0 = all green)

let pass = 0, fail = 0;
const approx = (a, b, tol, msg) => {
  const ok = Math.abs(a - b) <= tol;
  console.log(`  ${ok ? 'ok ' : 'FAIL'}  ${msg}   (got ${a}, want ${b} ±${tol})`);
  ok ? pass++ : fail++;
  return ok;
};
const truthy = (cond, msg) => {
  console.log(`  ${cond ? 'ok ' : 'FAIL'}  ${msg}`);
  cond ? pass++ : fail++;
  return cond;
};

console.log('\nTHE LEVEL AND THE RATE — verifier\n');

// ── Primary constants (sourced; see facts.md) ──────────────────────────────
const MU_EARTH = 3.986004418e14;   // m^3/s^2  (GM_earth, IERS/JPL)
const R_EARTH  = 6.371e6;          // m        (volumetric mean, NASA)
const M_SUN    = 1.98892e30;       // kg       (NASA Sun fact sheet)
const M_MOON   = 7.342e22;         // kg       (NASA Moon fact sheet)
const D_MOON   = 3.84399e8;        // m        (mean Earth–Moon distance)
const D_SUN    = 1.495979e11;      // m        (1 au)

// ═══ RUNG 1 — TIDE: the level is 1/r², the rate (gradient) is 1/r³ ═══════════
// A body of mass M at distance d exerts:
//   PULL (the force, the LEVEL)      ∝ M / d²
//   TIDE (the gradient of the force) ∝ M / d³   — because differencing 1/r² adds a power of 1/r
console.log('RUNG 1 — the Sun pulls harder yet raises the smaller tide');
const distRatio = D_SUN / D_MOON;                                  // Sun is this many × farther
const pullRatio = (M_SUN / M_MOON) * (D_MOON / D_SUN) ** 2;        // level  ∝ M/d²
const tideRatio = (M_SUN / M_MOON) * (D_MOON / D_SUN) ** 3;        // rate   ∝ M/d³
approx(distRatio, 389.2, 0.5, 'the Sun is ~389× farther than the Moon');
approx(pullRatio, 178.9, 0.6, 'the Sun pulls ~179× harder than the Moon (the LEVEL, ∝1/d²)');
approx(tideRatio, 0.46, 0.01, "the Sun raises only ~0.46× the Moon's tide (the RATE, ∝1/d³)");
// THE IDENTITY that pins the thesis: tide = pull / distance.
// One extra power of 1/d separates the level from its own gradient, so the same
// extra factor of 389 turns "179× stronger" into "0.46× weaker".
approx(tideRatio, pullRatio / distRatio, 1e-9,
  'IDENTITY: tideRatio = pullRatio / distRatio — the level and its gradient are different functions of d');
truthy(pullRatio > 1 && tideRatio < 1,
  'the same body is BOTH the stronger pull AND the weaker tide — only possible if level ≠ rate');

// And demonstrate the exponents directly: numerically differentiate g(r)=μ/r²
// and confirm the LEVEL falls as r^-2 while its RATE (|dg/dr|) falls as r^-3.
const g = (r) => MU_EARTH / (r * r);
const dgdr = (r) => { const h = r * 1e-6; return (g(r + h) - g(r - h)) / (2 * h); };
const slope = (f, r1, r2) => Math.log(Math.abs(f(r2)) / Math.abs(f(r1))) / Math.log(r2 / r1);
approx(slope(g,    1e8, 1e9), -2, 0.001, 'the force g(r) scales as r^-2 (the LEVEL)');
approx(slope(dgdr, 1e8, 1e9), -3, 0.001, 'its gradient dg/dr scales as r^-3 (the RATE) — one power steeper');

// ═══ RUNG 2 — METAL: the level (temperature) is held EQUAL; the rate is all ═══
// Both blocks sit at the SAME room temperature. What your skin reads is the
// contact temperature T_c, set by effusivity e=√(kρc) — a transport RATE, not a level.
//   T_c = (e_skin·T_skin + e_mat·T_mat) / (e_skin + e_mat)
console.log('\nRUNG 2 — same temperature, opposite feel (the rate is effusivity)');
const T_SKIN = 33, T_ROOM = 21;     // °C — finger ~33, both blocks at room 21
// effusivities verified in research/why-metal-feels-colder/verify.mjs (e = √(kρc)):
const e = { copper: 37193, oak: 466, foam: 33, skin: 1176 };
const contact = (mat) => (e.skin * T_SKIN + e[mat] * T_ROOM) / (e.skin + e[mat]);
approx(contact('copper'), 21.37, 0.02, 'copper drives the interface to 21.37 °C (skin plunges ~11.6 °C)');
approx(contact('oak'),    29.60, 0.02, 'oak barely moves it: 29.60 °C (skin dips ~3.4 °C)');
approx(contact('foam'),   32.67, 0.02, 'foam stays at 32.67 °C — almost skin-warm');
truthy(Math.abs(T_ROOM - T_ROOM) < 1e-12,
  'the LEVEL is identical for all three blocks (all at 21 °C) — every felt difference is the rate');
approx(e.copper / e.oak, 79.8, 0.5,
  'the RATE (effusivity) ranges ~80× across blocks that share one temperature');

// ═══ RUNG 3 — MOON: there is no level (no balance); only rates ═══════════════
// "Held up" implies a static balance (net force 0). The truth is a constant,
// fully-unbalanced acceleration — a pure second time-derivative of position.
console.log('\nRUNG 3 — the Moon is always falling (the acceleration never vanishes)');
const aMoon = MU_EARTH / (D_MOON * D_MOON);            // m/s^2, inward, never zero
const dropPerSec = 0.5 * aMoon * 1 * 1;                // ½at² over t=1s
const vCirc = Math.sqrt(MU_EARTH / D_MOON);            // sideways speed
const gSurface = MU_EARTH / (R_EARTH * R_EARTH);
approx(aMoon * 1e3, 2.698, 0.01, 'gravity at the Moon = 2.698e-3 m/s² — small, but NOT zero');
approx(dropPerSec * 1e3, 1.35, 0.01, 'the Moon falls 1.35 mm toward Earth every second');
approx(vCirc, 1018, 3, '...while sliding ~1018 m sideways, so the ground curves away by the same 1.35 mm');
approx((aMoon / gSurface) * 100, 0.0275, 0.001, 'g at the Moon is 0.0275% of surface gravity — present, unbalanced');
truthy(aMoon > 0, 'the net inward acceleration is never zero: there is no balance to read, only a rate');

// ═══ RUNG 4 — WHEEL: the rate is real but UNDERSAMPLED, so it lies ═══════════
// The mirror case. Here the eye DOES read a rate (the spin), but film delivers
// discrete frames, and a rate above the Nyquist limit folds to an alias.
//   apparent = f_eff − fs·round(f_eff/fs),   f_eff = S · f_rot
console.log('\nRUNG 4 — the backward wheel (a rate the frames cannot carry)');
const fs = 24;             // frames per second (classic film)
const S  = 12;             // spokes (12-fold symmetry)
const alias = (frot) => { const fEff = S * frot; return fEff - fs * Math.round(fEff / fs); };
approx(alias(2.0), 0, 1e-9, 'at 2.0 rev/s the wheel appears FROZEN (spoke freq 24 = fs)');
truthy(alias(1.9) < 0, 'at 1.9 rev/s — turning forward — the wheel appears to spin BACKWARD');
approx(alias(1.9), -1.2, 1e-9, 'the apparent (aliased) spoke frequency is −1.2 Hz: a real percept of a reversal that is not happening');
const nyquist = fs / (2 * S);
approx(nyquist, 1.0, 1e-9, 'faithful only below the Nyquist rate: f_rot < fs/(2S) = 1.0 rev/s');
truthy(1.9 > nyquist, 'the deceiving spin (1.9) sits above Nyquist — undersampled, so the recovered rate is an alias');

// ── The unifying statement, asserted across all four ───────────────────────
console.log('\nTHE SPINE — four "static" nouns, four rates:');
console.log('  cold  = a flux     (dE/dt)        wood and metal share one temperature');
console.log('  orbit = an accel   (d²x/dt²)      the Moon shares the cannonball\'s fall');
console.log('  tide  = a gradient (dg/dr)        the Sun shares the Moon\'s inverse-square law');
console.log('  spin  = a sample   (aliased dθ/dt) the frame shares the wheel\'s true rotation');

console.log(`\n${pass}/${pass + fail} checks passed.${fail ? '  ✗ FAILURES ABOVE' : ''}\n`);
process.exit(fail ? 1 : 0);
