// verify.mjs — the show-the-check for "Why a Siren Changes Pitch as It Passes"
// (the immersive stratum at public/strata/doppler-siren/).
//
// The claim the page makes, and what this file proves:
//   1. A passing source's heard pitch drops smoothly between high and low limits.
//      For a close pass the distant notes are nearly steady and the transition
//      is rapid. Sound emitted at closest approach has frequency f0 and is
//      heard b/v later. Closer pass → sharper drop.
//   2. The plateau ratio is exactly (v+vs)/(v−vs), independent of how close the
//      pass is. The drop in semitones is 12·log2((v+vs)/(v−vs)).
//   3. The f0 crossing you HEAR occurs b/v after closest approach: the sound
//      emitted at t_e=0 takes b/v to cross the gap. This is not a claim about
//      the time of the arithmetic midpoint of the high and low frequencies.
//   4. Two independent methods agree to <3e-8 on the observed-frequency curve:
//      (A) the closed form f' = f0 · v / (v + v_r),  v_r = dr/dt_e
//      (B) a from-scratch WAVEFRONT-COUNTING simulation: emit crests at interval
//          1/f0 from the moving source, propagate each at speed v, time their
//          arrivals at the fixed observer, read instantaneous f as 1/(arrival gap).
//      Method B knows nothing of method A's formula — it only emits and propagates.
//
// Run:  node research/doppler-siren/verify.mjs           (human-readable)
//       node research/doppler-siren/verify.mjs --json    (machine, for the page/test)
//
// Constants are stated, not hidden. Speed of sound in dry air at 20°C = 343.0 m/s
// (NIST / standard; 331.3·sqrt(1+T/273.15) gives 343.2 at 20°C — we use 343.0).

const V = 343.0;        // speed of sound in air, m/s (20°C, dry)
const F0 = 1000.0;      // source (siren) frequency, Hz — a round reference tone
const VS = 30.0;        // source speed, m/s (108 km/h ≈ 67 mph — a fast vehicle)
const B = 10.0;         // closest-approach distance (how far the source passes you), m

// --- geometry: source on the x-axis, observer at (0, b); source at x = vs·t_e ---
// distance at emission time t_e:
const r = (te) => Math.hypot(B, VS * te);
// radial velocity dr/dt_e (negative while approaching, t_e<0):
const vr = (te) => (VS * VS * te) / r(te);

// (A) closed-form observed frequency for a wavefront EMITTED at time t_e,
// as a function of that wavefront's RECEPTION time t_r = t_e + r/v.
const fClosed = (te) => F0 * V / (V + vr(te));
const tRecv = (te) => te + r(te) / V;

// plateau limits (te → ∓∞ ⇒ vr → ∓vs):
const fHigh = F0 * V / (V - VS);   // approaching head-on
const fLow  = F0 * V / (V + VS);   // receding tail-on
const ratio = (V + VS) / (V - VS); // = fHigh/fLow, independent of b
const semis = (x) => 12 * Math.log2(x);
const dropSemitones = semis(ratio);

// --- (B) independent wavefront-counting simulation -------------------------------
// Emit a crest every T0 = 1/f0 seconds from the moving source. Crest k is emitted at
// te_k = k·T0 from position (vs·te_k, 0); it reaches the observer at
//   tr_k = te_k + dist(emit position, observer)/v.
// The observed instantaneous frequency between consecutive arrivals is 1/(tr_{k+1}-tr_k).
// This uses ONLY "emit at interval, propagate at v" — no Doppler formula anywhere.
function simulate(teStart, teEnd) {
  const T0 = 1 / F0;
  const arrivals = [];
  // emit crests across the window with a little margin each side
  const kStart = Math.floor(teStart / T0) - 2;
  const kEnd = Math.ceil(teEnd / T0) + 2;
  for (let k = kStart; k <= kEnd; k++) {
    const te = k * T0;
    const xs = VS * te;
    const dist = Math.hypot(xs, B);
    arrivals.push({ te, tr: te + dist / V });
  }
  arrivals.sort((a, b) => a.tr - b.tr);
  // instantaneous observed frequency, time-stamped at the midpoint of each arrival gap
  const samples = [];
  for (let i = 1; i < arrivals.length; i++) {
    const gap = arrivals[i].tr - arrivals[i - 1].tr;
    const tMid = 0.5 * (arrivals[i].tr + arrivals[i - 1].tr);
    samples.push({ tr: tMid, f: 1 / gap, teMid: 0.5 * (arrivals[i].te + arrivals[i - 1].te) });
  }
  return samples;
}

