#!/usr/bin/env node
// Offline gate for /strata/fastest-line-through-a-corner/
// Recomputes EVERY number shown on the page from first principles and exits 0 on all-pass.
// Two independent methods where possible:
//   (A) v = sqrt(mu*g*r) from the closed form  AND  by numerically solving the force balance
//       mu*m*g = m*v^2/r for an arbitrary mass m (confirming v is independent of m: mass cancels).
//   (B) the lap-time delta from the quasi-steady-state (QSS) friction-circle integral AND from a
//       refined-resolution re-integration (confirming the sign and value are converged, not artifacts).
//
// The physics model here is byte-for-byte the same as the inline script in
// public/strata/fastest-line-through-a-corner/index.html.

'use strict';

// ── model constants (must match the page) ────────────────────────────────
const G = 9.81, W = 11, VMAX = 90, AENG = 3.5, NARC = 160, DSTR = 1.5;
const MPS_MPH = 2.2369362920544, MPS_KMH = 3.6;

// ── geometry ─────────────────────────────────────────────────────────────
function geomC(Rc, th) {
  const Ri = Rc - W / 2, Ro = Rc + W / 2;
  return { Rc, th, Ri, Ro, O: { x: 0, y: -Rc },
    dOut: { x: Math.cos(th), y: -Math.sin(th) },
    X: { x: Ro * Math.sin(th), y: -Rc + Ro * Math.cos(th) },
    nOutIn: { x: -Math.sin(th), y: -Math.cos(th) } };
}
function apexPt(g, f) { const psi = f * g.th; return { x: g.Ri * Math.sin(psi), y: -g.Rc + g.Ri * Math.cos(psi) }; }
function entryArc(Tx, A) {
  const R1 = ((Tx - A.x) * (Tx - A.x) + (W / 2 - A.y) * (W / 2 - A.y)) / (2 * (W / 2 - A.y));
  const O1 = { x: Tx, y: W / 2 - R1 };
  return { R1, O1, n: { x: (O1.x - A.x) / R1, y: (O1.y - A.y) / R1 } };
}
function exitArcF(A, n, g) {
  let den = 1 - (n.x * g.nOutIn.x + n.y * g.nOutIn.y);
  if (den < 1e-3) den = 1e-3;
  const num = (A.x - g.X.x) * g.nOutIn.x + (A.y - g.X.y) * g.nOutIn.y;
  let R2 = num / den; if (!isFinite(R2) || R2 <= 0 || R2 > 6000) R2 = 6000;
  const O2 = { x: A.x + n.x * R2, y: A.y + n.y * R2 };
  return { R2, O2, TO: { x: O2.x - R2 * g.nOutIn.x, y: O2.y - R2 * g.nOutIn.y } };
}
const angOf = (C, P) => Math.atan2(P.y - C.y, P.x - C.x);
function pushArc(pts, C, R, a0, a1, nseg) {
  let da = a1 - a0; while (da > Math.PI) da -= 2 * Math.PI; while (da < -Math.PI) da += 2 * Math.PI;
  for (let i = 0; i <= nseg; i++) { const a = a0 + da * i / nseg; pts.push({ x: C.x + R * Math.cos(a), y: C.y + R * Math.sin(a), r: R }); }
}
function buildLine(g, Tx, f, Sx, Lstr, narc = NARC) {
  const A = apexPt(g, f), e = entryArc(Tx, A), x = exitArcF(A, e.n, g);
  const pts = [], nS = Math.max(8, Math.round((Tx - Sx) / DSTR));
  for (let i = 0; i < nS; i++) pts.push({ x: Sx + (Tx - Sx) * i / nS, y: W / 2, r: Infinity });
  pushArc(pts, e.O1, e.R1, angOf(e.O1, { x: Tx, y: W / 2 }), angOf(e.O1, A), narc);
  const tmp = []; pushArc(tmp, x.O2, x.R2, angOf(x.O2, A), angOf(x.O2, x.TO), narc);
  for (let i = 1; i < tmp.length; i++) pts.push(tmp[i]);
  const toIdx = pts.length - 1;
  const nP = Math.max(12, Math.round(Lstr / DSTR));
  for (let i = 1; i <= nP; i++) pts.push({ x: x.TO.x + g.dOut.x * Lstr * i / nP, y: x.TO.y + g.dOut.y * Lstr * i / nP, r: Infinity });
  pts[0].s = 0; for (let i = 1; i < pts.length; i++) pts[i].s = pts[i - 1].s + Math.hypot(pts[i].x - pts[i - 1].x, pts[i].y - pts[i - 1].y);
  return { pts, R1: e.R1, R2: x.R2, A, TO: x.TO, toIdx };
}
function profile(pts, mu) {
  const n = pts.length, aMax = mu * G;
  const vcap = new Array(n), v = new Array(n);
  for (let i = 0; i < n; i++) { vcap[i] = isFinite(pts[i].r) ? Math.min(VMAX, Math.sqrt(mu * G * pts[i].r)) : VMAX; v[i] = vcap[i]; }
  for (let i = 1; i < n; i++) {
    const ds = pts[i].s - pts[i - 1].s, r = pts[i - 1].r, vp = v[i - 1];
    const alat = isFinite(r) ? vp * vp / r : 0;
    const al = Math.min(Math.sqrt(Math.max(0, aMax * aMax - alat * alat)), AENG);
    v[i] = Math.min(vcap[i], Math.sqrt(vp * vp + 2 * al * ds));
  }
  for (let i = n - 2; i >= 0; i--) {
    const ds = pts[i + 1].s - pts[i].s, r = pts[i + 1].r, vn = v[i + 1];
    const alat = isFinite(r) ? vn * vn / r : 0;
    const ab = Math.sqrt(Math.max(0, aMax * aMax - alat * alat));
    v[i] = Math.min(v[i], Math.sqrt(vn * vn + 2 * ab * ds));
  }
  let t = 0; for (let i = 1; i < n; i++) t += (pts[i].s - pts[i - 1].s) / (0.5 * (v[i] + v[i - 1]));
  return { v, t };
}
function findGeoTx(g) {
  const A = apexPt(g, 0.5); let lo = -800, hi = -1.2;
  for (let k = 0; k < 100; k++) { const mid = (lo + hi) / 2, e = entryArc(mid, A), x = exitArcF(A, e.n, g);
    if (e.R1 - x.R2 > 0) lo = mid; else hi = mid; }
  return (lo + hi) / 2;
}
const sxFor = (geoTx, mu) => geoTx - (VMAX * VMAX) / (2 * mu * G) - 60;
function minSpeed(v, toIdx) { let m = Infinity, mi = 0; for (let i = 0; i <= toIdx; i++) if (v[i] < m) { m = v[i]; mi = i; } return { v: m, i: mi }; }

