// verify.mjs — every number that appears on /strata/braess, recomputed.
// Run: node research/braess/verify.mjs   ->  prints PASS/FAIL per check + tally.
//
// Two independent methods agree throughout:
//   (A) closed-form, derived by hand in the comments below;
//   (B) the general Frank–Wolfe solver in engine.mjs (convex => global optimum),
//       which knows nothing about these particular networks.

import { userEquilibrium, systemOptimum, simplePaths, totalCost } from './engine.mjs';

let pass = 0, fail = 0;
const approx = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps * Math.max(1, Math.abs(b));
function check(name, got, want, eps = 1e-6) {
  const ok = (typeof want === 'number') ? approx(got, want, eps) : (got === want);
  console.log(`${ok ? 'PASS' : 'FAIL'}  ${name}  ->  ${got}${ok ? '' : `  (want ${want})`}`);
  ok ? pass++ : fail++;
}

// ---------------------------------------------------------------------------
// 1) The textbook "4000 drivers" network (popularized form; minutes).
//    Nodes S,A,B,T.  Edges:
//      S->A : x/100      (congestible)         a=1/100 b=0
//      A->T : 45         (constant)            a=0     b=45
//      S->B : 45         (constant)            a=0     b=45
//      B->T : x/100      (congestible)         a=1/100 b=0
//      A->B : 0          (the new road)        a=0     b=0
//    Demand = 4000.
// ---------------------------------------------------------------------------
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) ] };

// Closed form, no bridge: symmetric split 2000/2000, each path 2000/100+45 = 65.
{
  const ue = userEquilibrium(base4000);
  check('4000 no-bridge: per-driver minutes (closed form 65)', Math.round(ue.perCapita * 1e6) / 1e6, 65, 1e-4);
  check('4000 no-bridge: total veh-min (4000*65)', Math.round(ue.total), 260000, 1e-9);
}
// Closed form, with bridge: unique eq routes all 4000 on S->A->B->T,
// each = 4000/100 + 0 + 4000/100 = 80; deviating to either old route costs 85.
{
  const ue = userEquilibrium(bridged4000);
  check('4000 with-bridge: per-driver minutes (closed form 80)', Math.round(ue.perCapita * 1e6) / 1e6, 80, 1e-4);
  check('4000 with-bridge: total veh-min (4000*80)', Math.round(ue.total), 320000, 1e-3);
  // the paradox: adding a zero-cost road raised everyone's time 65 -> 80 (+23.08%)
  check('4000 paradox sign: bridged worse than base', ue.perCapita > 65 - 1e-6 ? 'worse' : 'better', 'worse');
  check('4000 paradox magnitude: +23.08%', Math.round((80 / 65 - 1) * 10000) / 100, 23.08, 0.01);
  // Instance price of anarchy. NOTE the social optimum does NOT simply split
  // 2000/2000 (=65); a planner routes w=1750 on each L-path and z=500 on the
  // zigzag, giving total 258750 veh-min = 64.6875/driver (closed form below).
  // So the bridged-net equilibrium 80 is 256/207 ~ 1.237x the optimum, still
  // under the affine class-wide tight bound 4/3.
  //   C(w) = 0.02(4000-w)^2 + 90w, minimized at w=1750 -> C=258750.
  const so = systemOptimum(bridged4000);
  check('4000 with-bridge: system optimum total veh-min = 258750', Math.round(so.total), 258750, 1e-9);
  check('4000 with-bridge: system optimum per-driver = 64.6875', Math.round(so.perCapita * 1e4) / 1e4, 64.6875, 1e-3);
  check('4000 instance PoA = 256/207', Math.round(ue.total / so.total * 1e6) / 1e6, 256/207, 1e-3);
  // and the planner's optimum still uses the zigzag for 500 of 4000 drivers
  const soZig = so.pathFlow[so.paths.findIndex(p => p.length === 3)];
  check('4000 optimum keeps 500 drivers on the zigzag', Math.round(soZig), 500, 1e-9);
}
// The deviation check that proves all-zigzag is a Nash equilibrium.
{
  // with everyone on S-A-B-T: x_SA = x_BT = 4000. A lone driver switching to
  // S-A-T pays x_SA/100 (still ~4000) + 45 = 85 > 80; symmetric for S-B-T.
  check('4000 deviation S-A-T costs 85 (>=80, so no incentive)', 4000/100 + 45, 85);
}

