#!/usr/bin/env node
// verify-why-stopping-distance-quadruples.mjs
//
// Offline gate for /strata/why-stopping-distance-quadruples/. It recomputes EVERY number the
// page shows, from nothing but v^2 = u^2 - 2*a*d (the work-energy theorem for a constant
// braking force) and unit conversions, and exits 0 only if all checks pass. Where possible each
// fact is verified two independent ways (e.g. the Highway Code cells from the imperial generating
// rule AND from SI kinematics).
//
// The physics (one honest two-term formula):
//   total stopping distance  D = reaction distance + braking distance
//                              = v * t_r            (LINEAR in speed)
//                              + v^2 / (2*a)        (QUADRATIC in speed)
//   residual speed at a point where a slower car has stopped (braking-only frame, common start):
//                              w = sqrt(v^2 - u^2)  (friction/a CANCELS: no mu in it)
//
// Sources verified 2026-07-17:
//   UK Highway Code, Rule 126 "Typical stopping distances" (gov.uk; DVSA chart PDF, asset 2024):
//     thinking ft = mph, braking ft = mph^2/20  ->  metric cells
//     20:6+6=12  30:9+14=23  40:12+24=36  50:15+38=53  60:18+55=73  70:21+75=96  (m)
//     "gap should be at least doubled on wet roads and up to ten times greater on icy roads".
//   FHWA, "Speed Concepts: Informational Guide", Ch.4, summarizing AASHTO Green Book SSD:
//     perception-reaction time 2.5 s (exceeds the 90th-percentile driver), deceleration 11.2 ft/s^2 [0.35g].
//
// Run:  node research/why-stopping-distance-quadruples/verify-why-stopping-distance-quadruples.mjs

'use strict';

// ---- constants (identical to the page's inline JS) --------------------------------
const G      = 9.81;        // m/s^2
const MPH_MS = 0.44704;     // m/s per mph  (exact: 1609.344/3600)
const FT_M   = 0.3048;      // m per ft     (exact)

// Highway Code implied constants, DERIVED from its own generating rule:
//   metric thinking distance = 0.3 m per mph  ->  t_r = 0.3 / (mph in m/s)
//   imperial braking = mph^2/20 ft            ->  a from v^2 = 2*a*d
const TR_HC  = 0.3 / MPH_MS;                       // = 0.67108 s  ("Highway Code driver")
const DRY_A  = (MPH_MS * MPH_MS) / (2 * (FT_M / 20)); // = 6.5566 m/s^2 (0.669 g)

// surfaces: deceleration (m/s^2). wet = half of dry (Code: double the gap); ice = a tenth (x10).
const A_DRY   = DRY_A;          // 6.556  (0.669 g)
const A_WET   = DRY_A / 2;      // 3.278  (0.334 g)
const A_ICE   = DRY_A / 10;     // 0.656  (0.067 g)
const A_AASHTO = 3.4;           // FHWA/AASHTO design deceleration (0.35 g)
const TR_AASHTO = 2.5;          // AASHTO design perception-reaction time (s)

const mps  = (mph) => mph * MPH_MS;          // mph -> m/s
const mph  = (v)   => v / MPH_MS;            // m/s -> mph
const m2ft = (m)   => m / FT_M;             // m   -> ft

// the two-term model
const reactDist = (v_mph, t_r)   => mps(v_mph) * t_r;                 // m
const brakeDist = (v_mph, a)     => mps(v_mph) * mps(v_mph) / (2 * a); // m
const totalDist = (v_mph, t_r, a) => reactDist(v_mph, t_r) + brakeDist(v_mph, a);

// residual speed (braking-only frame): fast car speed where a slower car (u) has stopped, both
// braking from a common start. Independent of a.
const residualBrakingOnly = (v_mph, u_mph) => Math.sqrt(Math.max(0, mps(v_mph) ** 2 - mps(u_mph) ** 2));

// residual speed in the SAME-REACTION frame: both cars start together, both react for t_r, both
// brake at a. Where the slow car (u) has fully stopped, how fast is the fast car (v)?
function residualSameReaction(v_mph, u_mph, t_r, a) {
  const v = mps(v_mph), u = mps(u_mph);
  const Dslow = u * t_r + u * u / (2 * a);   // slow car's total stop distance
  const reactV = v * t_r;                    // fast car's reaction distance
  if (reactV >= Dslow) return { touched: false, speed: v }; // hasn't started braking yet
  const into = Dslow - reactV;               // distance into fast car's braking phase
  const sp2 = v * v - 2 * a * into;
  return { touched: true, speed: Math.sqrt(Math.max(0, sp2)) };
}