// --- cross-check A vs B on a shared time window ----------------------------------
const TE0 = -3.0, TE1 = 3.0;        // emission-time window (s)
const sim = simulate(TE0, TE1);
// for each simulated sample, compare to the closed form evaluated at the SAME emission
// midpoint (the sim's instantaneous f corresponds to the crest-pair emission midpoint).
let maxRelErr = 0, worst = null, samplesCompared = 0;
for (const s of sim) {
  if (s.teMid < TE0 || s.teMid > TE1) continue;
  samplesCompared++;
  const fc = fClosed(s.teMid);
  const rel = Math.abs(s.f - fc) / fc;
  if (rel > maxRelErr) { maxRelErr = rel; worst = { tr: s.tr, sim: s.f, closed: fc }; }
}

if (samplesCompared !== 6000) throw new Error(`Expected 6000 compared intervals, got ${samplesCompared}`);

// --- the smooth transition between distant limits, measured --------------------
// Sample the closed form densely in RECEPTION time and find the 10%–90% transition.
function curveInReceptionTime(n = 20000) {
  const out = [];
  for (let i = 0; i <= n; i++) {
    const te = TE0 + (TE1 - TE0) * (i / n);
    out.push({ tr: tRecv(te), f: fClosed(te), te });
  }
  out.sort((a, b) => a.tr - b.tr);
  return out;
}
const curve = curveInReceptionTime();
// fraction of the full high→low span covered, vs time
const span = fHigh - fLow;
const frac = (f) => (fHigh - f) / span; // 0 at high plateau, 1 at low plateau
// time at which the curve first crosses 10% and 90% of the drop
let t10 = null, t90 = null, tMid50 = null;
for (const p of curve) {
  const fr = frac(p.f);
  if (t10 === null && fr >= 0.10) t10 = p.tr;
  if (tMid50 === null && fr >= 0.50) tMid50 = p.tr;
  if (t90 === null && fr >= 0.90) { t90 = p.tr; break; }
}
const transitionDuration = t90 - t10;          // seconds the bulk of the drop takes
const totalWindow = TE1 - TE0;                  // seconds we watched (emission window)
const lagPropagation = B / V;                   // reception time of the t_e=0 wavefront = b/v exactly
const f0CrossingRecv = tRecv(0);               // when you hear the te=0 sound; == b/v

// Sound emitted at closest approach has received frequency f0 (vr(0)=0):
const fAtClosest = fClosed(0);

// asymmetry: the high→f0 and f0→low steps differ slightly in semitones
const semisUp = semis(fHigh / F0);     // f0 → fHigh
const semisDown = semis(F0 / fLow);    // fLow → f0

// transition sharpness vs pass distance: rebuild t10..t90 for several b
function transitionFor(b) {
  const rB = (te) => Math.hypot(b, VS * te);
  const vrB = (te) => (VS * VS * te) / rB(te);
  const fcB = (te) => F0 * V / (V + vrB(te));
  const trB = (te) => te + rB(te) / V;
  const pts = [];
  const n = 20000;
  for (let i = 0; i <= n; i++) {
    const te = TE0 + (TE1 - TE0) * (i / n);
    pts.push({ tr: trB(te), f: fcB(te) });
  }
  pts.sort((a, b2) => a.tr - b2.tr);
  let a10 = null, a90 = null;
  for (const p of pts) {
    const fr = (fHigh - p.f) / span;
    if (a10 === null && fr >= 0.10) a10 = p.tr;
    if (fr >= 0.90) { a90 = p.tr; break; }
  }
  return a90 - a10;
}
const sharpnessTable = [2, 5, 10, 30, 60].map((b) => ({ b, transition_s: transitionFor(b) }));

