// ============================================================================
//  Find What Doesn't Change — verifier for the combine portal (P3).
//
//  THE SPINE.  Five layers of this place each prove a "you can't" (or, in the
//  fifth, a "there must be"). This portal's claim, which none of the five states
//  alone, is that the PROOF is the same proof every time:
//
//      find a quantity the allowed moves cannot change, then show the goal
//      would require changing it.
//
//  An invariant. This file recomputes each layer's invariant from scratch and
//  shows, for each, that (a) the invariant is unmoved by the layer's own moves,
//  and (b) the impossibility (or necessity) follows. It then CROSS-CHECKS that
//  every parent verifier still commits the fact this portal lifts from it, by
//  reading the parent's source — so the portal can never silently drift from the
//  strata it gathers.
//
//  Run:  node research/find-what-doesnt-change/verify.mjs
//  Honest scope: this is a FRAME, not a finding. Every result below is a known
//  theorem (Gauss 1827; Euler 1736; Johnson–Story 1879; the Fox/Reidemeister
//  invariants; Borsuk 1933). The new thing is the join, and the join is checked.
// ============================================================================

import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, "..", "..");
let PASS = 0, FAIL = 0;
const out = [];
function check(label, cond, got, want) {
  if (cond) { PASS++; out.push(`  ok   ${label}`); }
  else { FAIL++; out.push(`  FAIL ${label}` + (got !== undefined ? `  (got ${got}, want ${want})` : "")); }
}
const near = (a, b, eps = 1e-12) => Math.abs(a - b) <= eps;
function parentSrc(rel) { return readFileSync(join(ROOT, "research", rel), "utf8"); }

// ============================================================================
//  MASK I — EGREGIUM.  Invariant: the Gaussian curvature K.
//  Allowed moves: isometries (any distance-preserving bend). They cannot change
//  K (Theorema Egregium). The plane and the cylinder have K = 0; the sphere has
//  K = 1/R² ≠ 0; so no isometry carries the sphere to the plane — no flat map of
//  the Earth is faithful. The ant reads K from inside: angle-excess / area.
// ============================================================================
out.push("MASK I — Egregium: curvature is intrinsic; excess/area = 1/R², invariant of the triangle");
{
  const PI = Math.PI;
  // Spherical area of a triangle with interior angles a,b,c on a sphere of radius
  // R is Girard's theorem: Area = R²·(a+b+c−π). So the ant's reading,
  // excess/Area = (a+b+c−π)/(R²(a+b+c−π)) = 1/R², for EVERY triangle — that is the
  // invariance made arithmetic: the answer does not depend on which triangle.
  for (const R of [1, 2, 6371]) {
    for (const [a, b, c] of [[PI / 2, PI / 2, PI / 2], [2.0, 1.4, 1.1], [1.2, 1.2, 1.2]]) {
      const excess = a + b + c - PI;
      const area = R * R * excess;
      const K = excess / area;
      check(`R=${R}, angles(${a},${b},${c}): excess/area = 1/R² = ${(1 / (R * R)).toExponential(3)}`,
        near(K, 1 / (R * R)), K, 1 / (R * R));
    }
  }
  // The plane: every triangle sums to exactly π, excess 0, K = 0.
  check("plane: any triangle angle-sum = π exactly ⇒ K = 0", near((PI / 3 + PI / 3 + PI / 3) - PI, 0), 0, 0);
  // The cylinder is flat too (one principal curvature is 0 ⇒ Gaussian K = k1·k2 = 0):
  // a flat map of a CYLINDER is faithful; of a SPHERE it cannot be. The wall is K≠0.
  const Kcyl = (1 / 3) * 0, Ksphere = (1 / 6371) * (1 / 6371);
  check("cylinder K = 0 (flattenable) ≠ sphere K = 1/R² > 0 (not flattenable)",
    Kcyl === 0 && Ksphere > 0, `${Kcyl},${Ksphere}`, "0, >0");
  // Gauss–Bonnet ties the SAME K to a topological invariant, the Euler
  // characteristic: ∮K dA = 2πχ, χ(sphere) = 2. (Euler's number, in Egregium —
  // the same Euler whose parity decides the bridges. A resonance, named, not
  // overclaimed: these are two distinct theorems that share a man's name.)
  const R = 6371, intK = (1 / (R * R)) * (4 * PI * R * R); // ∮K dA over whole sphere = 4π
  check("Gauss–Bonnet: ∮K dA = 4π = 2π·χ, χ(sphere) = 2", near(intK, 2 * PI * 2), intK, 2 * PI * 2);
}

