// verify.mjs — the check behind the portal "The Price of Everyone Being Right"
// (/strata/price-of-anarchy/). The portal walks ONE shape — local optimization →
// collective harm, curable only by a constraint — across three strata that already
// live on the ground, and it makes a structural claim the three source pages do not
// make on their own:
//
//   (A) BRAESS (the-road-that-made-everyone-late) and the COMMONS
//       (tragedy-of-the-commons) are genuine EQUILIBRIA — stable rest points of a
//       game — with a measurable *price of anarchy* (selfish cost / coordinated cost).
//   (B) The affine-routing price of anarchy is BOUNDED (never worse than 4/3), while
//       the commons price of anarchy is UNBOUNDED (grows without ceiling as the crowd
//       grows). Some anarchies are cheap; some are ruinous. THIS is the cross-cutting
//       claim, and it is what this verifier pins.
//   (C) The PHANTOM JAM (phantom-traffic-jam) is NOT an equilibrium at all — it is a
//       dynamical INSTABILITY, so it has no price-of-anarchy ratio. The portal must be
//       honest that the unifying claim spans two mathematical languages, and that the
//       phantom jam is the reductio: local reasonableness with NOTHING to fight over
//       still self-organizes into harm, and the cure is still a *constraint* (patient
//       spacing restabilizes the identical road).
//
// Everything numeric the portal displays is recomputed here, two independent ways
// where possible, by IMPORTING the exact engines the three source pages were verified
// with. Run:  node research/price-of-anarchy/verify.mjs   (exit 0 iff all pass)

import { userEquilibrium, systemOptimum } from '../braess/engine.mjs';
import { PARAMS, equilibriumSpeed, initRing, step } from '../phantom-traffic-jam/idm.mjs';

let pass = 0, fail = 0;
function check(name, got, want, eps = 1e-6) {
  const ok = (typeof want === 'number' && typeof got === 'number')
    ? Math.abs(got - want) <= eps
    : got === want;
  console.log(`${ok ? 'ok  ' : 'FAIL'}  ${name}  ->  ${JSON.stringify(got)}${ok ? '' : `   (want ${JSON.stringify(want)})`}`);
  ok ? pass++ : fail++;
  return ok;
}
const round = (x, n = 6) => Math.round(x * 10 ** n) / 10 ** n;

// ===========================================================================
// 1 · BRAESS — the road. Selfish equilibrium vs a planner's optimum.
//     (the-road-that-made-everyone-late; research/braess/engine.mjs)
// ===========================================================================
console.log('\n# 1 · BRAESS — the road (the-road-that-made-everyone-late)');
const E = (u, v, a, b) => ({ u, v, a, b });
const base4000 = { S: 'S', T: 'T', demand: 4000, edges: [
  E('S','A',1/100,0), E('A','T',0,45), E('S','B',0,45), E('B','T',1/100,0) ] };
const bridged4000 = { ...base4000, edges: [ ...base4000.edges, E('A','B',0,0) ] };

const braessNoBridge = userEquilibrium(base4000);
const braessSelfish  = userEquilibrium(bridged4000);
const braessOptimum  = systemOptimum(bridged4000);

// The number the portal shows the reader "before" (with the free shortcut open):
check('Braess selfish equilibrium, per driver = 80 min', round(braessSelfish.perCapita, 4), 80, 1e-3);
// The number after the CONSTRAINT (close the shortcut) — everyone is better off:
check('Braess after the cure (shortcut closed) = 65 min', round(braessNoBridge.perCapita, 4), 65, 1e-3);
check('Braess: closing a road strictly helps (65 < 80)', braessNoBridge.perCapita < braessSelfish.perCapita, true);
// The planner's optimum on the SAME bridged network (drivers can't reach it alone):
check('Braess system optimum (bridged) = 64.6875 min', round(braessOptimum.perCapita, 4), 64.6875, 1e-3);
// The price of anarchy for THIS instance:
const braessPoA = braessSelfish.total / braessOptimum.total;
check('Braess instance price of anarchy = 256/207', round(braessPoA, 6), round(256/207, 6), 1e-4);
check('Braess PoA ≈ 1.237', round(braessPoA, 3), 1.237, 1e-3);

// The class-wide TIGHT bound: affine costs can never exceed 4/3, and the unit
// network attains it exactly. This is the "bounded anarchy" half of claim (B).
const baseUnit    = { S: 'S', T: 'T', demand: 1, edges: [
  E('S','A',1,0), E('A','T',0,1), E('S','B',0,1), E('B','T',1,0) ] };
