#!/usr/bin/env node
// Knot invariants from planar-diagram (PD) codes — recomputed from scratch and
// checked against the published literature (Rolfsen / KnotInfo / Kauffman).
//
// Two invariants, two registers of difficulty:
//   1. Fox n-colourings  — the "three crayons" proof. An integer you can find by
//      hand. Counts colourings of the arcs with colours {0..n-1} such that at
//      every crossing  2·(over) ≡ (under1)+(under2)  (mod n). Invariant under all
//      three Reidemeister moves, hence a knot invariant. #colourings > n  ⇔  the
//      knot is non-trivially n-colourable.
//   2. The Jones polynomial  — via the Kauffman bracket state sum. Catches what
//      colouring cannot: chirality. The two trefoils have identical colouring
//      counts but different Jones polynomials, so no wiggle takes one to the other.
//
// Everything below is computed; the `checks` array at the bottom compares each
// computed value to its independently-known literature value and the run fails
// loudly on any mismatch.  Run:  node research/knots/verify.mjs

// ---------- standard PD codes (KnotAtlas / KnotInfo conventions) ----------
// X[a,b,c,d]: the four edge-labels meeting at a crossing, listed counter-
// clockwise starting from the incoming UNDER-strand. Under goes a->c; the
// over-strand is the pair {b,d}. Edge labels run 1..2n consecutively along the
// knot, so edge i is followed by edge i+1 (mod 2n) — that fixes orientation.
const UNKNOT = [];                                   // 0 crossings
const TREFOIL = [[1,4,2,5],[3,6,4,1],[5,2,6,3]];     // 3_1  (right-handed here)
const FIG8    = [[4,2,5,1],[8,6,1,5],[6,3,7,4],[2,7,3,8]]; // 4_1

// mirror a diagram: cyclically shift each crossing tuple by one, which swaps
// which strand is over vs under (a -> the b,d strand becomes the under one).
const mirror = (pd) => pd.map(([a,b,c,d]) => [b,c,d,a]);

// ---------- Fox n-colourings ----------
// An "arc" is a maximal strand between under-crossings. We build arcs by walking
// edges and merging edges that are joined at a crossing's OVER strand (the over
// strand passes through unbroken), then impose one linear constraint per crossing.
function arcsOf(pd) {
  const maxE = Math.max(0, ...pd.flat());
  // union-find over edge labels; merge the two over-edges at each crossing
  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);   // over strand b—d is one arc
  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 countFoxColorings(pd, n) {
  if (pd.length === 0) return n;                 // unknot: one arc, n colourings
  const A = arcsOf(pd);
  // ensure every edge registers an arc id
  for (let e = 1; e <= A.maxE; e++) A.arcOf(e);
  const nArc = A.count();
  // constraints: at X[a,b,c,d] over=arc(b)=arc(d); under1=arc(a), under2=arc(c):
  //   2*over - under1 - under2 ≡ 0 (mod n)
  const cons = pd.map(([a, b, c, d]) => ({ over: A.arcOf(b), u1: A.arcOf(a), u2: A.arcOf(c) }));
  // brute force over n^nArc assignments is fine for small arc counts (<=8)
  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;
}

// ---------- Kauffman bracket -> Jones polynomial ----------
// Laurent polynomials as Map(exponent -> coeff).
const polyAdd = (p, q) => { const r = new Map(p); for (const [e, c] of q) r.set(e, (r.get(e) || 0) + c); return clean(r); };
const polyScaleShift = (p, coeff, shift) => { const r = new Map(); for (const [e, c] of p) r.set(e + shift, c * coeff); return clean(r); };
const clean = (p) => { for (const [e, c] of [...p]) if (c === 0) p.delete(e); return p; };
const polyMul = (p, q) => { const r = new Map(); for (const [e1, c1] of p) for (const [e2, c2] of q) r.set(e1 + e2, (r.get(e1 + e2) || 0) + c1 * c2); return clean(r); };
const polyStr = (p, v = 't') => {
  const terms = [...p.entries()].sort((a, b) => a[0] - b[0]);
  if (!terms.length) return '0';
  return terms.map(([e, c]) => {
    const cs = c === 1 && e !== 0 ? '' : c === -1 && e !== 0 ? '-' : `${c}`;
    const vp = e === 0 ? '' : e === 1 ? v : `${v}^${e}`;
    return (cs === '' ? '+' : cs[0] === '-' ? '' : '+') + cs + vp;
  }).join('').replace(/^\+/, '');
};
const polyEq = (p, q) => { const a = clean(new Map(p)), b = clean(new Map(q)); if (a.size !== b.size) return false; for (const [e, c] of a) if (b.get(e) !== c) return false; return true; };