// ============================================================================
//  MASK II — THE BRIDGES.  Invariant: the parity of the vertex degrees.
//  Allowed moves: extend the walk one bridge at a time. Passing THROUGH a vertex
//  uses bridges in pairs, so only the start and end may sit at an odd vertex —
//  the count of odd-degree vertices is fixed at ≥4 for Königsberg and forbids the
//  walk. The handshake lemma makes that count always even.
// ============================================================================
out.push("\nMASK II — The Bridges: odd-degree count is invariant; Euler walk iff it is 0 or 2");
{
  // Königsberg multigraph: 4 landmasses, 7 bridges, degree sequence (5,3,3,3).
  // vertices {0:Kneiphof island, 1:Altstadt bank, 2:Vorstadt bank, 3:Lomse island}
  //   Kneiphof–Altstadt ×2, Kneiphof–Vorstadt ×2, Kneiphof–Lomse ×1,
  //   Altstadt–Lomse ×1, Vorstadt–Lomse ×1.  Degrees: 0→5, 1→3, 2→3, 3→3.
  const KOENIG = [[0, 1], [0, 1], [0, 2], [0, 2], [0, 3], [1, 3], [2, 3]];
  const degrees = (edges, nV = 4) => {
    const d = new Array(nV).fill(0);
    for (const [u, v] of edges) { d[u]++; d[v]++; }
    return d;
  };
  const oddCount = (edges) => degrees(edges).filter(x => x % 2 === 1).length;
  const eulerWalk = (edges) => { const o = oddCount(edges); return o === 0 || o === 2; };

  check("Königsberg degree sequence = (5,3,3,3)", degrees(KOENIG).sort((a, b) => b - a).join(",") === "5,3,3,3");
  check("Σdegrees = 14 = 2·(7 edges) — handshake lemma (always even)", degrees(KOENIG).reduce((a, b) => a + b) === 14);
  check("Königsberg odd-vertex count = 4 (> 2) ⇒ NO Euler walk", oddCount(KOENIG) === 4 && !eulerWalk(KOENIG), oddCount(KOENIG), 4);
  // The move that flips feasibility: drop ONE bridge joining two odd vertices.
  // Removing edge [1,3] makes degrees (5,2,3,2) → odd count = 2 → a walk appears.
  const cut = KOENIG.filter(([u, v]) => !(u === 1 && v === 3));
  check("remove one bridge (1–3): odd count drops 4→2 ⇒ Euler walk becomes POSSIBLE", oddCount(cut) === 2 && eulerWalk(cut), oddCount(cut), 2);
  // The invariant's parity is exhaustive over how you walk: brute force shows no
  // ordering of the 7 bridges from any of the 4 starts is a valid trail.
  let valid = 0;
  const perms = (arr) => arr.length <= 1 ? [arr] : arr.flatMap((x, i) => perms(arr.slice(0, i).concat(arr.slice(i + 1))).map(p => [x, ...p]));
  for (const order of perms([0, 1, 2, 3, 4, 5, 6])) {
    for (const start of [0, 1, 2, 3]) {
      let at = start, ok = true;
      for (const e of order) { const [u, v] = KOENIG[e]; if (u === at) at = v; else if (v === at) at = u; else { ok = false; break; } }
      if (ok) valid++;
    }
  }
  check(`brute force: 0 valid trails over all 4·7! = 20160 ordered attempts (got ${valid})`, valid === 0, valid, 0);
}

