#!/usr/bin/env node
// verify.mjs — checks the relativity-of-simultaneity engine the tool runs.
//
// Imports the SAME module the browser page imports
// (public/strata/the-slice-you-call-now/engine.js), so a green run here certifies
// the numbers a visitor sees. The anchors are the exact structure of the Lorentz
// transform, the EXACT simultaneity offset Δt = vD/c², the causal asymmetry
// (spacelike pairs can be re-sorted, timelike pairs never), and Penrose's
// Andromeda numbers.
//
// Run:  node research/simultaneity/verify.mjs

import {
  CONST, gamma, boost, addVel,
  simultaneityOffset, offsetFromWalk, simSlope, worldlineSlope,
  separation, simultaneityBoost, judge, andromedaDays, ANDROMEDA_LY,
} from '../../public/strata/the-slice-you-call-now/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})`);
const close = (a, b, rel, m) => ok(Math.abs(a - b) <= rel * Math.max(1, Math.abs(a), Math.abs(b)), `${m}  (got ${a}, want ${b})`);

const c = CONST.c;
console.log('The Slice You Call Now — relativity-of-simultaneity engine, verifier\n');

// ── 0. constants are the defined values ──────────────────────────────────────
console.log('0. constants');
ok(c === 299792458, 'c is the exact SI value');
close(CONST.LY, 9.4607304725808e15, 1e-12, '1 light-year = c × Julian year (exact)');
close(CONST.YEAR, 31557600, 1e-12, 'Julian year = 365.25 d in seconds');

// ── 1. the Lorentz transform has the right structure ─────────────────────────
console.log('1. the Lorentz transform');
{
  ok(gamma(0) === 1, 'γ(0) = 1');
  ok(gamma(0.6) > 1, 'γ(β>0) > 1');
  close(gamma(0.6), 1.25, 1e-12, 'γ(0.6) = 5/4 (the 3-4-5 boost)');
  close(gamma(0.8), 5 / 3, 1e-12, 'γ(0.8) = 5/3');

  // β=0 is the identity
  const e = { t: 7, x: 3e8 };
  const z = boost(e, 0);
  close(z.t, e.t, 1e-12, 'β=0 leaves t unchanged');
  close(z.x, e.x, 1e-12, 'β=0 leaves x unchanged');

  // the invariant interval s² = (ct)² − x² is preserved by ANY boost
  const beta = 0.42;
  const before = (c * e.t) ** 2 - e.x ** 2;
  const b = boost(e, beta);
  const after = (c * b.t) ** 2 - b.x ** 2;
  close(after, before, 1e-9, 'boost preserves the invariant interval (ct)²−x²');

  // boosting by β then by −β returns the original event (group inverse)
  const round = boost(boost(e, beta), -beta);
  close(round.t, e.t, 1e-9, 'boost(β) then boost(−β) returns the event (t)');
  close(round.x, e.x, 1e-9, 'boost(β) then boost(−β) returns the event (x)');

  // composing two boosts = a single boost at the relativistically-added velocity
  const b1 = 0.5, b2 = 0.5;
  const composed = boost(boost(e, b1), b2);
  const single = boost(e, addVel(b1, b2));
  close(composed.t, single.t, 1e-9, 'two boosts compose to addVel(β1,β2) (t)');
  close(composed.x, single.x, 1e-9, 'two boosts compose to addVel(β1,β2) (x)');
  close(addVel(0.5, 0.5), 0.8, 1e-12, '0.5c ⊕ 0.5c = 0.8c, not c (velocities never reach c)');
  ok(addVel(1, 1) === 1, 'c ⊕ c = c (light has no preferred frame)');
}