// ---------------------------------------------------------------------------
// 2) The normalized unit-demand network (the "1.5 -> 2.0" version).
//      S->A : x      A->T : 1      S->B : 1      B->T : x      A->B : 0
//      Demand = 1.
//    No bridge: split 1/2 each, cost 1/2 + 1 = 1.5.
//    With bridge: all on S->A->B->T, cost x+0+x = 1+1 = 2.0.
// ---------------------------------------------------------------------------
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 ue0 = userEquilibrium(baseUnit), ue1 = userEquilibrium(bridgedUnit);
  check('unit no-bridge: equilibrium latency 1.5', Math.round(ue0.perCapita * 1e6) / 1e6, 1.5, 1e-5);
  check('unit with-bridge: equilibrium latency 2.0', Math.round(ue1.perCapita * 1e6) / 1e6, 2.0, 1e-5);
}

// ---------------------------------------------------------------------------
// 3) Price of anarchy. For AFFINE costs the worst-case ratio
//    C(userEq)/C(systemOpt) is <= 4/3 (Roughgarden–Tardos 2002), and the
//    bridged unit network attains EXACTLY 4/3 — the tight instance.
//    System optimum of the bridged unit net: by symmetry route fraction p on
//    each of the two "L" paths (S-A-T, S-B-T) and 1-2p on the zigzag? Actually
//    the optimum simply ignores the zigzag and splits 1/2-1/2, total cost 1.5.
//    User eq uses the zigzag, total cost 2.0.  Ratio = 2.0/1.5 = 4/3.
// ---------------------------------------------------------------------------
{
  const ue = userEquilibrium(bridgedUnit), so = systemOptimum(bridgedUnit);
  check('bridged-unit user-eq total cost = 2.0', Math.round(ue.total * 1e6) / 1e6, 2.0, 1e-5);
  check('bridged-unit system-opt total cost = 1.5', Math.round(so.total * 1e6) / 1e6, 1.5, 1e-5);
  check('bridged-unit price of anarchy = 4/3', Math.round(ue.total / so.total * 1e6) / 1e6, 4/3, 1e-4);
  check('PoA within affine bound 4/3', ue.total / so.total <= 4/3 + 1e-6 ? 'within' : 'exceeds', 'within');
}

// ---------------------------------------------------------------------------
// 4) The strict harm band for unit demand and congestible slope 1.
//      S->A : x   A->T : c   S->B : c   B->T : x   A->B : 0,  demand 1.
//    No-bridge latency = 1/2 + c. With the bridge:
//      c <= 1/2: unused, latency 1/2 + c;
//      1/2 < c < 1: mixed routes, latency 2c;
//      c >= 1: all zigzag, latency 2.
//    Comparing times gives strict harm iff 1/2 < c < 3/2. At c <= 1/2
//    and c = 3/2 the time is unchanged; at c > 3/2 the bridge helps and
//    every driver uses it. The grid below also checks the low-cost regimes.
// ---------------------------------------------------------------------------
{
  const mk = (c, bridge) => ({ S:'S', T:'T', demand:1, edges:[
    E('S','A',1,0), E('A','T',0,c), E('S','B',0,c), E('B','T',1,0), ...(bridge?[E('A','B',0,0)]:[]) ] });
  // c = 1: no-bridge latency 1.5; bridged should be 2.0 (paradox, +33 1/3%)
  check('c=1: bridge raises latency 1.5 -> 2.0', Math.round(userEquilibrium(mk(1,true)).perCapita*1e4)/1e4, 2.0, 1e-3);
  // c = 1.5 (threshold): no-bridge = 2.0; bridged = 2.0 (bridge becomes neutral)
  check('c=1.5: no-bridge latency = 2.0', Math.round(userEquilibrium(mk(1.5,false)).perCapita*1e4)/1e4, 2.0, 1e-3);
  check('c=1.5: bridged latency = 2.0 (no longer worse)', Math.round(userEquilibrium(mk(1.5,true)).perCapita*1e4)/1e4, 2.0, 1e-3);
  // c = 2 (> threshold 3/2): the SAME bridge now HELPS. No-bridge eq = 1/2+2 = 2.5;
  // with the bridge the all-zigzag path costs only 2.0 (two congestible edges + free
  // link, independent of c) and drivers prefer it -> latency falls 2.5 -> 2.0. The
  // bridge that hurt for 1/2<c<3/2 helps at c>3/2. Upper harm boundary c* = 3/2.
  check('c=2: no-bridge latency = 2.5', Math.round(userEquilibrium(mk(2,false)).perCapita*1e4)/1e4, 2.5, 1e-3);
  check('c=2: bridged latency = 2.0 (now the bridge HELPS, 2.5 -> 2.0)', Math.round(userEquilibrium(mk(2,true)).perCapita*1e4)/1e4, 2.0, 1e-3);
}

