#!/usr/bin/env node
// verify-should-you-pump-the-brakes.mjs
//
// Offline gate for /strata/should-you-pump-the-brakes/. It recomputes EVERY number the
// page shows, from the SAME model the page's inline JS uses, and exits 0 only if all
// checks pass.
//
// The model (single-hump mu-slip curve + work-energy kinematics):
//   mu(s): 0 at s=0, peak at s=0.15, sliding value at s=1     [Burckhardt/Pacejka single hump]
//   deceleration   a = mu_eff * g                              (locked wheels add a plow term on loose surfaces)
//   distance       d = v^2 / (2a)                              [work-energy theorem; constant-decel strategies]
//   pump distance  numerical integration of the on/off cycle   (on-phase first)
//
// Surface anchors (hpwizard SAE tire-friction table):
//   dry 0.90/0.75, wet 0.60/0.50, packed snow 0.20/0.15, ice 0.10/0.07.
// Loose-gravel wedge calibrated to NHTSA: ABS ~27.2% longer than locked (SAE 1999-01-1287; DOT HS 811 182).
//
// Run:  node research/should-you-pump-the-brakes/verify-should-you-pump-the-brakes.mjs

'use strict';

// ---- shared constants (identical to the page's inline JS) ------------------------
const G = 9.81;            // m/s^2
const MPH = 0.44704;       // m/s per mph
const SP = 0.15;           // peak-slip location (fraction), inside the 10-20% band
const THRESH_EFF = 0.88;   // expert threshold braking: fraction of peak grip held
const ABS_EFF_DEF = 0.90;  // default ABS fraction of peak
const NHTSA_GRAVEL = 0.272;// loose gravel: ABS is this fraction longer than locked

const SURF = {
  dry:    { peak: 0.90, slide: 0.75, loose: false, label: 'Dry asphalt' },
  wet:    { peak: 0.60, slide: 0.50, loose: false, label: 'Wet asphalt' },
  snow:   { peak: 0.20, slide: 0.15, loose: false, label: 'Packed snow' },
  ice:    { peak: 0.10, slide: 0.07, loose: false, label: 'Ice' },
  gravel: { peak: 0.55, slide: 0.45, loose: true,  label: 'Loose gravel / deep snow' },
};

// plow "wedge" (in g) added to LOCKED wheels on loose surfaces, calibrated so
// (slide + wedge) = (1 + NHTSA_GRAVEL) * ABS_EFF_DEF * peak.
const wedgeOf = (s) => (s.loose ? (1 + NHTSA_GRAVEL) * ABS_EFF_DEF * s.peak - s.slide : 0);

// single-hump mu-slip curve: 0 at s=0, peak at SP, slide at s=1, smooth at the peak
function muSlip(s, peak, slide) {
  if (s <= 0) return 0;
  if (s >= 1) return slide;
  if (s <= SP) { const u = 1 - s / SP; return peak * (1 - u * u); }
  const w = (s - SP) / (1 - SP); return peak + (slide - peak) * w * w;
}

function decel(strategy, s, absEff, phaseOn) {
  const wedge = wedgeOf(s);
  if (strategy === 'abs')       return absEff * s.peak * G;
  if (strategy === 'locked')    return (s.slide + wedge) * G;
  if (strategy === 'threshold') return THRESH_EFF * s.peak * G;
  if (strategy === 'pump')      return phaseOn ? (s.slide + wedge) * G : 0;
  return 0;
}

function stop(strategy, s, v0, o = {}) {
  const absEff = o.absEff == null ? ABS_EFF_DEF : o.absEff;
  const freq = o.freq == null ? 2 : o.freq;
  const duty = o.duty == null ? 0.5 : o.duty;
  if (strategy !== 'pump') {
    const a = decel(strategy, s, absEff, true);
    return { d: v0 * v0 / (2 * a), t: v0 / a, a, avgA: a };
  }
  const dt = 1e-4, period = 1 / freq, aOn = decel('pump', s, absEff, true);
  let v = v0, x = 0, t = 0, guard = 0;
  while (v > 0 && guard < 5e7) {
    const ph = (t % period) / period;
    const on = ph < duty;
    const a = on ? aOn : 0;
    v -= a * dt; if (v < 0) v = 0;
    x += v * dt; t += dt; guard++;
  }
  return { d: x, t, a: aOn, avgA: v0 * v0 / (2 * x) };
}

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