// the same state->everything the page solves for
function solve(st) {
  const th = st.ang * Math.PI / 180, g = geomC(st.rc, th);
  const geoTx = findGeoTx(g), Sx = sxFor(geoTx, st.mu);
  const TxEarly = geoTx * 1.35, TxLate = geoTx * 0.18;
  const Tx = TxEarly + (TxLate - TxEarly) * st.turnin;
  const you = buildLine(g, Tx, st.apex, Sx, st.straight);
  const geo = buildLine(g, geoTx, 0.5, Sx, st.straight);
  const pYou = profile(you.pts, st.mu), pGeo = profile(geo.pts, st.mu);
  const mYou = minSpeed(pYou.v, you.toIdx), mGeo = minSpeed(pGeo.v, geo.toIdx);
  return { g, Sx, geoTx, Tx, you, geo, apexYou: mYou.v, apexGeo: mGeo.v,
    exitYou: pYou.v[you.toIdx], exitGeo: pGeo.v[geo.toIdx], tYou: pYou.t, tGeo: pGeo.t, delta: pGeo.t - pYou.t };
}

// ── check harness ────────────────────────────────────────────────────────
let PASS = 0, FAIL = 0;
function ok(name, cond, detail) {
  (cond ? PASS++ : FAIL++);
  console.log(`${cond ? 'PASS' : 'FAIL'}  ${name}${detail ? '   ' + detail : ''}`);
}
const close = (a, b, tol) => Math.abs(a - b) <= tol;