// ============================================================================
//  MASK III — THE FIFTEEN PUZZLE.  Invariant: the parity bit J.
//  Allowed moves: slide a tile into the gap (a transposition of the gap with a
//  neighbour). Each slide flips sign(perm) and flips (−1)^(gap taxicab) together,
//  so J = sign·(−1)^(gap taxicab) is unchanged by every slide. The solved board
//  has J = +1; exactly the J = +1 boards are reachable — exactly half. Loyd's
//  14–15 swap has J = −1: unreachable, the prize uncollectable.
// ============================================================================
out.push("\nMASK III — The Fifteen Puzzle: J = sign·(−1)^(gap taxicab) is invariant under every slide");
{
  // ---- 3×3 (8-puzzle): full BFS proves the reachable set is exactly 9!/2 ----
  const W = 3, N = 9, GOAL = [1, 2, 3, 4, 5, 6, 7, 8, 0]; // 0 = gap, home = last cell
  const enc = (b) => { let h = 0; for (const x of b) h = h * 9 + x; return h; };
  const neigh = (b) => {
    const z = b.indexOf(0), r = (z / W) | 0, c = z % W, res = [];
    for (const [dr, dc] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
      const nr = r + dr, nc = c + dc;
      if (nr < 0 || nr >= W || nc < 0 || nc >= W) continue;
      const nb = b.slice(), nz = nr * W + nc;
      nb[z] = nb[nz]; nb[nz] = 0; res.push(nb);
    }
    return res;
  };
  const seen = new Set([enc(GOAL)]);
  let frontier = [GOAL];
  while (frontier.length) {
    const nxt = [];
    for (const b of frontier) for (const nb of neigh(b)) { const h = enc(nb); if (!seen.has(h)) { seen.add(h); nxt.push(nb); } }
    frontier = nxt;
  }
  check("8-puzzle BFS: reachable states = 181440 = 9!/2 (exactly half of 362880)", seen.size === 181440, seen.size, 181440);
  check("the other exact half (181440) is forever unreachable", 362880 - seen.size === 181440);

  // ---- the invariant J, defined from scratch, agrees with reachability ----
  // J = +1 means (inversions among tiles, row-major) + (blank's taxicab distance
  // from its home cell) is EVEN. Each slide changes inversions and the blank's
  // taxicab parity together, so this bit is unchanged by every slide — and a board
  // is reachable from solved iff J = +1. (sign(perm)·(−1)^taxicab, written as a parity.)
  // inversions over ALL cells incl. the blank (value 0) = parity of the full
  // permutation; counting the blank is what couples sign to the blank's taxicab so
  // the sum is invariant under both horizontal and vertical slides.
  const inversions = (b) => { let inv = 0; for (let i = 0; i < b.length; i++) for (let j = i + 1; j < b.length; j++) if (b[i] > b[j]) inv++; return inv; };
  const blankTaxi = (b, w) => { const z = b.indexOf(0), r = (z / w) | 0, c = z % w; return Math.abs(r - (w - 1)) + Math.abs(c - (w - 1)); }; // home = last cell
  // J = +1 ⇔ the board sits in the SOLVED board's parity class for its width.
  const Jplus = (b, w) => (inversions(b) + blankTaxi(b, w)) % 2 === (w * w - 1) % 2;
  check("solved 8-puzzle has J = +1", Jplus(GOAL, 3) === true);
  // J = +1 on EVERY reachable board, and J = −1 on every unreachable board:
  let jOK = true;
  for (const h of seen) { // decode
    const b = new Array(9); let x = h; for (let i = 8; i >= 0; i--) { b[i] = x % 9; x = (x / 9) | 0; }
    if (!Jplus(b, 3)) { jOK = false; break; }
  }
  check("J = +1 holds on all 181440 reachable boards (necessary AND sufficient)", jOK);

  // ---- Loyd's 4×4 swap: J = −1 ----
  const solved16 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0];
  const loyd = solved16.slice(); // swap tiles 14 and 15 (at indices 13 and 14)
  [loyd[13], loyd[14]] = [loyd[14], loyd[13]];
  check("solved 15-puzzle J = +1; Loyd's 14–15 swap J = −1 (unsolvable — the prize)", Jplus(solved16, 4) === true && Jplus(loyd, 4) === false, `${Jplus(solved16, 4)},${Jplus(loyd, 4)}`, "true,false");
  // smallest real rearrangement with gap home is a 3-cycle (even): you can never swap just two.
  const swap2 = solved16.slice(); [swap2[0], swap2[1]] = [swap2[1], swap2[0]]; // swap tiles 1,2 (gap stays home)
  check("with gap home, swapping just two tiles gives J = −1 (impossible) — smallest move is a 3-cycle", Jplus(swap2, 4) === false, Jplus(swap2, 4), false);
}