console.log('should-you-pump-the-brakes :: offline verifier');
console.log(`g=${G} m/s^2  peak-slip=${SP * 100}%  ABS eff (default)=${ABS_EFF_DEF}  threshold eff=${THRESH_EFF}`);
console.log('');

const v60 = 60 * MPH;

// [1] the mu-slip model reproduces the cited anchors AND peaks in the 10-20% band
console.log('[1] mu-slip curve reproduces anchors and peaks in the 10-20% slip band');
{
  for (const [k, s] of Object.entries(SURF)) {
    check(`${k}: peak at s=${SP} = ${s.peak}`, approx(muSlip(SP, s.peak, s.slide), s.peak, 1e-9),
      `mu(0.15)=${muSlip(SP, s.peak, s.slide).toFixed(3)}`);
    check(`${k}: sliding at s=1 = ${s.slide}`, approx(muSlip(1, s.peak, s.slide), s.slide, 1e-9),
      `mu(1)=${muSlip(1, s.peak, s.slide).toFixed(3)}`);
    // numerically confirm the maximum is inside 10-20% slip
    let best = 0, bs = 0;
    for (let i = 0; i <= 2000; i++) { const ss = i / 2000; const m = muSlip(ss, s.peak, s.slide); if (m > best) { best = m; bs = ss; } }
    check(`${k}: maximum lies in 10-20% slip`, bs >= 0.10 && bs <= 0.20, `argmax slip=${(bs * 100).toFixed(1)}%`);
    check(`${k}: mu(0)=0 and curve falls past the peak`, approx(muSlip(0, s.peak, s.slide), 0, 1e-12) && muSlip(0.5, s.peak, s.slide) > muSlip(1, s.peak, s.slide));
  }
}

// [2] dry 60 mph, three ways: ABS ~45, locked ~49 (+~8%), naive pump ~98 (~2x); order ABS<locked<pump
console.log('\n[2] dry 60 mph three ways (d = v^2/2a): ABS ~45 m, locked ~49 m, naive pump ~2x');
{
  const abs = stop('abs', SURF.dry, v60, { absEff: 0.90 });
  const locked = stop('locked', SURF.dry, v60);
  const pump = stop('pump', SURF.dry, v60, { freq: 2, duty: 0.5 });
  // cross-check ABS and locked against an independent closed-form d = v^2/(2*mu*g)
  const absCF = v60 * v60 / (2 * 0.90 * 0.90 * G);
  const lockedCF = v60 * v60 / (2 * 0.75 * G);
  check('ABS distance ~45 m', Math.abs(abs.d - 45) < 2, `${abs.d.toFixed(2)} m`);
  check('ABS matches independent closed form', approx(abs.d, absCF, 1e-9), `${absCF.toFixed(2)} m`);
  check('locked distance ~49 m', Math.abs(locked.d - 49) < 2, `${locked.d.toFixed(2)} m`);
  check('locked is 6-10% longer than ABS on dry (continuous, no steering)',
    (locked.d / abs.d - 1) > 0.06 && (locked.d / abs.d - 1) < 0.10, `+${((locked.d / abs.d - 1) * 100).toFixed(1)}%`);
  check('locked matches independent closed form', approx(locked.d, lockedCF, 1e-9), `${lockedCF.toFixed(2)} m`);
  check('naive pump is roughly double ABS (~2x)', pump.d / abs.d > 1.9 && pump.d / abs.d < 2.3,
    `${(pump.d / abs.d).toFixed(2)}x = ${pump.d.toFixed(2)} m`);
  check('pump average deceleration ~ duty*slide*g (smeared limit sanity)',
    Math.abs(pump.avgA - 0.5 * 0.75 * G) / (0.5 * 0.75 * G) < 0.06, `avgA=${pump.avgA.toFixed(3)} vs smear ${(0.5 * 0.75 * G).toFixed(3)}`);
  check('paved ORDER: ABS < locked < naive pump', abs.d < locked.d && locked.d < pump.d,
    `${abs.d.toFixed(1)} < ${locked.d.toFixed(1)} < ${pump.d.toFixed(1)}`);
}

