// verify-the-shortcut-it-refused.mjs
//
// Recomputes — from the real Tero adaptive-flow ODE and first-principles graph
// algorithms — every number the page public/strata/the-shortcut-it-refused/ shows.
// No dependencies:  node research/the-shortcut-it-refused/verify-the-shortcut-it-refused.mjs
//
// Two claims held in tension (the piece's whole point):
//   (1) THEOREM (Bonifaci–Mehlhorn–Varma 2012). With linear reinforcement f(Q)=|Q|,
//       the Tero dynamics converges to the shortest source–sink path on a graph with a
//       unique shortest path — a provable natural algorithm. We run the very dynamics
//       and check its surviving tube == Dijkstra's path, on the page's maze, on the
//       historic Nakagaki 4-route maze, and on random mazes.
//   (2) NO OPTIMUM ON MANY CITIES. On a 36-city "Tokyo-like" dish the grown network
//       OVERSPENDS the minimum spanning tree by ~78% (cost ≈ 1.78× MST) to buy
//       robustness — it is NOT the MST and does not try to be. Every scorecard the
//       page prints (cost, detour, fault tolerance) is recomputed here on the same
//       layout, seed and parameters.
//
// The living-organism figures from Tero et al. 2010 (≈1.8× MST, MD≈0.85, fault
// tolerance ~14% vs the real rail's ~4%) are CITATIONS, recorded in README.md — this
// script reproduces the MODEL's numbers, it does not assert the biology.

import {
  mulberry32, dist, delaunayEdges, gabrielEdges, mstLength, primLength, dijkstra,
  runTwoTerminal, runDish, score, bridgeFraction,
} from './model.mjs';

let pass = 0, total = 0;
function check(name, cond, got) {
  total++;
  if (cond) { pass++; console.log(`  ✓ ${name}${got !== undefined ? '  → ' + got : ''}`); }
  else { console.log(`  ✗ ${name}  → ${got}`); }
}
const near = (a, b, tol) => Math.abs(a - b) <= tol;

// ── the exact layouts embedded in the page ──────────────────────────────────────
const CITIES = [[54.98,50.29],[65.02,48.24],[39.61,48.87],[42.34,51.32],[35.19,45.88],[49.68,55.19],[51.09,40.2],[53.22,57.48],[46.63,59.68],[44.36,65.06],[50.28,64.43],[52.29,54.69],[54.88,55.72],[34.54,46.16],[81.12,50.79],[70.74,66.26],[57.88,76.06],[42.29,75.71],[33.1,62.5],[27.02,59.52],[28.12,46.8],[24.84,36.62],[40.35,29.23],[55.86,23.73],[70.82,32.98],[73.63,41.71],[85.57,51.33],[73.47,76.74],[60.57,86.2],[36.07,78.43],[8.92,66.65],[6.67,43.53],[19.44,20.23],[38.88,15.08],[71.78,14.87],[91.53,36.77]].map(([x,y])=>({x,y}));

const MAZE_COLS = 8, MAZE_ROWS = 6;
const MAZE_PTS = [[0.57,0.82],[9.16,0.37],[18.76,0.28],[30.66,-0.13],[41.22,-0.81],[50.84,0.72],[60.48,-1.46],[69.9,-0.6],[1.19,9.36],[10.77,10.67],[19.26,8.56],[30.88,9.12],[39.32,8.87],[49.91,11.47],[59.24,8.74],[71.05,9.45],[-0.28,21.46],[9.32,19.66],[19.15,21.11],[30.67,21.14],[40.03,20.92],[50.45,18.92],[60.41,20.23],[69.45,20.84],[0.33,28.52],[11.3,29.52],[19.55,31.12],[29.25,29.03],[41,29.34],[51.49,28.54],[59.55,30.78],[69.44,30.48],[-1.27,38.74],[10.7,40.07],[19.26,41.29],[28.65,40.7],[41.36,39.36],[50.1,41.07],[61.04,40.24],[71.37,40.61],[0.12,48.83],[9.38,50.09],[18.97,49.26],[30.8,48.92],[38.74,49.48],[50.92,50.43],[59.74,48.79],[69.37,51.37]].map(([x,y])=>({x,y}));
const MAZE_EDGES_IDX = [[0,1],[0,8],[1,2],[2,3],[2,10],[3,4],[4,5],[4,12],[5,13],[6,7],[6,14],[7,15],[8,16],[9,17],[10,11],[10,18],[11,12],[12,13],[12,20],[13,14],[13,21],[14,15],[14,22],[15,23],[16,17],[16,24],[17,18],[18,19],[18,26],[19,27],[20,21],[20,28],[21,22],[21,29],[22,23],[22,30],[23,31],[24,25],[25,26],[26,27],[26,34],[27,28],[28,29],[28,36],[29,30],[29,37],[30,31],[30,38],[31,39],[32,33],[32,40],[33,34],[33,41],[34,35],[35,36],[35,43],[36,37],[36,44],[37,38],[37,45],[38,39],[38,46],[39,47],[40,41],[41,42],[42,43],[44,45],[45,46]];
const mazeEdges = MAZE_EDGES_IDX.map(([a, b]) => ({ a, b, L: dist(MAZE_PTS[a], MAZE_PTS[b]) }));
const MAZE_S = 40, MAZE_T = 7;                       // bottom-left ↔ top-right