// ============================================================================
//  MASK IV — THREE CRAYONS.  Invariant: the number of Fox 3-colourings.
//  Allowed moves: Reidemeister moves (any wiggle of the diagram). They cannot
//  change the colouring count. Unknot scores 3; the trefoil scores 9. 9 ≠ 3 is a
//  complete proof the trefoil is genuinely knotted. (Fox/Reidemeister engine
//  ported faithfully from research/knots/verify.mjs — see cross-check below.)
// ============================================================================
out.push("\nMASK IV — Three Crayons: the Fox 3-colouring count is a knot invariant; 9 ≠ 3 ⇒ knotted");
{
  const UNKNOT = [];
  const TREFOIL = [[1, 4, 2, 5], [3, 6, 4, 1], [5, 2, 6, 3]];   // 3_1
  const FIG8 = [[4, 2, 5, 1], [8, 6, 1, 5], [6, 3, 7, 4], [2, 7, 3, 8]]; // 4_1
  function arcsOf(pd) {
    const maxE = Math.max(0, ...pd.flat());
    const parent = Array.from({ length: maxE + 1 }, (_, i) => i);
    const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; };
    const uni = (x, y) => { parent[find(x)] = find(y); };
    for (const [a, b, c, d] of pd) uni(b, d);
    const arcId = new Map(); let next = 0;
    const arcOf = (e) => { const r = find(e); if (!arcId.has(r)) arcId.set(r, next++); return arcId.get(r); };
    return { arcOf, count: () => next, maxE };
  }
  function countFox(pd, n) {
    if (pd.length === 0) return n;
    const A = arcsOf(pd);
    for (let e = 1; e <= A.maxE; e++) A.arcOf(e);
    const nArc = A.count();
    const cons = pd.map(([a, b, c, d]) => ({ over: A.arcOf(b), u1: A.arcOf(a), u2: A.arcOf(c) }));
    let total = 0; const col = new Array(nArc).fill(0);
    const rec = (i) => {
      if (i === nArc) { for (const k of cons) if (((2 * col[k.over] - col[k.u1] - col[k.u2]) % n + n * 3) % n !== 0) return; total++; return; }
      for (let v = 0; v < n; v++) { col[i] = v; rec(i + 1); }
    };
    rec(0); return total;
  }
  check("unknot: Fox 3-colourings = 3 (the three constant fillings only)", countFox(UNKNOT, 3) === 3, countFox(UNKNOT, 3), 3);
  check("trefoil: Fox 3-colourings = 9 ⇒ 9 ≠ 3 ⇒ TREFOIL IS KNOTTED", countFox(TREFOIL, 3) === 9, countFox(TREFOIL, 3), 9);
  // The honest edge built into the spine: tricolouring has a blind spot. The
  // figure-eight scores 3 (looks 'unknotted' to three crayons) yet is knotted —
  // five crayons convict it (Fox 5-colourings = 25). No single invariant is whole.
  check("figure-eight: Fox 3-colourings = 3 (tricolouring's blind spot — it can't see this knot)", countFox(FIG8, 3) === 3, countFox(FIG8, 3), 3);
  check("figure-eight: Fox 5-colourings = 25 (five crayons convict what three acquit)", countFox(FIG8, 5) === 25, countFox(FIG8, 5), 25);
}