// [3] pump is monotone in duty and frequency, and never undercuts ABS on any paved surface
console.log('\n[3] pump monotone in duty + frequency; never beats ABS on any paved surface');
{
  // monotone in duty (higher duty -> shorter): sample the full slider range
  let mono = true, prev = Infinity;
  for (let d = 0.20; d <= 0.8001; d += 0.05) { const dd = stop('pump', SURF.dry, v60, { duty: d }).d; if (dd > prev) mono = false; prev = dd; }
  check('pump distance strictly decreases with duty cycle', mono);
  // monotone in frequency (on-phase-first integration): sample 1..4 Hz
  let monoF = true, prevF = -Infinity;
  for (let f = 1; f <= 4.0001; f += 0.5) { const df = stop('pump', SURF.dry, v60, { freq: f }).d; if (df < prevF) monoF = false; prevF = df; }
  check('pump distance is monotone in frequency (converges toward the smear)', monoF);
  // never undercuts ABS: worst-case pump (max duty, any freq) across every PAVED surface and speed
  const paved = ['dry', 'wet', 'snow', 'ice'];
  let neverBeats = true, worst = '';
  for (const k of paved) {
    for (let mph = 20; mph <= 80; mph += 5) {
      const v = mph * MPH;
      const absd = stop('abs', SURF[k], v, { absEff: 0.97 }).d;   // most efficient ABS
      const pd = stop('pump', SURF[k], v, { freq: 4, duty: 0.8 }).d; // best-case pump
      if (pd <= absd) { neverBeats = false; worst = `${k}@${mph}mph pump ${pd.toFixed(1)} <= ABS ${absd.toFixed(1)}`; }
    }
  }
  check('best-case pump never undercuts most-efficient ABS on any paved surface', neverBeats, worst || 'checked dry/wet/snow/ice, 20-80 mph');
}

// [4] expert threshold braking closes to within a few percent of ABS
console.log('\n[4] expert threshold braking nearly matches ABS');
{
  const abs = stop('abs', SURF.dry, v60, { absEff: 0.90 });
  const th = stop('threshold', SURF.dry, v60);
  check('threshold within 3% of ABS on dry', (th.d / abs.d - 1) < 0.03 && th.d > abs.d,
    `+${((th.d / abs.d - 1) * 100).toFixed(1)}% (${th.d.toFixed(1)} m vs ${abs.d.toFixed(1)} m)`);
  check('threshold is far shorter than the naive pump', th.d < 0.6 * stop('pump', SURF.dry, v60).d);
}

// [5] loose-gravel branch: locked beats ABS, ABS ~27.2% longer (NHTSA sign + magnitude)
console.log('\n[5] loose gravel: the ranking flips, ABS ~27.2% longer than locked (NHTSA)');
{
  const abs = stop('abs', SURF.gravel, v60, { absEff: 0.90 });
  const locked = stop('locked', SURF.gravel, v60);
  const pump = stop('pump', SURF.gravel, v60);
  const th = stop('threshold', SURF.gravel, v60);
  check('gravel: locked stops SHORTER than ABS', locked.d < abs.d, `${locked.d.toFixed(1)} < ${abs.d.toFixed(1)}`);
  check('gravel: ABS is 27.2% longer than locked (calibrated to NHTSA)', approx(abs.d / locked.d - 1, NHTSA_GRAVEL, 0.01),
    `+${((abs.d / locked.d - 1) * 100).toFixed(2)}%`);
  check('gravel: locked is the shortest of all four', locked.d < abs.d && locked.d < pump.d && locked.d < th.d);
  check('gravel: pump is still the worst', pump.d > abs.d && pump.d > locked.d && pump.d > th.d);
  check('gravel wedge is a positive plow bonus', wedgeOf(SURF.gravel) > 0, `wedge=${wedgeOf(SURF.gravel).toFixed(3)} g`);
}

// [6] sanity: mass cancels, and stronger grip always shortens the stop
console.log('\n[6] sanity: kinematics well-behaved');
{
  check('d = v^2/(2a) scales as v^2 (double speed -> 4x distance)',
    approx(stop('abs', SURF.dry, 2 * v60).d, 4 * stop('abs', SURF.dry, v60).d, 1e-9));
  check('more grip -> shorter stop (dry ABS < snow ABS)',
    stop('abs', SURF.dry, v60).d < stop('abs', SURF.snow, v60).d);
}

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