// shared parameters (identical to the page's inline copy) ─────────────────────────
const DISH = { a: 25, mu: 1.6, keepFrac: 0.06, steps: 3000, dt: 0.04, seed: 999, D0: 0.5 };
const MAZEP = { steps: 8000, dt: 0.15, keepFrac: 0.5, D0: 1 };

// ══════════════════════════════════════════════════════════════════════════════
console.log('\nA.  THE THEOREM — the linear Tero ODE computes the shortest path (Bonifaci–Mehlhorn–Varma 2012)\n');

// A1 — the page's maze: surviving tube == Dijkstra's path, to the last edge.
{
  const n = MAZE_PTS.length;
  const dj = dijkstra(n, mazeEdges, MAZE_S, MAZE_T);
  const res = runTwoTerminal(n, mazeEdges, MAZE_S, MAZE_T, MAZEP);
  const kept = [...res.kept].sort((a, b) => a - b), path = [...dj.pathEdges].sort((a, b) => a - b);
  const same = kept.length === path.length && kept.every((e, i) => e === path[i]);
  let keptLen = 0; for (const e of res.kept) keptLen += mazeEdges[e].L;
  check('page maze: ODE tube == Dijkstra edge set', same, `${kept.length} edges`);
  check('page maze: surviving length == shortest', near(keptLen, dj.dist, 1e-6), `${keptLen.toFixed(2)} vs ${dj.dist.toFixed(2)} units`);
  check('page maze: shortest length is 115.96 units', near(dj.dist, 115.96, 0.01), dj.dist.toFixed(2));
}

// A2 — Nakagaki, Yamada & Tóth 2000 (Nature 407:470): four routes 41/33/44/45 mm,
// the mould retracts to the single shortest tube (α₂ = 33 mm).
{
  const NAK = [41, 33, 44, 45];                     // α₁, α₂, β₁, β₂  (mm)
  const nEdges = NAK.map((L) => ({ a: 0, b: 1, L }));
  const dj = dijkstra(2, nEdges, 0, 1);
  const res = runTwoTerminal(2, nEdges, 0, 1, { ...MAZEP, steps: 6000 });
  const kept = [...res.kept];
  check('Nakagaki: shortest of {41,33,44,45} is 33 mm (α₂)', Math.min(...NAK) === 33 && dj.dist === 33, `min=${Math.min(...NAK)}`);
  check('Nakagaki: ODE keeps exactly the 33 mm route', kept.length === 1 && NAK[kept[0]] === 33, `route ${kept[0]} = ${NAK[kept[0]]} mm`);
}

// A3 — the theorem in general: on random jittered mazes the tube always == Dijkstra.
{
  function maze(cols, rows, seed, wallFrac) {
    const r = mulberry32(seed); const pts = [];
    for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) pts.push({ x: x * 10 + (r() - 0.5) * 3, y: y * 10 + (r() - 0.5) * 3 });
    const id = (x, y) => y * cols + x; const edges = [];
    for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
      if (x + 1 < cols && r() > wallFrac) edges.push({ a: id(x, y), b: id(x + 1, y), L: dist(pts[id(x, y)], pts[id(x + 1, y)]) });
      if (y + 1 < rows && r() > wallFrac) edges.push({ a: id(x, y), b: id(x, y + 1), L: dist(pts[id(x, y)], pts[id(x, y + 1)]) });
    }
    return { pts, edges, id };
  }
  let ok = 0, tried = 0;
  for (const seed of [2, 3, 4, 5, 6, 8, 9, 11, 12, 13]) {
    const { pts, edges, id } = maze(7, 5, seed, 0.18); const n = pts.length;
    const s = id(0, 0), t = id(6, 4);
    const dj = dijkstra(n, edges, s, t); if (dj.dist === Infinity) continue; tried++;
    const res = runTwoTerminal(n, edges, s, t, MAZEP);
    const k = [...res.kept].sort((a, b) => a - b), d = [...dj.pathEdges].sort((a, b) => a - b);
    if (k.length === d.length && k.every((e, i) => e === d[i])) ok++;
  }
  check(`${tried} random mazes: every ODE tube == its Dijkstra path`, ok === tried, `${ok}/${tried}`);
}