// ---- test harness ----------------------------------------------------------------
let pass = 0, fail = 0;
const approx = (a, b, tol = 1e-6) => Math.abs(a - b) <= tol;
function check(name, cond, detail = '') {
  if (cond) { pass++; console.log(`  PASS  ${name}${detail ? '  ' + detail : ''}`); }
  else { fail++; console.log(`  FAIL  ${name}${detail ? '  ' + detail : ''}`); }
}

console.log('why-stopping-distance-quadruples :: offline verifier');
console.log(`implied Highway Code constants: t_r = ${TR_HC.toFixed(4)} s, a = ${DRY_A.toFixed(4)} m/s^2 (${(DRY_A / G).toFixed(3)} g)`);
console.log('');

const SPEEDS = [20, 30, 40, 50, 60, 70];
const OFF_THINK = [6, 9, 12, 15, 18, 21];      // official metric thinking cells (m)
const OFF_BRAKE = [6, 14, 24, 38, 55, 75];     // official metric braking cells (m)
const OFF_TOTAL = [12, 23, 36, 53, 73, 96];    // official metric total cells (m)

// [1] Highway Code rows from the IMPERIAL generating rule (thinking ft = mph, braking ft = mph^2/20)
// Note on tolerance: the chart's thinking and braking CELLS reproduce within +-0.5 m (the spec's bar).
// The chart's TOTAL cell is the sum of the two ALREADY-ROUNDED cells (e.g. 40 mph: 12 + 24 = 36), so
// an exact imperial total (36.58 m) can sit up to ~0.6 m off a total cell as two roundings accumulate.
// We check that internal identity too, so nothing is hidden.
console.log('[1] Highway Code Rule 126 rows from the imperial rule (thinking ft = mph, braking ft = mph^2/20)');
SPEEDS.forEach((s, i) => {
  const thinkM = (s) * FT_M;            // thinking ft = mph  ->  metres
  const brakeM = (s * s / 20) * FT_M;   // braking ft = mph^2/20  ->  metres
  const totM = thinkM + brakeM;
  check(`${s} mph thinking = ${OFF_THINK[i]} m (imperial cell, +-0.5 m)`, Math.abs(thinkM - OFF_THINK[i]) <= 0.5, `= ${thinkM.toFixed(2)} m`);
  check(`${s} mph braking  = ${OFF_BRAKE[i]} m (imperial cell, +-0.5 m)`, Math.abs(brakeM - OFF_BRAKE[i]) <= 0.5, `= ${brakeM.toFixed(2)} m`);
  check(`${s} mph total    = ${OFF_TOTAL[i]} m (imperial, +-0.7 m: two roundings)`, Math.abs(totM - OFF_TOTAL[i]) <= 0.7, `= ${totM.toFixed(2)} m`);
  check(`${s} mph chart identity: total cell = thinking cell + braking cell`, OFF_TOTAL[i] === OFF_THINK[i] + OFF_BRAKE[i]);
});

// [2] Same rows from SI kinematics with the implied constants (t_r = 0.671 s, a = 6.556 m/s^2)
console.log('\n[2] Same rows from SI kinematics (t_r = 0.671 s, a = 6.556 m/s^2) -> confirms the implied constants');
SPEEDS.forEach((s, i) => {
  const thinkM = reactDist(s, TR_HC);
  const brakeM = brakeDist(s, DRY_A);
  const totM = thinkM + brakeM;
  check(`${s} mph SI thinking within 0.5 m of ${OFF_THINK[i]}`, Math.abs(thinkM - OFF_THINK[i]) <= 0.5, `= ${thinkM.toFixed(2)} m`);
  check(`${s} mph SI braking within 0.5 m of ${OFF_BRAKE[i]}`, Math.abs(brakeM - OFF_BRAKE[i]) <= 0.5, `= ${brakeM.toFixed(2)} m`);
  check(`${s} mph SI total within 0.5 m of ${OFF_TOTAL[i]}`, Math.abs(totM - OFF_TOTAL[i]) <= 0.5, `= ${totM.toFixed(2)} m`);
});
check('implied reaction time = 0.671 s', approx(TR_HC, 0.671, 5e-4), `${TR_HC.toFixed(4)} s`);
check('implied deceleration = 0.669 g', approx(DRY_A / G, 0.669, 2e-3), `${(DRY_A / G).toFixed(4)} g`);