// ============================================================================
//  THE MIRROR — BORSUK–ULAM.  The SAME move, run the other way: an invariant
//  parity that FORBIDS escape and therefore GUARANTEES a coincidence exists.
//  1-D: g(θ) = f(θ) − f(θ+π) is odd, g(θ+π) = −g(θ), so by the Intermediate
//  Value Theorem it has a zero — an antipodal pair that agrees. Tucker's lemma is
//  the discrete heart: an antipodal ±labelling of an even ring must contain a +/−
//  edge — there is no escape, exhaustively. Forbidding the escape IS guaranteeing
//  the match. The wall and the guarantee are one theorem read two ways.
// ============================================================================
out.push("\nTHE MIRROR — Borsuk–Ulam: the same invariance, used to GUARANTEE rather than forbid");
{
  // 1-D: a random smooth periodic f; g odd ⇒ sign change ⇒ a zero exists.
  const mulberry32 = (a) => () => { a |= 0; a = a + 0x6D2B79F5 | 0; let t = Math.imul(a ^ a >>> 15, 1 | a); t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t; return ((t ^ t >>> 14) >>> 0) / 4294967296; };
  let everyHasZero = true, maxOddErr = 0;
  for (let trial = 0; trial < 200; trial++) {
    const rnd = mulberry32(1000 + trial);
    const ks = [1, 2, 3], amp = ks.map(() => rnd() * 2 - 1), ph = ks.map(() => rnd() * 2 * Math.PI);
    const f = (t) => ks.reduce((s, k, i) => s + amp[i] * Math.sin(k * t + ph[i]), 0);
    const g = (t) => f(t) - f(t + Math.PI);
    // g is odd under the half-turn: g(t+π) = −g(t)
    for (let t = 0; t < Math.PI; t += 0.31) maxOddErr = Math.max(maxOddErr, Math.abs(g(t + Math.PI) + g(t)));
    // a sign change over [0,π] ⇒ a zero (IVT)
    let neg = false, pos = false;
    for (let t = 0; t <= Math.PI + 1e-9; t += Math.PI / 64) { const v = g(t); if (v < 0) neg = true; if (v > 0) pos = true; }
    if (!(neg && pos)) {
      // g could be identically ~0; treat a flat zero as a (degenerate) match
      let allSmall = true; for (let t = 0; t <= Math.PI; t += Math.PI / 64) if (Math.abs(g(t)) > 1e-9) allSmall = false;
      if (!allSmall) everyHasZero = false;
    }
  }
  check("1-D: g(θ)=f(θ)−f(θ+π) is odd to machine precision (g(θ+π) = −g(θ))", maxOddErr < 1e-9, maxOddErr.toExponential(2), "<1e-9");
  check("1-D: over 200 random profiles, g changes sign ⇒ an antipodal MATCH always exists (IVT)", everyHasZero);

  // Tucker's lemma, EXHAUSTIVE: even ring, antipodal ±1 labelling forced; over all
  // such labellings there is always a complementary (+,−) adjacent edge. No escape.
  const tuckerNoEscape = (m) => { // m even
    const half = m / 2, total = 1 << half;
    for (let mask = 0; mask < total; mask++) {
      const lab = new Array(m);
      for (let i = 0; i < half; i++) { const s = (mask >> i) & 1 ? 1 : -1; lab[i] = s; lab[i + half] = -s; }
      let hasEdge = false;
      for (let i = 0; i < m; i++) if (lab[i] * lab[(i + 1) % m] < 0) { hasEdge = true; break; }
      if (!hasEdge) return false; // an escape would break the guarantee
    }
    return true;
  };
  for (const m of [4, 6, 8, 10, 12]) check(`Tucker (exhaustive, ring size ${m}): every antipodal ±labelling has a +/− edge — no escape`, tuckerNoEscape(m));
}