const bridgedUnit = { ...baseUnit, edges: [ ...baseUnit.edges, E('A','B',0,0) ] };
const unitSelfish = userEquilibrium(bridgedUnit);
const unitOpt     = systemOptimum(bridgedUnit);
const unitPoA     = unitSelfish.total / unitOpt.total;
check('Braess unit-network PoA = 4/3 exactly (tight bound)', round(unitPoA, 6), round(4/3, 6), 1e-4);
check('affine PoA is bounded: instance ≤ 4/3', braessPoA <= 4/3 + 1e-9, true);

// ===========================================================================
// 2 · COMMONS — the pasture. Cournot/open-access equilibrium vs the sole owner.
//     (tragedy-of-the-commons; closed forms re-derived here)
//     Value V(X) = X·(a − bX); a=100, b=1. Sole owner maximizes → Xopt=a/2b=50,
//     Vopt=a²/4b=2500. n identical open-access herders play Cournot; efficiency
//     at the Nash herd is 4n/(n+1)². Its price of anarchy is the reciprocal,
//     (n+1)²/4n, which GROWS WITHOUT BOUND — the "unbounded anarchy" half of (B).
// ===========================================================================
console.log('\n# 2 · COMMONS — the pasture (tragedy-of-the-commons)');
const a = 100, b = 1;
const V     = (X) => X * (a - b * X);
const Xopt  = a / (2 * b);            // 50
const Vopt  = (a * a) / (4 * b);      // 2500
const Xnash = (n) => (n / (n + 1)) * (a / b);          // total open-access herd
const eff   = (n) => 4 * n / ((n + 1) * (n + 1));      // V(Xnash)/Vopt
const commonsPoA = (n) => 1 / eff(n);                  // = (n+1)²/4n

check('Commons sole-owner optimum herd Xopt = 50', Xopt, 50);
check('Commons sole-owner maximum value Vopt = 2500', Vopt, 2500);
check('Commons V(Xopt) equals Vopt', V(Xopt), 2500);
// efficiency closed form vs direct value ratio, several n:
for (const n of [1, 2, 4, 10, 100]) {
  check(`Commons efficiency 4n/(n+1)² == V(Xnash)/Vopt at n=${n}`, round(V(Xnash(n)) / Vopt, 9), round(eff(n), 9), 1e-9);
}
check('Commons eff(1) = 100% (sole owner reaches the optimum)', eff(1), 1);
check('Commons eff(4) = 64%', round(eff(4), 4), 0.64, 1e-9);
check('Commons eff(100) ≈ 3.92%', round(eff(100), 4), round(400/10201, 4), 1e-4);
// value is monotonically dissipated as the crowd grows:
let monoDown = true;
for (let n = 1; n < 200; n++) if (V(Xnash(n + 1)) > V(Xnash(n)) + 1e-9) monoDown = false;
check('Commons: shared value falls monotonically as n grows', monoDown, true);
// THE cross-cutting contrast: commons PoA is UNBOUNDED (exceeds Braess's 4/3 ceiling
// and keeps climbing), unlike affine routing.
check('Commons PoA at n=4 = 25/16 = 1.5625 (already past 4/3)', round(commonsPoA(4), 6), round(25/16, 6), 1e-9);
check('Commons PoA is unbounded: PoA(1000) > 250', commonsPoA(1000) > 250, true);
check('Commons PoA grows without ceiling: PoA(n) strictly increasing for n≥1', (() => {
  for (let n = 1; n < 500; n++) if (commonsPoA(n + 1) <= commonsPoA(n)) return false; return true;
})(), true);

// ===========================================================================
// 3 · PHANTOM JAM — the ring. An INSTABILITY, not an equilibrium. No PoA ratio.
//     (phantom-traffic-jam; research/phantom-traffic-jam/idm.mjs)
//     Identical cars, no bottleneck. Below a critical density a small nudge decays;
//     above it, a stop-and-go cluster crystallizes from nothing and crawls BACKWARD.
//     The cure is still a CONSTRAINT: patient spacing (a larger safe headway T)
//     restabilizes the *identical* road.
// ===========================================================================
console.log('\n# 3 · PHANTOM JAM — the ring (phantom-traffic-jam)');
const L = 1000;                 // ring length, m
const dt = 0.1;                 // s, ballistic integrator (Treiber)