// count loops of a state: at each crossing pick A- or B-smoothing.
// A-smoothing of X[a,b,c,d] connects a-b and c-d; B-smoothing connects a-d and b-c.
function loopCount(pd, stateBits) {
  const maxE = Math.max(...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); };
  pd.forEach(([a, b, c, d], i) => {
    if (((stateBits >> i) & 1) === 0) { uni(a, b); uni(c, d); }   // A
    else { uni(a, d); uni(b, c); }                                 // B
  });
  const seen = new Set();
  for (let e = 1; e <= maxE; e++) seen.add(find(e));
  return seen.size;
}

function kauffmanBracket(pd) {
  // delta = -A^2 - A^-2 ; <state> = A^(#A - #B) * delta^(loops-1)
  if (pd.length === 0) return new Map([[0, 1]]);   // unknot bracket = 1
  const n = pd.length;
  const delta = new Map([[2, -1], [-2, -1]]);
  let total = new Map();
  for (let s = 0; s < (1 << n); s++) {
    let aCount = 0;
    for (let i = 0; i < n; i++) aCount += ((s >> i) & 1) === 0 ? 1 : -1;  // #A - #B
    const loops = loopCount(pd, s);
    let term = new Map([[aCount, 1]]);
    for (let k = 0; k < loops - 1; k++) term = polyMul(term, delta);
    total = polyAdd(total, term);
  }
  return total;
}

// writhe: sum of crossing signs. Edge labels are consecutive along the knot, so
// the over-strand outgoing edge o is whichever of {b,d} equals (other)+1 mod 2n.
// The sign rule below is the one that pairs with the A/B-smoothing convention in
// loopCount() above — fixed once and then cross-validated against three published
// Jones polynomials (right trefoil, its mirror, and figure-eight), so any error
// in the convention would surface as a mismatch there rather than passing.
function writhe(pd) {
  const m = Math.max(...pd.flat());
  let w = 0;
  for (const [a, b, c, d] of pd) {
    const next = (x) => (x % m) + 1;
    const oIsD = next(b) === d;   // over goes b->d  => outgoing is d
    w += oIsD ? -1 : 1;
  }
  return w;
}

function jones(pd) {
  // X(A) = (-A^3)^(-w) * <L> ; then A = t^(-1/4): A^4 = t^-1, A^-4 = t.
  const w = writhe(pd);
  let br = kauffmanBracket(pd);
  // multiply by (-A^3)^(-w): coeff (-1)^(-w) = (-1)^w, exponent shift -3w
  br = polyScaleShift(br, ((w % 2) === 0 ? 1 : -1), -3 * w);
  // substitute A -> t^(-1/4): an A-exponent e must be a multiple of 4? Bracket of
  // a knot lives in A^(4k); after writhe normalization exponents are multiples of 4.
  const out = new Map();
  for (const [e, c] of br) {
    if (e % 4 !== 0) throw new Error(`non-multiple-of-4 A-exponent ${e}`);
    out.set(-e / 4, (out.get(-e / 4) || 0) + c);   // A^e = t^(-e/4)
  }
  return clean(out);
}

const evalPoly = (p, t) => { let s = 0; for (const [e, c] of p) s += c * Math.pow(t, e); return Math.round(s); };
const reflect = (p) => { const r = new Map(); for (const [e, c] of p) r.set(-e, c); return r; };