const out = {
  inputs: { v_sound_mps: V, f0_hz: F0, source_speed_mps: VS, source_speed_kmh: VS * 3.6, closest_approach_m: B },
  plateaus: {
    approaching_hz: fHigh,
    receding_hz: fLow,
    from_closest_approach_emission_hz: fAtClosest, // heard at b/v, not t=0
    ratio_high_over_low: ratio,
    drop_semitones: dropSemitones,
    semitones_up_to_high: semisUp,
    semitones_down_to_low: semisDown,
    asymmetry_semitones: Math.abs(semisUp - semisDown),
  },
  structure: {
    transition_10_90_duration_s: transitionDuration,
    total_emission_window_s: totalWindow,
    transition_fraction_of_window: transitionDuration / totalWindow,
    transition_centre_recv_s: tMid50,
    f0_crossing_recv_s: f0CrossingRecv,         // == b/v: you hear "the middle" this late
    propagation_lag_b_over_v_s: lagPropagation,
    sharpness_vs_pass_distance: sharpnessTable,   // closer pass ⇒ shorter transition
  },
  cross_check: {
    method_A: 'closed form  f = f0·v/(v+vr)',
    method_B: 'wavefront-counting sim (emit at 1/f0, propagate at v, 1/arrival-gap)',
    samples_compared: samplesCompared,
    max_relative_error: maxRelErr,
    worst_point: worst,
    agree: maxRelErr < 3e-8,
  },
};

if (process.argv.includes('--json')) {
  console.log(JSON.stringify(out, null, 2));
  process.exit(0);
}

const r3 = (x) => Math.round(x * 1000) / 1000;
console.log(`\n  WHY A SIREN CHANGES PITCH AS IT PASSES: the check\n  ${'='.repeat(54)}`);
console.log(`  Inputs: f0=${F0} Hz · source ${VS} m/s (${r3(VS*3.6)} km/h) · pass distance b=${B} m · v_sound=${V} m/s\n`);
console.log(`  Distant APPROACHING limit : ${r3(fHigh)} Hz   (+${r3(semisUp)} semitones)`);
console.log(`  EMITTED at closest point : ${r3(fAtClosest)} Hz   (= f0; heard b/v later)`);
console.log(`  Distant RECEDING limit    : ${r3(fLow)} Hz   (−${r3(semisDown)} semitones)`);
console.log(`  Total drop high→low       : ${r3(dropSemitones)} semitones, ratio ${r3(ratio)} = (v+vs)/(v−vs)`);
console.log(`  Asymmetry up vs down      : ${r3(out.plateaus.asymmetry_semitones)} semitones (up≠down)\n`);
console.log(`  The drop is smooth: 10%–90% of it happens in ${r3(transitionDuration)} s,`);
console.log(`  i.e. ${r3(100*transitionDuration/totalWindow)}% of the ${r3(totalWindow)} s we watched; outside it the curve approaches its limits.`);
console.log(`  Closer passes are sharper:`);
for (const row of sharpnessTable) console.log(`     b=${String(row.b).padStart(2)} m → drop takes ${r3(row.transition_s)} s`);
console.log(`  You HEAR closest approach (pitch = f0) at t=${r3(f0CrossingRecv*1000)} ms, lagging the`);
console.log(`  source's real nearest moment by exactly b/v = ${r3(lagPropagation*1000)} ms.\n`);
console.log(`  Cross-check (two independent methods):`);
console.log(`     A = closed form,  B = wavefront-counting sim`);
console.log(`     compared ${samplesCompared} samples · max relative error = ${out.cross_check.max_relative_error.toExponential(2)}`);
console.log(`     ${out.cross_check.agree ? 'AGREE to <3e-8 ✓' : 'DISAGREE ✗'}\n`);
process.exit(out.cross_check.agree ? 0 : 1);