// ── 2. the simultaneity slice: Δt = vD/c², EXACT ─────────────────────────────
console.log('2. the slice — Δt = vD/c²');
{
  // a moving observer's now-slice (t'=0) at rest distance D sits, in the rest
  // frame, at t = βD/c. Confirm the engine's closed form equals the value the
  // full boost assigns — i.e. boosting the event (βD/c, D) lands exactly at t'=0.
  const beta = 0.3, D = 4e20;
  const dt = simultaneityOffset(beta, D);
  close(dt, (beta * D) / c, 1e-12, 'offset = βD/c by construction');
  const tp = boost({ t: dt, x: D }, beta).t;
  ok(Math.abs(tp) < 1e-6, 'that event really is "now" for the moving observer (t′≈0)');

  // exact linearity: double the speed or the distance ⇒ double the offset
  close(simultaneityOffset(2 * beta / 1, D), 2 * simultaneityOffset(beta, D), 1e-12, 'offset ∝ velocity');
  close(simultaneityOffset(beta, 2 * D), 2 * simultaneityOffset(beta, D), 1e-12, 'offset ∝ distance');

  // sign: moving toward the place (β>0) pushes the slice into the rest future
  ok(simultaneityOffset(0.1, D) > 0 && simultaneityOffset(-0.1, D) < 0, 'sign flips with direction of motion');
  ok(simultaneityOffset(0, D) === 0, 'standing still ⇒ no offset (you and the rest frame share a now)');

  // the diagram slopes scissor symmetrically about the 45° light line and never reach it
  const bt = 0.5;
  close(simSlope(bt) * worldlineSlope(bt), 1, 1e-12, 'now-line and worldline are reflections in ct=x (slopes reciprocal)');
  ok(simSlope(0.999999) < 1, 'the now-line slope (β) never reaches the light line (1)');
}

// ── 3. causality: only spacelike pairs can be re-sorted ──────────────────────
console.log('3. what the tilt can and cannot re-order');
{
  // a TIMELIKE pair (a cause and its effect): Δx small, cΔt large.
  const cause  = { t: 0,    x: 0 };
  const effect = { t: 1,    x: 1e7 };           // light could cover 3e8 m in 1 s ⟹ inside the cone
  const sepT = separation(cause, effect);
  ok(sepT.kind === 'timelike', 'cause→effect (reachable by light) is timelike');
  ok(simultaneityBoost(cause, effect) === null, 'no physical boost makes a timelike pair simultaneous');
  // its time-order is the SAME in every frame: scan β and check effect stays later
  let everReversed = false;
  for (let b = -0.999; b <= 0.999; b += 0.0123) {
    const a = boost(cause, b).t, d = boost(effect, b).t;
    if (d <= a) everReversed = true;
  }
  ok(!everReversed, 'every observer agrees the effect is after the cause (causal order is absolute)');

  // a SPACELIKE pair (two distant events): Δx large, cΔt small.
  const here  = { t: 0,   x: 0 };
  const there = { t: 0.5, x: 1e9 };             // 1e9 m in 0.5 s ⟹ faster than light to connect ⟹ outside cone
  const sepS = separation(here, there);
  ok(sepS.kind === 'spacelike', 'two causally-disconnected events are spacelike');
  const bSim = simultaneityBoost(here, there);
  ok(bSim !== null && Math.abs(bSim) < 1, 'a real boost makes the spacelike pair simultaneous');
  // and that boost really zeroes their time-gap
  ok(Math.abs(boost(here, bSim).t - boost(there, bSim).t) < 1e-9, 'at that boost the two events are genuinely simultaneous');
  // a slightly bigger boost reverses their order — the order is frame-dependent
  const before = boost(there, 0).t - boost(here, 0).t;
  const after  = boost(there, bSim + 0.2).t - boost(here, bSim + 0.2).t;
  ok(Math.sign(before) !== Math.sign(after), 'past the equalizing boost, the spacelike order flips — "now" was a choice');

  // judge(): a spacelike event changes category with β; a timelike one never does.
  // Sign: moving TOWARD the event (β>0, event at +x) tips your now-slice past it
  // into that region's future, so a fixed rest-"now" event there falls into your
  // PAST; moving away, it is still in your future. (Equivalently: the walker
  // toward Andromeda already calls "now" events the stationary person calls
  // future — Penrose's launched fleet.)
  const spaceEv = { t: 0, x: 2e9 };
  ok(judge(spaceEv, 0) === 'now' && judge(spaceEv, 0.3) === 'past' && judge(spaceEv, -0.3) === 'future',
     'the same far event is past, now, or future depending only on how you move');
  ok(judge(effect, 0) === 'future' && judge(effect, 0.9) === 'future' && judge(effect, -0.9) === 'future',
     'a future-cone event is in everyone’s future, however they move');
}