// [3] the ratios: braking quadruples, reaction only doubles, total x3.2 (NOT x4)
console.log('\n[3] doubling 30 -> 60 mph: braking ~x4, reaction x2, total ~x3.2 (total does NOT quadruple)');
{
  // from the official rounded cells
  const brakeRatioCells = OFF_BRAKE[4] / OFF_BRAKE[1];   // 55/14
  const totalRatioCells = OFF_TOTAL[4] / OFF_TOTAL[1];   // 73/23
  const thinkRatioCells = OFF_THINK[4] / OFF_THINK[1];   // 18/9
  check('braking ratio 55/14 = 3.93 (official cells)', approx(brakeRatioCells, 3.9286, 1e-3), brakeRatioCells.toFixed(4));
  check('braking ratio = 4.000 EXACTLY (mph^2/20 rule)', approx(brakeDist(60, DRY_A) / brakeDist(30, DRY_A), 4, 1e-9), (brakeDist(60, DRY_A) / brakeDist(30, DRY_A)).toFixed(6));
  check('reaction ratio = 2.000 EXACTLY (linear in v)', approx(reactDist(60, TR_HC) / reactDist(30, TR_HC), 2, 1e-9) && approx(thinkRatioCells, 2, 1e-9), thinkRatioCells.toFixed(4));
  check('TOTAL ratio 73/23 = 3.17 (official cells, ~3.2 not 4)', approx(totalRatioCells, 3.1739, 1e-3), totalRatioCells.toFixed(4));
  check('TOTAL ratio from SI = 3.21 (not 4) -> the myth overclaims', approx(totalDist(60, TR_HC, DRY_A) / totalDist(30, TR_HC, DRY_A), 3.21, 3e-2), (totalDist(60, TR_HC, DRY_A) / totalDist(30, TR_HC, DRY_A)).toFixed(4));
  // crossover: below 20 mph reaction >= braking (the Code's own 6+6 split at 20)
  check('at 20 mph reaction == braking (the 6 m + 6 m split)', Math.abs(reactDist(20, TR_HC) - brakeDist(20, DRY_A)) <= 0.5, `react ${reactDist(20, TR_HC).toFixed(2)} vs brake ${brakeDist(20, DRY_A).toFixed(2)} m`);
  check('below 20 mph reaction is the bigger half (at 15 mph)', reactDist(15, TR_HC) > brakeDist(15, DRY_A), `react ${reactDist(15, TR_HC).toFixed(2)} > brake ${brakeDist(15, DRY_A).toFixed(2)} m`);
}

// [4] the residual-speed invariant: w = sqrt(v^2 - u^2), independent of friction
console.log('\n[4] residual invariant: where the 30 car stops, the 60 car is still doing sqrt(60^2-30^2) mph, no mu in it');
{
  const wDirect = mph(residualBrakingOnly(60, 30));
  check('sqrt(60^2 - 30^2) = 51.96 mph', approx(wDirect, 51.9615, 1e-3), `${wDirect.toFixed(4)} mph`);
  // computed the long way (through the braking phase) at three different decelerations -> identical
  function residualThroughPhase(v_mph, u_mph, a) {
    const dU = brakeDist(u_mph, a);          // distance for slow car to stop (DEPENDS on a)
    const sp2 = mps(v_mph) ** 2 - 2 * a * dU; // fast car speed there
    return mph(Math.sqrt(Math.max(0, sp2)));
  }
  const wDry = residualThroughPhase(60, 30, A_DRY);
  const wWet = residualThroughPhase(60, 30, A_WET);
  const wIce = residualThroughPhase(60, 30, A_ICE);
  check('residual identical on dry / wet / ice (mu cancels)', approx(wDry, wWet, 1e-9) && approx(wWet, wIce, 1e-9) && approx(wDry, 51.9615, 1e-3), `dry ${wDry.toFixed(4)}, wet ${wWet.toFixed(4)}, ice ${wIce.toFixed(4)} mph`);
  // the stop DISTANCE itself does depend on a (so the invariance is genuinely about the speed)
  check('stop distance DOES vary with surface (invariance is about speed, not distance)', brakeDist(30, A_ICE) > brakeDist(30, A_WET) && brakeDist(30, A_WET) > brakeDist(30, A_DRY), `dry ${brakeDist(30, A_DRY).toFixed(1)} < wet ${brakeDist(30, A_WET).toFixed(1)} < ice ${brakeDist(30, A_ICE).toFixed(1)} m`);
}

