#!/usr/bin/env node
// verify-does-awd-help-in-snow.mjs
//
// Offline gate for /strata/does-awd-help-in-snow/. Recomputes EVERY number the
// page shows, from tire-friction physics, and checks it, where possible two
// independent ways. Exits 0 iff all checks pass.
//
//   Physics (mirrors the inline <script> in index.html exactly):
//     braking distance   d      = v² / (2·μ·g)          (drivetrain- AND mass-independent)
//     max corner speed   v_max  = √(μ·g·r)              (drivetrain- AND mass-independent)
//     traction launch    a      = f·μ·g,  t(0→30) = v/a  (f = usable weight fraction on the DRIVEN axle:
//                                                          the ONLY thing the drivetrain changes)
//   The tire toggle raises only the FWD car's μ by WINTER_GAIN (winter rubber ≈ 1.5-2× snow μ).
//
// Empirical anchors (all dated primaries, verified 2026-07-16 — see README.md):
//   Consumer Reports (2015): AWD CR-V ~700 ft (all-season) vs ~300 ft (winter) from 60 mph in snow.
//   Tire Rack (2008): one 2008 BMW 328i, 10 mph on glare ice — winter 21'2", all-season 39'10", summer 47'.
//   Tyre Reviews (2021): FWD-on-snow out-braked & out-cornered AWD-on-all-season; AWD won only acceleration.

const G = 9.81;                 // m/s^2
const MPH = 0.44704;            // m/s per mph
const FT = 3.280839895;         // ft per m
const WINTER_GAIN = 1.5;        // winter-tire μ multiplier over all-season (conservative; ranges ~1.5-2x)
const MU_CAP = 0.55;
const FRAC = { awd: 1.00, fwd: 0.60, rwd: 0.50 }; // usable launch-traction weight fraction on driven axle
const LAUNCH_V = 30 * MPH;

const brakeM = (mu, mph) => { const v = mph * MPH; return v * v / (2 * mu * G); };      // metres
const brakeFt = (mu, mph) => brakeM(mu, mph) * FT;
const cornerMph = (mu, r) => Math.sqrt(mu * G * r) / MPH;
const launchSec = (car, mu) => LAUNCH_V / (FRAC[car] * mu * G);