console.log('== 1. The grip-limited cornering speed  v = sqrt(mu*g*r) ==');
{
  const v = Math.sqrt(0.85 * G * 50);
  ok('v(mu=0.85, r=50 m) = 20.42 m/s', close(v, 20.419, 0.01), `${v.toFixed(3)} m/s = ${(v * MPS_MPH).toFixed(2)} mph = ${(v * MPS_KMH).toFixed(1)} km/h`);

  // Method (A2): solve the force balance mu*m*g = m*v^2/r numerically for an arbitrary mass; v must not depend on m.
  function solveV(mu, r, m) {
    // find v with |mu*m*g - m*v^2/r| = 0 by bisection on v
    let lo = 0, hi = 200;
    for (let k = 0; k < 80; k++) { const mid = (lo + hi) / 2; if (m * mid * mid / r < mu * m * G) lo = mid; else hi = mid; }
    return (lo + hi) / 2;
  }
  const vHeavy = solveV(0.85, 50, 1800), vLight = solveV(0.85, 50, 300);
  ok('mass cancels: solving mu*m*g = m*v^2/r gives the same v for m=1800 and m=300 kg',
    close(vHeavy, vLight, 1e-6) && close(vHeavy, v, 1e-3), `heavy ${vHeavy.toFixed(4)} vs light ${vLight.toFixed(4)}`);

  const lift = Math.sqrt(60 / 50) - 1;
  ok('speed scales as sqrt(r): +20% radius (50->60 m) lifts speed +9.5%', close(lift, 0.0954, 0.001), `+${(lift * 100).toFixed(2)}%`);

  const v60 = Math.sqrt(0.85 * G * 60);
  ok('worked pair: r=60 m -> 22.37 m/s', close(v60, 22.368, 0.01), `${v60.toFixed(3)} m/s = ${(v60 * MPS_MPH).toFixed(2)} mph`);
}

console.log('\n== 2. Geometric baseline (default corner: Rc=45 m, W=11 m, angle=90 deg) ==');
{
  const g = geomC(45, Math.PI / 2);
  const geoTx = findGeoTx(g);
  const e = entryArc(geoTx, apexPt(g, 0.5)), x = exitArcF(apexPt(g, 0.5), e.n, g);
  ok('geometric line is a single radius: entry R1 == exit R2', close(e.R1, x.R2, 0.05), `R1=${e.R1.toFixed(3)}  R2=${x.R2.toFixed(3)}`);
  ok('geometric radius = 77.06 m', close(e.R1, 77.056, 0.05), `${e.R1.toFixed(3)} m`);
  const vg = Math.sqrt(0.95 * G * e.R1);
  ok('geometric apex/exit speed = 26.80 m/s (grip cap)', close(vg, 26.80, 0.05), `${vg.toFixed(3)} m/s = ${(vg * MPS_MPH).toFixed(1)} mph`);
}