// ---------------------------------------------------------------------------
// 5) Cross-check the solver against brute-force closed forms it can't "cheat":
//    enumerate paths and confirm the equal-latency Wardrop condition holds on
//    every USED path at the returned equilibrium.
// ---------------------------------------------------------------------------
{
  const net = bridged4000;
  const ue = userEquilibrium(net);
  const paths = simplePaths(net.edges, net.S, net.T);
  const lat = paths.map(p => p.reduce((L, ei) => L + net.edges[ei].a*ue.edgeFlow[ei] + net.edges[ei].b, 0));
  // the single used path (zigzag) carries all the flow; its latency is the min.
  const minLat = Math.min(...lat);
  check('Wardrop condition: equilibrium per-capita = min path latency', Math.round(ue.perCapita*1e4)/1e4, Math.round(minLat*1e4)/1e4, 1e-3);
}

// ---------------------------------------------------------------------------
// 6) Solver sanity: number of simple S->T paths.
// ---------------------------------------------------------------------------
check('no-bridge net has 2 simple S->T paths', simplePaths(base4000.edges,'S','T').length, 2);
check('bridged net has 3 simple S->T paths', simplePaths(bridged4000.edges,'S','T').length, 3);

// ---------------------------------------------------------------------------
// 7) The closed-form equilibrium the LIVE PAGE uses, cross-checked against the
//    general solver on a grid. Network: congestible slope s (cost s*x), constant
//    edges c, demand N, optional zero-cost bridge.
//      no bridge:  per-driver = s*N/2 + c            (split N/2 each)
//      bridge:     c <= s*N/2 -> s*N/2 + c  (bridge unused)
//                  s*N/2 < c < s*N -> 2c    (mixed: some keep the L-routes)
//                  c >= s*N -> 2*s*N        (all on the zigzag)
//    This is the exact function braessEquilibrium() reproduced in the page JS.
// ---------------------------------------------------------------------------
function braessEquilibrium({ s, c, N, bridge }) {
  const noBridge = s * N / 2 + c;
  if (!bridge) return noBridge;
  if (c <= s * N / 2) return noBridge;        // bridge ignored
  if (c >= s * N) return 2 * s * N;           // all zigzag
  return 2 * c;                                // mixed regime
}
{
  let gridOk = 0, gridBad = 0;
  for (const s of [1/100, 1/50, 1]) for (const N of [1, 100, 1000, 4000]) for (const cc of [0.1, 0.5, 1, 2, 5, 20, 45, 60, 100]) {
    for (const bridge of [false, true]) {
      const net = { S:'S', T:'T', demand:N, edges:[
        E('S','A',s,0), E('A','T',0,cc), E('S','B',0,cc), E('B','T',s,0), ...(bridge?[E('A','B',0,0)]:[]) ] };
      const solved = userEquilibrium(net).perCapita;
      const formula = braessEquilibrium({ s, c: cc, N, bridge });
      if (approx(solved, formula, 1e-3)) gridOk++; else { gridBad++; if (gridBad<=3) console.log(`  grid mismatch s=${s} N=${N} c=${cc} bridge=${bridge}: solver ${solved} vs formula ${formula}`); }
    }
  }
  check(`live-page formula matches solver on full grid (${gridOk} cells)`, gridBad, 0);
}

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