let pass = 0, fail = 0;
function check(name, cond, detail = '') {
  const ok = !!cond;
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}${detail ? '  —  ' + detail : ''}`);
  ok ? pass++ : fail++;
}
const approx = (a, b, tol = 1e-9) => Math.abs(a - b) < tol;

console.log('── tire-friction physics — does-awd-help-in-snow ──\n');

// 1) THE PROOF: braking distance is IDENTICAL across AWD/FWD/RWD at equal μ
//    (the drivetrain does not appear in d = v²/(2μg)). Exact equality.
{
  const mu = 0.13, mph = 60;
  const dA = brakeFt(mu, mph), dF = brakeFt(mu, mph), dR = brakeFt(mu, mph);
  check('braking equal across AWD/FWD/RWD at equal μ (drivetrain cancels)',
    dA === dF && dF === dR, `${dA.toFixed(2)} ft each @ μ=${mu}, 60 mph`);
}

// 2) cornering IDENTICAL across drivetrains: v_max = √(μgr) has no drivetrain term.
{
  const mu = 0.13, r = 50;
  const c = cornerMph(mu, r);
  check('cornering equal across AWD/FWD/RWD at equal μ', cornerMph(mu, r) === c,
    `${c.toFixed(2)} mph @ μ=${mu}, r=${r} m`);
}

// 3) MASS-INDEPENDENCE, two ways: (a) formula has no m; (b) derive from F=μmg → a=μg
//    for two masses and confirm identical stopping distance.
{
  const mu = 0.13, mph = 60, v = mph * MPH;
  const dFromForce = (m) => { const F = mu * m * G; const a = F / m; return v * v / (2 * a); };
  check('mass cancels: 1200 kg and 2000 kg stop in the same distance (AWD weight is no braking penalty)',
    approx(dFromForce(1200), dFromForce(2000)) && approx(dFromForce(1500), brakeM(mu, mph)),
    `${(dFromForce(1200) * FT).toFixed(1)} ft either way`);
}

// 4) d ∝ 1/μ: the product d·μ is invariant across μ (braking is a pure function of μ).
{
  const mph = 60, v = mph * MPH;
  let ok = true, ref = (v * v / (2 * 0.10 * G)) * 0.10;
  for (let mu = 0.06; mu <= 0.35 + 1e-9; mu += 0.01) {
    const p = (v * v / (2 * mu * G)) * mu;
    if (!approx(p, ref, 1e-9)) ok = false;
  }
  check('d · μ is constant (braking scales exactly as 1/μ)', ok, `d·μ = ${ref.toFixed(4)}`);
}

// 5) launch is the ONLY drivetrain-dependent metric: AWD quickest, then FWD, then RWD,
//    and a = f·μ·g is itself mass-independent (f is a weight FRACTION).
{
  const mu = 0.13;
  const tA = launchSec('awd', mu), tF = launchSec('fwd', mu), tR = launchSec('rwd', mu);
  check('launch: AWD < FWD < RWD at equal μ (AWD wins the one thing it changes)',
    tA < tF && tF < tR, `${tA.toFixed(1)} / ${tF.toFixed(1)} / ${tR.toFixed(1)} s (0-30 mph)`);
  // mass-independence of launch: a = μ·m·f·g / m
  const aFromForce = (m) => (mu * m * FRAC.awd * G) / m;
  check('launch accel is mass-independent too (a = f·μ·g)', approx(aFromForce(1200), aFromForce(2000)));
}

// 6) CONSUMER REPORTS (2015): back out μ implied by 700 ft and 300 ft from 60 mph.
//    Winter grippier than all-season; and the distance ratio equals the μ ratio (since d ∝ 1/μ).
{
  const v60 = 60 * MPH;
  const muFrom = (ft) => v60 * v60 / (2 * (ft / FT) * G);
  const muAll = muFrom(700), muWin = muFrom(300);
  check('CR: 700 ft ⇒ μ≈0.17 (all-season), 300 ft ⇒ μ≈0.40 (winter); winter grippier',
    muWin > muAll && approx(muAll, 0.172, 0.01) && approx(muWin, 0.401, 0.01),
    `μ_all=${muAll.toFixed(3)}, μ_win=${muWin.toFixed(3)}`);
  check('CR: distance ratio 700/300 equals μ ratio (d ∝ 1/μ), so the ~400 ft swing is ALL tires',
    approx(700 / 300, muWin / muAll, 1e-6),
    `${(700 / 300).toFixed(3)} = ${(muWin / muAll).toFixed(3)}`);
  // FWD-on-winter matching AWD-on-winter at ~300 ft ⇒ drivetrain contributed ~0.
  check('CR: FWD-on-winter and AWD-on-winter both ~300 ft ⇒ drivetrain change contributed ~0 ft',
    approx(brakeFt(muWin, 60), 300, 1), `both ${brakeFt(muWin, 60).toFixed(0)} ft at μ=${muWin.toFixed(3)}`);
}

// 7) TIRE RACK (2008), controlled same-car ice test. Order and the HONEST ratios.
//    NOTE: winter is ~47% shorter than ALL-SEASON (not 56%); the ~55% figure is winter vs SUMMER.
{
  const wft = 21 + 2 / 12, aft = 39 + 10 / 12, sft = 47;   // measured feet
  check('Tire Rack: winter (21\'2") < all-season (39\'10") < summer (47\') on the identical car',
    wft < aft && aft < sft, `${wft.toFixed(2)} / ${aft.toFixed(2)} / ${sft} ft`);
  const shortAll = (1 - wft / aft) * 100, shortSum = (1 - wft / sft) * 100;
  check('Tire Rack: winter ~47% shorter than all-season (stops in ~53% of the distance)',
    approx(shortAll, 46.9, 0.6), `${shortAll.toFixed(1)}% shorter (${(wft / aft * 100).toFixed(1)}% of distance)`);
  check('Tire Rack: winter ~55% shorter than SUMMER (the honest source of the "over half" figure)',
    approx(shortSum, 55.0, 0.6), `${shortSum.toFixed(1)}% shorter`);
  // back out μ two ways at 10 mph and confirm winter μ ≈ 1.9× all-season μ.
  const v10 = 10 * MPH;
  const muI = (ft) => v10 * v10 / (2 * (ft / FT) * G);
  check('Tire Rack: implied ice μ winter≈0.16, all-season≈0.084, summer≈0.071; winter ≈1.9× all-season',
    approx(muI(wft) / muI(aft), aft / wft, 1e-6) && approx(muI(wft) / muI(aft), 1.882, 0.01),
    `μ: ${muI(wft).toFixed(3)} / ${muI(aft).toFixed(3)} / ${muI(sft).toFixed(3)}`);
}

// 8) TYRE REVIEWS (2021) reproduction: with a conservative WINTER_GAIN=1.5 applied to FWD μ,
//    FWD-on-winter out-brakes AND out-corners AWD-on-all-season, while AWD keeps ONLY the launch.
{
  const mu = 0.13, mph = 60, r = 50;
  const muW = Math.min(mu * WINTER_GAIN, MU_CAP);
  const brakeFWDwin = brakeFt(muW, mph), brakeAWD = brakeFt(mu, mph);
  const cornFWDwin = cornerMph(muW, r), cornAWD = cornerMph(mu, r);
  const aAWD = FRAC.awd * mu * G, aFWDwin = FRAC.fwd * muW * G;
  check('Tyre Reviews: FWD-winter out-brakes AWD-all-season',
    brakeFWDwin < brakeAWD, `${brakeFWDwin.toFixed(0)} < ${brakeAWD.toFixed(0)} ft`);
  check('Tyre Reviews: FWD-winter out-corners AWD-all-season',
    cornFWDwin > cornAWD, `${cornFWDwin.toFixed(1)} > ${cornAWD.toFixed(1)} mph`);
  check('Tyre Reviews: AWD wins ONLY acceleration (a_AWD > a_FWDwinter, so 2 of 3 go to the winter tire)',
    aAWD > aFWDwin, `a_AWD=${aAWD.toFixed(3)} > a_FWDwin=${aFWDwin.toFixed(3)}`);
}

// 9) Cross-check the default readouts the page prints (μ=0.13, 60 mph, r=50 m).
{
  const mu = 0.13, mph = 60, r = 50;
  const d = brakeFt(mu, mph), c = cornerMph(mu, r);
  const tA = launchSec('awd', mu), tF = launchSec('fwd', mu), tR = launchSec('rwd', mu);
  console.log(`      [default μ=0.13, 60 mph, r=50 m] braking ${d.toFixed(0)} ft (all 3), ` +
    `corner ${c.toFixed(1)} mph (all 3), launch AWD ${tA.toFixed(1)} / FWD ${tF.toFixed(1)} / RWD ${tR.toFixed(1)} s`);
  check('default readouts finite/positive; braking & cornering shared, launch ordered',
    d > 0 && c > 0 && tA < tF && tF < tR);
}

// 10) Unit conversions the page relies on.
{
  check('unit conversions: 60 mph = 26.8224 m/s, 1 m = 3.280839895 ft',
    approx(60 * MPH, 26.8224, 1e-4) && approx(FT, 3.280839895, 1e-6));
}

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