// ── 4. Penrose's Andromeda paradox, the headline numbers ─────────────────────
console.log('4. the Andromeda paradox (Penrose 1989)');
{
  close(ANDROMEDA_LY, 2.495e6, 1e-9, 'Andromeda taken at 2.495 million ly (Riess et al. 2012: 765 ± 28 kpc)');
  // a 1.4 m/s stroll toward Andromeda: "several days" of its history re-sorted
  const days = andromedaDays(1.4, ANDROMEDA_LY);
  near(days, 3.5, 5.0, 'a 1.4 m/s stroll ⇒ ≈ 4 days’ offset on Andromeda (Penrose’s "several days")');
  // a slow 1 m/s walk ⇒ ~3 days
  near(andromedaDays(1.0, ANDROMEDA_LY), 2.8, 3.4, 'a 1 m/s walk ⇒ ≈ 3.1 days');
  // two people walking PAST each other (toward / away) double the gap between THEM
  const apart = andromedaDays(1.4, ANDROMEDA_LY) - andromedaDays(-1.4, ANDROMEDA_LY);
  near(apart, 7.0, 10.0, 'two strollers passing in opposite directions disagree by ≈ 8 days');
  // scale sanity from first principles: Δt = vD/c²
  const D = ANDROMEDA_LY * CONST.LY;
  close(offsetFromWalk(1.4, ANDROMEDA_LY), (1.4 * D) / c ** 2, 1e-9, 'the readout is exactly v·D/c²');
  // standing still: no offset
  ok(andromedaDays(0, ANDROMEDA_LY) === 0, 'stand still and your Andromeda-now matches the rest frame');
  // monotonic in distance: the same walk re-sorts more time the farther the place
  ok(offsetFromWalk(1.4, 1) < offsetFromWalk(1.4, ANDROMEDA_LY), 'farther place ⇒ bigger offset for the same walk');
}

// ── 5. the reachable range the tool sweeps (sanity on each preset) ────────────
console.log('5. the slider range');
{
  // across-a-room (3 m) at a walk: utterly negligible — femtoseconds. Honest: the
  // effect is real at every distance, just unmeasurably small until astronomical.
  const room = offsetFromWalk(1.4, 3 / CONST.LY);   // 3 m expressed in ly
  ok(room > 0 && room < 1e-15, 'across a room the offset is real but sub-femtosecond (you share a now, for all practical purposes)');
  // the Sun (1 AU ≈ 8.317 light-minutes): a walk ⇒ microseconds
  const sun = offsetFromWalk(1.4, (1.495978707e11) / CONST.LY);
  near(sun * 1e6, 2.0, 2.7, 'toward the Sun, a 1.4 m/s walk shifts your now by ≈ 2.3 µs');
  // monotone increase with distance across the presets
  const dists = [3 / CONST.LY, 1.495978707e11 / CONST.LY, 4.2465, 26000, ANDROMEDA_LY];
  let mono = true;
  for (let i = 1; i < dists.length; i++) if (offsetFromWalk(1.4, dists[i]) <= offsetFromWalk(1.4, dists[i - 1])) mono = false;
  ok(mono, 'the offset grows monotonically room → Sun → Proxima → galactic centre → Andromeda');
}

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