// Run a ring of N cars with params p, seed one 0.5 m/s nudge, warm up, then report
// the velocity spread (max−min) over a measurement window. spread≈0 ⇒ stable.
function ringSpread(N, p = PARAMS, warmup = 900, measure = 300) {
  const st = initRing(N, L, 0.5, p);
  const nWarm = Math.round(warmup / dt), nMeas = Math.round(measure / dt);
  for (let k = 0; k < nWarm; k++) step(st, dt, p);
  let mn = Infinity, mx = -Infinity;
  for (let k = 0; k < nMeas; k++) {
    step(st, dt, p);
    for (let i = 0; i < N; i++) { if (st.v[i] < mn) mn = st.v[i]; if (st.v[i] > mx) mx = st.v[i]; }
  }
  return mx - mn;                // m/s
}

// Below the critical density the nudge decays (uniform flow is stable):
const spreadStable = ringSpread(20);
check('Phantom: N=20 (20/km) stays smooth — nudge decays (spread < 1 m/s)', spreadStable < 1, true);
// Above it, the same nudge on the same road blows up into a jam:
const spreadJam = ringSpread(45);
check('Phantom: N=45 (45/km) jams from the same nudge (spread > 10 m/s)', spreadJam > 10, true);
check('Phantom: crossing a density threshold flips stable→jam (jam spread ≫ stable)', spreadJam > spreadStable + 9, true);

// THE CURE is a constraint: give the SAME 45-car ring a larger safe headway T
// (patient / adaptive spacing) and the instability is suppressed — same road, same
// cars, one bounded reaction. Confirm a patient fleet restabilizes.
// Empirically, N=45 restabilizes once the safe headway reaches ~2.6 s; at 2.8 s the
// velocity spread collapses to < 0.25 m/s (measured across T=1.5…3.5 — see facts.md).
const patient = { ...PARAMS, T: 2.8 };   // 1.5 s → 2.8 s safe headway
const spreadPatient = ringSpread(45, patient);
check('Phantom cure: patient spacing (T 1.5→2.8 s) restabilizes the SAME jammed ring', spreadPatient < 1, true);
check('Phantom cure strictly helps: patient spread ≪ selfish spread', spreadPatient < spreadJam - 9, true);

// The jam that does form crawls BACKWARD against the flow. Track the slowest car's
// cluster drift sign over the ring (unwrapped) — negative = upstream.
function backwardWave(N, p = PARAMS, warmup = 900, measure = 300) {
  const st = initRing(N, L, 0.5, p);
  const nWarm = Math.round(warmup / dt), nMeas = Math.round(measure / dt);
  for (let k = 0; k < nWarm; k++) step(st, dt, p);
  // jam centre = position of the minimum-speed car; unwrap its motion.
  let prev = null, unwrapped = 0, t0 = null, x0 = null;
  const centre = () => { let mi = 0; for (let i = 1; i < N; i++) if (st.v[i] < st.v[mi]) mi = i; return st.x[mi]; };
  for (let k = 0; k < nMeas; k++) {
    step(st, dt, p);
    const c = centre();
    if (prev !== null) { let d = c - prev; if (d > L / 2) d -= L; if (d < -L / 2) d += L; unwrapped += d; }
    prev = c;
    if (t0 === null) { t0 = 0; x0 = 0; }
  }
  return unwrapped / measure;     // m/s, signed
}
const wave = backwardWave(50);
check('Phantom: the jam wave travels BACKWARD (drift < 0)', wave < 0, true);
// magnitude is in the observed ballpark (model ≈ −13 km/h; real highways −15…−20).
check('Phantom: backward wave speed is a few m/s upstream (|v| between 1 and 8 m/s)',
  Math.abs(wave) > 1 && Math.abs(wave) < 8, true);

// ===========================================================================
// 4 · CALIBRATION — the statistic recovers a known answer (so a green run means
//     something). A single owner is not an anarchy: PoA must be exactly 1.
// ===========================================================================
console.log('\n# 4 · CALIBRATION');
check('Sole owner (n=1) is not an anarchy: price of anarchy = 1', round(commonsPoA(1), 9), 1, 1e-9);
check('Removing Braess bridge cannot make an affine net worse than 4/3', braessNoBridge.perCapita <= braessSelfish.perCapita, true);
// A trivial one-path Braess-style net has no anarchy either (selfish == optimal):
const trivial = { S: 'S', T: 'T', demand: 10, edges: [ E('S','T', 1/100, 0) ] };
check('Calibration: single-road net has PoA = 1 (no coordination gap)',
  round(userEquilibrium(trivial).total / systemOptimum(trivial).total, 6), 1, 1e-4);

// ===========================================================================
console.log(`\n${fail === 0 ? 'ALL PASSED' : 'FAILURES PRESENT'} — ${pass}/${pass + fail} checks`);
process.exit(fail === 0 ? 0 : 1);