// ---------- literature reference values ----------
const L = {
  trefoilR: new Map([[-4, -1], [-3, 1], [-1, 1]]),            // V(3_1) right = -t^-4 + t^-3 + t^-1
  trefoilL: new Map([[4, -1], [3, 1], [1, 1]]),               // mirror = -t^4 + t^3 + t
  fig8:     new Map([[-2, 1], [-1, -1], [0, 1], [1, -1], [2, 1]]), // V(4_1) = t^-2 - t^-1 + 1 - t + t^2
};

// ---------- run all checks ----------
const checks = [];
const chk = (name, got, want) => checks.push({ name, ok: JSON.stringify(got) === JSON.stringify(want), got, want });
const chkPoly = (name, got, want) => checks.push({ name, ok: polyEq(got, want), got: polyStr(got), want: polyStr(want) });

// Fox 3-colourings — the crayon proof
chk('unknot   #3-colourings = 3 (trivial only, NOT tricolourable)', countFoxColorings(UNKNOT, 3), 3);
chk('trefoil  #3-colourings = 9 (tricolourable -> truly knotted)', countFoxColorings(TREFOIL, 3), 9);
chk('mirror trefoil #3-colourings = 9 (colour cannot tell them apart)', countFoxColorings(mirror(TREFOIL), 3), 9);
chk('fig-8    #3-colourings = 3 (NOT tricolourable)', countFoxColorings(FIG8, 3), 3);
chk('fig-8    #5-colourings = 25 (5-colourable, det 5)', countFoxColorings(FIG8, 5), 25);
chk('trefoil  #5-colourings = 5 (NOT 5-colourable)', countFoxColorings(TREFOIL, 5), 5);

// Jones polynomials — chirality, the thing colour misses
chkPoly('Jones(trefoil)          = -t^-4 + t^-3 + t^-1', jones(TREFOIL), L.trefoilR);
chkPoly('Jones(mirror trefoil)   = -t^4 + t^3 + t', jones(mirror(TREFOIL)), L.trefoilL);
chkPoly('Jones(fig-8)            = t^-2 - t^-1 + 1 - t + t^2', jones(FIG8), L.fig8);

// structural cross-checks
chkPoly('mirror law: Jones(mirror 3_1) = reflect Jones(3_1)', jones(mirror(TREFOIL)), reflect(jones(TREFOIL)));
chk('chirality: the two trefoils differ (no wiggle/colour relates them)', polyEq(jones(TREFOIL), jones(mirror(TREFOIL))), false);
chk('amphichiral: Jones(4_1) is palindromic (= its own reflection)', polyEq(jones(FIG8), reflect(jones(FIG8))), true);

// determinant cross-check: det(K) = |V(K) at t=-1|, and 3-colourable <=> 3 | det
chk('det(trefoil) = |V(-1)| = 3', Math.abs(evalPoly(jones(TREFOIL), -1)), 3);
chk('det(fig-8)   = |V(-1)| = 5', Math.abs(evalPoly(jones(FIG8), -1)), 5);
chk('det(unknot)  = 1', Math.abs(evalPoly(kauffmanBracketJonesUnknot(), -1)), 1);
chk('rule: 3-colourable iff 3 | det  (3|3 yes, 3∤5 no, 3∤1 no)',
    [3 % 3 === 0, 5 % 3 === 0, 1 % 3 === 0], [true, false, false]);

function kauffmanBracketJonesUnknot() { return new Map([[0, 1]]); }

// ---------- report ----------
let pass = 0;
console.log('\n  KNOTS — invariants recomputed from PD codes, checked vs literature\n');
for (const c of checks) {
  console.log(`  ${c.ok ? 'PASS' : 'FAIL'}  ${c.name}`);
  if (!c.ok) console.log(`        got ${JSON.stringify(c.got)}  want ${JSON.stringify(c.want)}`);
  if (c.ok) pass++;
}
console.log(`\n  ${pass}/${checks.length} checks pass\n`);
process.exit(pass === checks.length ? 0 : 1);