console.log('\n== 3. Default sandbox state (turn-in 0.51, apex 0.58, mu=0.95, straight=350 m) ==');
const DEF = { turnin: 0.51, apex: 0.58, mu: 0.95, rc: 45, ang: 90, straight: 350 };
{
  const S = solve(DEF);
  ok('default turn-in maps to Tx ~ -20.0 m', close(S.Tx, -20.0, 0.1), `Tx=${S.Tx.toFixed(3)}`);
  ok('your entry radius R1 = 63.0 m', close(S.you.R1, 63.02, 0.3), `${S.you.R1.toFixed(2)} m`);
  ok('your exit radius R2 = 102.9 m (wider than geometric 77.1)', close(S.you.R2, 102.9, 0.5) && S.you.R2 > 77.1, `${S.you.R2.toFixed(2)} m`);
  ok('apex speed: your line 24.24 m/s, SLOWER than geometric 26.80', close(S.apexYou, 24.24, 0.05) && S.apexYou < S.apexGeo,
    `you ${S.apexYou.toFixed(2)}  geo ${S.apexGeo.toFixed(2)}`);
  ok('exit speed: your line 30.97 m/s, FASTER than geometric 26.80', close(S.exitYou, 30.97, 0.05) && S.exitYou > S.exitGeo,
    `you ${S.exitYou.toFixed(2)} (${(S.exitYou * MPS_MPH).toFixed(1)} mph)  geo ${S.exitGeo.toFixed(2)} (${(S.exitGeo * MPS_MPH).toFixed(1)} mph)`);
  ok('lap-time delta over 350 m straight = +90 ms (your line faster)', close(S.delta * 1000, 89.95, 2) && S.delta > 0,
    `delta = ${(S.delta * 1000).toFixed(1)} ms`);

  // Method (B2): re-integrate at doubled resolution; the delta must be near-converged (same sign, within ~2 ms).
  const th = DEF.ang * Math.PI / 180, gg = geomC(DEF.rc, th), gtx = findGeoTx(gg), Sx = sxFor(gtx, DEF.mu);
  const TxE = gtx * 1.35, TxL = gtx * 0.18, Tx = TxE + (TxL - TxE) * DEF.turnin;
  const you2 = buildLine(gg, Tx, DEF.apex, Sx, DEF.straight, NARC * 2);
  const geo2 = buildLine(gg, gtx, 0.5, Sx, DEF.straight, NARC * 2);
  const d2 = profile(geo2.pts, DEF.mu).t - profile(you2.pts, DEF.mu).t;
  ok('delta is near-converged (re-integrated at 2x resolution agrees within 2 ms, same sign)',
    close(d2 * 1000, S.delta * 1000, 2) && d2 > 0, `2x-res delta = ${(d2 * 1000).toFixed(1)} ms (vs ${(S.delta * 1000).toFixed(1)} ms)`);
}

console.log('\n== 4. The flip: the late-apex advantage REQUIRES a following straight ==');
{
  const d0 = solve({ ...DEF, straight: 0 }).delta * 1000;
  const d250 = solve({ ...DEF, straight: 250 }).delta * 1000;
  const d700 = solve({ ...DEF, straight: 700 }).delta * 1000;
  ok('no following straight -> geometric line is faster (delta < 0)', d0 < 0, `delta@0 = ${d0.toFixed(1)} ms`);
  ok('break-even is near a ~250 m straight (delta crosses zero)', Math.abs(d250) < 40, `delta@250 = ${d250.toFixed(1)} ms`);
  ok('long straight -> late apex wins, exit speed compounds (delta > 0)', d700 > 0, `delta@700 = ${d700.toFixed(1)} ms`);
  ok('delta grows monotonically with straight length (more straight = bigger late-apex win)',
    d0 < d250 && d250 < d700, `${d0.toFixed(0)} < ${d250.toFixed(0)} < ${d700.toFixed(0)} ms`);
}

console.log('\n== 5. Ross Bentley: faster corner -> drive closer to the geometric line ==');
{
  // A fast sweeper (gentle angle, large radius) should shrink the late-apex win vs a tight slow corner,
  // for the same following straight.
  const tight = solve({ ...DEF, ang: 120, rc: 30, straight: 350 }).delta * 1000; // slow, sharp corner
  const sweep = solve({ ...DEF, ang: 55, rc: 75, straight: 350 }).delta * 1000;  // fast, open sweeper
  ok('slow/sharp corner rewards the late apex more than a fast sweeper does',
    tight > sweep, `tight ${tight.toFixed(0)} ms  vs  sweeper ${sweep.toFixed(0)} ms`);
}

console.log(`\n${FAIL === 0 ? 'ALL CHECKS PASS' : 'SOME CHECKS FAILED'}  (${PASS} passed, ${FAIL} failed)`);
process.exit(FAIL === 0 ? 0 : 1);
