// research/harmonic-flow/verify.mjs
// De-risks "Every Triangle Agreed": the harmonic component of a comparison flow.
//
// Every number the instrument prints is recomputed here from first principles and
// cross-checked, including the orthogonality (Pythagoras) of the three-way split
// and the DEFINING properties of the harmonic flow (div-free AND curl-free, yet
// nonzero). The Penney curl fraction is re-derived independently and checked
// against the sibling layer's published 55.8%.
//
//   node research/harmonic-flow/verify.mjs

import { hodge, flowFromP } from './hodge.mjs';

let pass = 0, fail = 0;
const EPS = 1e-9;
function ok(cond, msg) { (cond ? (pass++, console.log('  ✓ ' + msg)) : (fail++, console.error('  ✗ ' + msg))); }
function near(a, b, tol, msg) { ok(Math.abs(a - b) <= (tol ?? EPS), `${msg}  (${a.toFixed(6)} ≈ ${b.toFixed(6)})`); }
const maxAbs = (v) => v.reduce((m, x) => Math.max(m, Math.abs(x)), 0);

// ---- the three defining checks every decomposition must pass ---------------
function structural(label, n, edges) {
  const h = hodge(n, edges);
  const { gradient: eG, curl: eC, harmonic: eH, total: eY } = h.energy;
  console.log(`\n[${label}]  edges=${edges.length} triangles=${h.triangles}  ` +
    `grad=${(100 * h.fraction.gradient).toFixed(1)}% curl=${(100 * h.fraction.curl).toFixed(1)}% harm=${(100 * h.fraction.harmonic).toFixed(1)}%`);
  // Pythagoras: the three pieces are L2-orthogonal ⇒ energies add to the total.
  near(eG + eC + eH, eY, 1e-7 * (eY + 1), `${label}: ‖grad‖²+‖curl‖²+‖harm‖² = ‖Y‖²`);
  // The harmonic flow is div-free (orthogonal to every ranking)...
  ok(maxAbs(h._diag.divOfHarm) < 1e-6, `${label}: harmonic is div-free (no source/sink)`);
  // ...and curl-free (sums to zero around every measured triangle).
  ok(maxAbs(h._diag.curlOfHarm) < 1e-6, `${label}: harmonic is curl-free (every triangle agrees)`);
  return h;
}

console.log('=== I. The three known regimes (complete graphs: harmonic must vanish) ===');

// Rock–paper–scissors: K3 with a pure cycle. All curl, no gradient, no harmonic.
{
  const w = 0.85, l = Math.log(w / (1 - w));
  const h = structural('rock-paper-scissors', 3, [[0, 1, l], [1, 2, l], [0, 2, -l]]);
  near(h.fraction.curl, 1, 1e-9, 'RPS: 100% curl');
  near(h.fraction.gradient, 0, 1e-9, 'RPS: 0% gradient');
  near(h.fraction.harmonic, 0, 1e-9, 'RPS: 0% harmonic (complete graph)');
}

// Clean ladder: complete, transitive. All gradient.
{
  const s = [1.5, 0.5, -0.5, -1.5], edges = [];
  for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) edges.push([i, j, s[i] - s[j]]);
  const h = structural('ladder (transitive)', 4, edges);
  near(h.fraction.gradient, 1, 1e-9, 'ladder: 100% gradient');
  near(h.fraction.curl, 0, 1e-9, 'ladder: 0% curl');
  near(h.fraction.harmonic, 0, 1e-9, 'ladder: 0% harmonic');
  // and the recovered potential reproduces the planted ranking order
  const ord = [...h.s.keys()].sort((a, b) => h.s[b] - h.s[a]);
  ok(JSON.stringify(ord) === JSON.stringify([0, 1, 2, 3]), 'ladder: recovered ranking = planted order');
}

console.log('\n=== II. The harmonic regime (holes in the graph) — the new ground ===');

// THE canonical harmonic flow: a 4-cycle (square) with NO diagonals → no triangle.
// A unit circulation A→B→C→D→A is div-free and (vacuously) curl-free, yet nonzero:
// it loops the hole. Pure harmonic.
{
  const sq = [[0, 1, 1], [1, 2, 1], [2, 3, 1], [0, 3, -1]]; // 0→1→2→3→0 (edge (0,3) carries 3→0 = −1)
  const h = structural('bare square (4-cycle, no diagonals)', 4, sq);
  ok(h.triangles === 0, 'square: 0 triangles (no comparison closes a face)');
  near(h.fraction.harmonic, 1, 1e-9, 'square: 100% harmonic — the loop in the hole');
  near(h.fraction.curl, 0, 1e-9, 'square: 0% curl');
  near(h.fraction.gradient, 0, 1e-9, 'square: 0% gradient');
}

// Pentagon (5-cycle, no chords): also pure harmonic. Holes of any size loop.
{
  const pent = [[0, 1, 1], [1, 2, 1], [2, 3, 1], [3, 4, 1], [0, 4, -1]];
  const h = structural('bare pentagon (5-cycle)', 5, pent);
  near(h.fraction.harmonic, 1, 1e-9, 'pentagon: 100% harmonic');
}