// ══════════════════════════════════════════════════════════════════════════════
console.log('\nB.  THE FRONTIER — 36 "Tokyo-like" cities: the mould refuses the minimum network\n');

const cand = delaunayEdges(CITIES);
const mstK = mstLength(CITIES.length, cand);
const mstP = primLength(CITIES.length, cand);
const delTotal = cand.reduce((s, e) => s + e.L, 0);

// B1 — the MST length two independent ways (Kruskal vs Prim) must agree.
check('MST length: Kruskal == Prim', near(mstK.length, mstP.length, 1e-9) && mstK.connected, `${mstK.length.toFixed(2)} units`);
check('candidate graph is 95 Delaunay tubes', cand.length === 95, `${cand.length} edges, Gabriel ${gabrielEdges(CITIES).length}`);

// B2 — the "connect everything" ceiling: full Delaunay ≈ 3.94× MST.
check('full Delaunay net = 3.94× MST (the wasteful ceiling)', near(delTotal / mstK.length, 3.94, 0.01), (delTotal / mstK.length).toFixed(3) + '×');

// B3 — the MST is all-bridges: FT = 100% (every single cut orphans a branch).
{
  const ft = bridgeFraction(CITIES.length, mstK.edges);
  check('MST fault tolerance = 100% (35/35 links fatal)', ft.fraction === 1 && ft.total === 35, `${ft.bridges}/${ft.total}`);
}

// B4 — THE MOULD (default I0 = 0.50): cost 1.78× MST, detour 1.26, connected, FT 0%.
{
  const { kept } = runDish(CITIES, cand, { ...DISH, I0: 0.50 });
  const sc = score(CITIES, cand, kept);
  check('mould cost = 1.78× MST (overspends by ~78%, NOT the MST)', near(sc.costRatio, 1.784, 0.01), sc.costRatio.toFixed(3) + '×');
  check('mould total length = 616.5 units', near(sc.TL, 616.55, 0.5), sc.TL.toFixed(1));
  check('mould detour (transport efficiency) = 1.26', near(sc.detour, 1.258, 0.005), sc.detour.toFixed(3));
  check('mould spans all 36 cities (1 component)', sc.components === 1, `${sc.edges} tubes`);
  check('mould fault tolerance = 0% (idealised: every tube on a loop)', sc.FT === 0 && sc.bridges === 0, `${sc.bridges}/${sc.edges} fatal`);
}

// B5 — LEAN end of the frontier (I0 = 0.10): cheaper but fragile (FT ≈ 12%).
{
  const { kept } = runDish(CITIES, cand, { ...DISH, I0: 0.10 });
  const sc = score(CITIES, cand, kept);
  check('lean network cost = 1.32× MST', near(sc.costRatio, 1.319, 0.01), sc.costRatio.toFixed(3) + '×');
  check('lean network fault tolerance = 12% (5/41 links fatal)', sc.bridges === 5 && near(sc.FT, 5 / 41, 1e-9), `${(sc.FT * 100).toFixed(0)}%`);
  check('lean network still spans all cities', sc.components === 1, `${sc.edges} tubes`);
}

// B6 — REDUNDANT end (I0 = 1.20): even more track, still FT 0.
let costRedundant;
{
  const { kept } = runDish(CITIES, cand, { ...DISH, I0: 1.20 });
  const sc = score(CITIES, cand, kept);
  costRedundant = sc.costRatio;
  check('redundant network cost = 2.55× MST', near(sc.costRatio, 2.548, 0.01), sc.costRatio.toFixed(3) + '×');
}

// B7 — monotone frontier: cost rises with I0, and NEVER touches the MST (always > 1).
{
  const costs = [0.10, 0.50, 1.20].map((I0) => score(CITIES, cand, runDish(CITIES, cand, { ...DISH, I0 }).kept).costRatio);
  const mono = costs[0] < costs[1] && costs[1] < costs[2];
  const above = costs.every((c) => c > 1.0);
  check('frontier is monotone in I0 and always overspends the MST', mono && above, costs.map((c) => c.toFixed(2) + '×').join(' < '));
}

// ══════════════════════════════════════════════════════════════════════════════
console.log(`\n${pass}/${total} PASS`);
if (pass !== total) process.exit(1);