// [5] the 1.5 s flip: at a texting-human reaction the fast car has not touched the brakes yet
console.log('\n[5] flip point: at t_r = 1.5 s the 60 mph car has not braked where the 30 mph car has stopped');
{
  const react60_15 = reactDist(60, 1.5);
  check('60 mph reaction distance at 1.5 s exceeds the 30 mph Highway Code total (23 m)', react60_15 > 23, `${react60_15.toFixed(2)} m > 23 m`);
  const same = residualSameReaction(60, 30, 1.5, A_DRY);
  check('same-reaction frame at 1.5 s (dry): fast car has NOT touched the brakes', same.touched === false, `still doing ${mph(same.speed).toFixed(1)} mph`);
  // flip threshold t* where fast reaction distance == slow total (dry): u^2 / (2a(v-u))
  const u = mps(30), v = mps(60);
  const tStar = (u * u / (2 * A_DRY)) / (v - u);
  check('flip threshold t* = u^2/(2a(v-u)) is between the Alert and distracted detents (dry)', tStar > 1.0 && tStar < 1.5, `t* = ${tStar.toFixed(3)} s`);
  check('at the Highway Code 0.67 s the fast car IS still braking (not yet flipped)', residualSameReaction(60, 30, TR_HC, A_DRY).touched === true);
}

// [6] the same-reaction frame at the Highway Code reaction: ~57 mph
console.log('\n[6] same-reaction frame (both react 0.671 s, dry): fast car still doing ~57 mph where slow car stops');
{
  const same = residualSameReaction(60, 30, TR_HC, A_DRY);
  check('same-reaction residual ~ 57 mph', same.touched && approx(mph(same.speed), 57, 1), `${mph(same.speed).toFixed(2)} mph`);
  // ordering of the three frames: braking-only (52) < same-reaction (57) < texting flips off
  check('braking-only 52 < same-reaction 57 (reaction widens the gap)', residualBrakingOnly(60, 30) < same.speed, `52 vs ${mph(same.speed).toFixed(1)} mph`);
}

// [7] the AASHTO frame reproduces FHWA/Green Book design stopping sight distances
console.log('\n[7] AASHTO design frame (2.5 s + 3.4 m/s^2) reproduces the FHWA/Green Book SSD table (ft)');
{
  const SSD_DESIGN = [115, 200, 305, 425, 570, 730]; // AASHTO 2011 Exhibit 3-1, ft
  SPEEDS.forEach((s, i) => {
    const dM = totalDist(s, TR_AASHTO, A_AASHTO);
    const dFt = m2ft(dM);
    check(`${s} mph AASHTO SSD ~ ${SSD_DESIGN[i]} ft`, Math.abs(dFt - SSD_DESIGN[i]) <= 5, `= ${dFt.toFixed(1)} ft (${dM.toFixed(1)} m)`);
  });
  // roads are designed for a far slower human and gentler braking than the UK chart assumes
  const aashto30 = totalDist(30, TR_AASHTO, A_AASHTO);
  check('AASHTO 30 mph SSD (~61 m) is ~2.6x the Highway Code 23 m', aashto30 > 2.4 * 23 && aashto30 < 2.8 * 23, `${aashto30.toFixed(1)} m vs 23 m`);
  check('AASHTO reaction 2.5 s >> Highway Code 0.671 s', TR_AASHTO > 3 * TR_HC);
  check('AASHTO braking 3.4 m/s^2 is gentler than the Code 6.556 m/s^2', A_AASHTO < DRY_A);
}

// [8] kinetic energy is proportional to v^2 -> quadruples when speed doubles
console.log('\n[8] kinetic energy KE = 1/2 m v^2 quadruples 30 -> 60 mph');
{
  const ke = (v_mph) => 0.5 * 1500 * mps(v_mph) ** 2; // reference 1500 kg car, J
  check('KE(60)/KE(30) = 4.000 exactly', approx(ke(60) / ke(30), 4, 1e-9), (ke(60) / ke(30)).toFixed(6));
  check('KE scales with v^2, braking distance scales with KE (both v^2/2a)', approx(brakeDist(60, DRY_A) / brakeDist(30, DRY_A), ke(60) / ke(30), 1e-9));
}

// [9] wet doubles and ice tenths the braking distance (matches Rule 126 gap guidance)
console.log('\n[9] Rule 126 gap guidance: wet doubles, ice ~x10 the braking distance');
{
  check('wet braking distance = 2x dry (half the grip)', approx(brakeDist(30, A_WET) / brakeDist(30, A_DRY), 2, 1e-9), `${brakeDist(30, A_WET).toFixed(1)} vs ${brakeDist(30, A_DRY).toFixed(1)} m`);
  check('ice braking distance = 10x dry (a tenth of the grip)', approx(brakeDist(30, A_ICE) / brakeDist(30, A_DRY), 10, 1e-9), `${brakeDist(30, A_ICE).toFixed(1)} vs ${brakeDist(30, A_DRY).toFixed(1)} m`);
}

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