// ============================================================================
//  CROSS-CHECKS — the portal can never drift from the strata it gathers.
//  Read each parent verifier's committed source and confirm it still asserts the
//  exact fact this portal lifts. (Same discipline as The Shape of Five.)
// ============================================================================
out.push("\nCROSS-CHECKS — each parent verifier still commits the fact this portal lifts");
{
  const egregium = parentSrc("egregium/verify.mjs");
  check("egregium/verify.mjs still asserts K = 1/R² (the curvature invariant)", /1\s*\/\s*\(R\s*\*\s*R\)/.test(egregium));
  check("egregium/verify.mjs still asserts Gauss–Bonnet ∮K dA = 2π·χ, χ(sphere)=2", /chi\(sphere\)\s*=\s*2|2\s*\*\s*pi\s*\*\s*chi/i.test(egregium));

  const bridges = parentSrc("what-the-bridges-knew/verify.mjs");
  check("what-the-bridges-knew/verify.mjs still uses the odd-degree predicate (0 or 2)", /odd\.length\s*!==\s*0\s*&&\s*odd\.length\s*!==\s*2/.test(bridges));

  const fifteen = parentSrc("fifteen-puzzle/verify.mjs");
  check("fifteen-puzzle/verify.mjs still asserts reachable = 181440 (= 9!/2)", /181440/.test(fifteen));
  check("fifteen-puzzle/verify.mjs still defines J = sign·(−1)^(gap taxicab)", /J\s*=\s*sign/.test(fifteen) || /taxicab/.test(fifteen));

  const knots = parentSrc("knots/verify.mjs");
  check("knots/verify.mjs still carries the Fox-colouring counter (countFoxColorings)", /countFoxColorings/.test(knots));
  check("knots/verify.mjs still encodes the trefoil PD [[1,4,2,5],[3,6,4,1],[5,2,6,3]]", /\[1,\s*4,\s*2,\s*5\]/.test(knots) && /TREFOIL/.test(knots));

  const borsuk = parentSrc("borsuk-ulam/verify.mjs");
  check("borsuk-ulam/verify.mjs still proves Tucker's no-escape (complementary edge)", /Tucker/.test(borsuk) && /complementary/i.test(borsuk));
}

// ============================================================================
//  THE JOIN, STATED ONCE — the load-bearing claim none of the five makes alone.
// ============================================================================
out.push("\nTHE JOIN — what kind of 'the same' this portal claims (read carefully, never lie)");
{
  // The five invariants are NOT the same number. Honesty requires naming exactly
  // what they share: the MOVE, not the value. Curvature is real-valued; the bridge
  // and puzzle invariants are parities (mod 2); the colouring count is an integer
  // (mod-3 system); Borsuk–Ulam's is a parity/degree forcing existence. What is
  // identical is the shape of the argument: a quantity preserved by the allowed
  // moves witnesses the (im)possibility.
  const kinds = {
    egregium: "real-valued (continuous geometric invariant; isometry-preserved)",
    bridges: "parity, mod 2 (odd-degree count)",
    fifteen: "parity, mod 2 (sign · gap taxicab)",
    crayons: "integer count (solutions of a mod-3 linear system)",
    borsuk: "parity / degree, mod 2 (odd map forces a zero)",
  };
  check("the spine claims a shared MOVE, not a shared number — and names each invariant's kind", Object.keys(kinds).length === 5);
  // Three of the five are literally mod-2 parity arguments — the cheapest, most
  // reused invariant in mathematics. That is a real observation, stated plainly.
  const parityCount = Object.values(kinds).filter(k => /parity/.test(k)).length;
  check("three of the five turn on a mod-2 parity (bridges, fifteen, Borsuk–Ulam)", parityCount === 3, parityCount, 3);
}

// ---- report ----
console.log(out.join("\n"));
console.log("\n" + "=".repeat(64));
if (FAIL === 0) console.log(`ALL ${PASS} CHECKS PASS`);
else console.log(`${PASS} passed, ${FAIL} FAILED`);
process.exit(FAIL === 0 ? 0 : 1);