// Closing the hole: take the square's cycle and ADD one diagonal (a measurement).
// Two triangles appear; the harmonic loop becomes detectable curl. Harmonic falls,
// curl rises, gradient stays ~0. This is the instrument's core demonstration.
{
  const open = hodge(4, [[0, 1, 1], [1, 2, 1], [2, 3, 1], [0, 3, -1]]);
  const closed = hodge(4, [[0, 1, 1], [1, 2, 1], [2, 3, 1], [0, 3, -1], [0, 2, 0]]); // add diagonal (0,2), flow 0
  console.log(`\n[closing the hole]  open harm=${(100 * open.fraction.harmonic).toFixed(1)}% ` +
    `→ closed harm=${(100 * closed.fraction.harmonic).toFixed(1)}% curl=${(100 * closed.fraction.curl).toFixed(1)}%`);
  ok(closed.triangles === 2, 'adding the diagonal creates 2 triangles');
  ok(closed.fraction.harmonic < open.fraction.harmonic - 0.2, 'measuring the missing pair drains the harmonic flow');
  ok(closed.fraction.curl > 0.2, '…it reappears as curl the triangles can now see');
  near(closed.fraction.gradient, 0, 1e-6, 'closed: still no honest ranking (gradient ~0)');
}

// "Every triangle agreed, the whole disagreed": a graph WITH triangles that are
// each individually consistent, yet whose homology has holes. The triangular
// prism K3×K2 — two triangular faces {0,1,2},{3,4,5} joined by verticals 0-3,
// 1-4, 2-5 — has two filled faces but its three square sides are unfilled, giving
// a 2-dimensional harmonic space (first Betti number b1 = 2). A flow can loop a
// side face: curl-free on both triangles, div-free, yet nonzero. Pure harmonic.
{
  // a unit circulation around the side face 0-1-4-3-0 (a square, no diagonal)
  const prism = [
    [0, 1, 1], [1, 2, 0], [0, 2, 0],   // top triangle {0,1,2}
    [3, 4, 0], [4, 5, 0], [3, 5, 0],   // bottom triangle {3,4,5}
    [0, 3, -1], [1, 4, -1], [2, 5, 0], // verticals; loop 0→1→4→3→0
  ];
  const h = structural('triangular prism (2 faces, holey sides)', 6, prism);
  ok(h.triangles === 2, 'exactly two triangular faces');
  ok(h.harmonicDim === 2, 'harmonic space is 2-dimensional (first Betti number = 2)');
  ok(maxAbs(h._diag.curlOfHarm) < 1e-6, 'the harmonic part has zero curl on every face…');
  ok(h.fraction.harmonic > 0.1, '…yet a real flow keeps a harmonic share the faces cannot see (>10%)');
}

console.log('\n=== III. Cross-check the sibling layer: Penney’s eight = 55.8% curl ===');

// Penney's game: P(i beats j) from Conway's leading numbers (independent re-impl).
function corr(X, Y) { let t = 0; for (let k = 1; k <= X.length; k++) if (X.slice(-k) === Y.slice(0, k)) t += 2 ** (k - 1); return t; }
function penneyFirst(A, B) { const AA = corr(A, A), AB = corr(A, B), BA = corr(B, A), BB = corr(B, B); const num = BB - BA; return num / (num + (AA - AB)); }
const seqs3 = [...'01234567'].map((_, i) => i.toString(2).padStart(3, '0').replace(/0/g, 'H').replace(/1/g, 'T'));
const Ppen = Array.from({ length: 8 }, (_, i) => Array.from({ length: 8 }, (_, j) => i === j ? 0.5 : penneyFirst(seqs3[i], seqs3[j])));
{
  const { n, edges } = flowFromP(Ppen);
  const h = structural("penney's eight (complete K8)", n, edges);
  near(h.fraction.harmonic, 0, 1e-9, 'Penney: harmonic = 0 (complete graph, as siblings assume)');
  near(100 * h.fraction.curl, 55.8, 0.1, "Penney: curl fraction = 55.8% — matches No King of the Hill");
}

// Sanity: my general code must equal the sibling's complete-graph shortcut
// (row-mean rating ⇒ gradient = r_i − r_j, curl = residual) to machine precision,
// for an arbitrary skill+cycle mix. If these agree, the new code is anchored to
// the already-verified one.
{
  const sig = (x) => 1 / (1 + Math.exp(-x));
  const sk = [2.2, 0.9, 0, -0.9, -2.2];
  const P = Array.from({ length: 5 }, (_, i) => Array.from({ length: 5 }, (_, j) => i === j ? 0.5 : sig(sk[i] - sk[j])));
  const w = 0.78, mid = [1, 2, 3];
  for (let k = 0; k < 3; k++) { const i = mid[k], j = mid[(k + 1) % 3]; P[i][j] = w; P[j][i] = 1 - w; } // spinning top
  // sibling shortcut:
  const Y = P.map((row, i) => row.map((p, j) => i === j ? 0 : Math.log(p / (1 - p))));
  const r = Y.map((row) => row.reduce((a, b) => a + b, 0) / 5);
  let eY = 0, eC = 0; for (let i = 0; i < 5; i++) for (let j = i + 1; j < 5; j++) { const g = r[i] - r[j], c = Y[i][j] - g; eY += Y[i][j] ** 2; eC += c ** 2; }
  const siblingCurl = eC / eY;
  const { n, edges } = flowFromP(P);
  const h = hodge(n, edges);
  console.log(`\n[spinning top]  general curl=${(100 * h.fraction.curl).toFixed(3)}%  sibling shortcut=${(100 * siblingCurl).toFixed(3)}%`);
  near(h.fraction.curl, siblingCurl, 1e-9, 'general decomposition = sibling complete-graph shortcut');
  near(h.fraction.harmonic, 0, 1e-9, 'spinning top: harmonic 0 (complete graph)');
}

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