// engine.mjs: two facts, exact arithmetic, and a proof you can check by hand.
//
// A unit-distance drawing puts the vertices of a graph at distinct points of the plane with every edge of length 1.
// Write z_i for the point of vertex i as a complex number. Two facts hold in every such drawing:
//
//   RHOMBUS.  Every 4-cycle u-v-w-x is a rhombus: z_u + z_w = z_v + z_x. (Four unit vectors adding to zero pair off
//             into opposite pairs; the two other pairings would put u on w or v on x.)
//   TRIANGLE. Every triangle a<b<c is equilateral: z_c - z_a = w^s (z_b - z_a) with w = e^(i pi/3) and s = +1 or -1.
//
// Everything below is exact linear algebra over Q(w) = {p + q w : p, q rational}, with w^2 = w - 1 and conj(w) = 1 - w.
// A derived identity z_a - z_b = zeta (z_u - z_v), with uv an edge, says |z_a - z_b| = |zeta|. So:
//   - if a = b is forced, two vertices share a point: impossible;
//   - if ab is an edge and |zeta| != 1, an edge is forced to the wrong length: impossible;
//   - if ab is not an edge and |zeta| = 1, a and b are one unit apart in EVERY drawing: add ab as an edge and go on.
// Triangle orientations are split into cases; the first case is fixed by reflecting the whole drawing.
//
// search() finds proofs. check() verifies a proof object without searching, and shares only the arithmetic.

// ---------- Q(w), exact ----------
const gcd = (a, b) => { if (a < 0n) a = -a; if (b < 0n) b = -b; while (b) { const t = a % b; a = b; b = t; } return a; };
export const Z = Object.freeze([0n, 0n, 1n]);
export const ONE = Object.freeze([1n, 0n, 1n]);
export const W = Object.freeze([0n, 1n, 1n]);   // w = e^(i pi/3)
export const WB = Object.freeze([1n, -1n, 1n]); // conj(w) = 1 - w = e^(-i pi/3)
export function mk(A, B, D) {
  if (D < 0n) { A = -A; B = -B; D = -D; }
  if (A === 0n && B === 0n) return Z;
  const g = gcd(gcd(A, B), D);
  if (g > 1n) { A /= g; B /= g; D /= g; }
  return [A, B, D];
}
export const isZ = (x) => x[0] === 0n && x[1] === 0n;
export const add = (x, y) => (isZ(x) ? y : isZ(y) ? x : mk(x[0] * y[2] + y[0] * x[2], x[1] * y[2] + y[1] * x[2], x[2] * y[2]));
export const neg = (x) => (isZ(x) ? Z : [-x[0], -x[1], x[2]]);
export const sub = (x, y) => add(x, neg(y));
export const mul = (x, y) => (isZ(x) || isZ(y) ? Z : mk(x[0] * y[0] - x[1] * y[1], x[0] * y[1] + x[1] * y[0] + x[1] * y[1], x[2] * y[2]));
export const inv = (x) => { if (isZ(x)) throw new Error('division by zero in Q(w)'); return mk((x[0] + x[1]) * x[2], -x[1] * x[2], x[0] * x[0] + x[0] * x[1] + x[1] * x[1]); };
export const eqq = (x, y) => x[0] === y[0] && x[1] === y[1] && x[2] === y[2];
// |x|^2 = (A^2 + AB + B^2) / D^2
export const norm2 = (x) => [x[0] * x[0] + x[0] * x[1] + x[1] * x[1], x[2] * x[2]];
export const isUnit = (x) => { const [p, q] = norm2(x); return p === q; };
export const toStr = (x) => `${x[0]},${x[1]},${x[2]}`;
export const fromStr = (s) => { const [A, B, D] = s.split(',').map((t) => BigInt(t)); return mk(A, B, D); };
const wPow = (s) => (s > 0 ? W : WB);

// ---------- generators ----------
// ['R', u, v, w, x]: the 4-cycle u-v-w-x is a rhombus: z_u - z_v + z_w - z_x = 0
// ['T', a, b, c, s]: the triangle a<b<c turns by w^s: z_c - z_a - w^s (z_b - z_a) = 0
export function genVec(n, g) {
  const v = new Array(n).fill(Z);
  if (g[0] === 'R') {
    const [, u, p, w, x] = g;
    v[u] = add(v[u], ONE); v[p] = sub(v[p], ONE); v[w] = add(v[w], ONE); v[x] = sub(v[x], ONE);
  } else {
    const [, a, b, c, s] = g, ws = wPow(s);
    v[c] = add(v[c], ONE); v[a] = add(v[a], sub(ws, ONE)); v[b] = sub(v[b], ws);
  }
  return v;
}
const gkey = (g) => g.join(':');
const diffVec = (n, a, b) => { const v = new Array(n).fill(Z); v[a] = ONE; v[b] = neg(ONE); return v; };

// ---------- a row space with provenance ----------
class Span {
  constructor(n, track = true) { this.n = n; this.track = track; this.rows = []; this.piv = []; this.prov = []; }
  clone() { const s = new Span(this.n, this.track); s.rows = this.rows.map((r) => r.slice()); s.piv = this.piv.slice(); s.prov = this.prov.map((p) => new Map(p)); return s; }
  // returns [normal form, combination] with v = nf + sum(comb[k] * generator k)
  reduce(v) {
    v = v.slice(); const comb = new Map();
    for (let i = 0; i < this.rows.length; i++) {
      const c = this.piv[i];
      if (isZ(v[c])) continue;
      const f = v[c], r = this.rows[i];
      for (let j = 0; j < this.n; j++) if (!isZ(r[j])) v[j] = sub(v[j], mul(f, r[j]));
      if (this.track) for (const [k, p] of this.prov[i]) { const t = add(comb.get(k) || Z, mul(f, p)); if (isZ(t)) comb.delete(k); else comb.set(k, t); }
    }
    return [v, comb];
  }
  insert(v, k) {
    const [r0, comb] = this.reduce(v);
    const c = r0.findIndex((x) => !isZ(x));
    if (c < 0) return false;
    // r0 = v - sum(comb) = gen_k - sum(comb)
    const prov = new Map(); if (this.track) prov.set(k, ONE);
    for (const [j, p] of comb) { const t = sub(prov.get(j) || Z, p); if (isZ(t)) prov.delete(j); else prov.set(j, t); }
    const f = inv(r0[c]);
    const row = r0.map((x) => mul(x, f));
    for (const [j, p] of prov) prov.set(j, mul(p, f));
    for (let i = 0; i < this.rows.length; i++) {
      const r = this.rows[i];
      if (isZ(r[c])) continue;
      const g = r[c];
      for (let j = 0; j < this.n; j++) if (!isZ(row[j])) r[j] = sub(r[j], mul(g, row[j]));
      const P = this.prov[i];
      for (const [j, p] of prov) { const t = sub(P.get(j) || Z, mul(g, p)); if (isZ(t)) P.delete(j); else P.set(j, t); }
    }
    this.rows.push(row); this.piv.push(c); this.prov.push(prov);
    return true;
  }
}

// solve target = sum c_g * gen_g over the given generator list, if possible; returns Map index->coeff or null
function solveIn(n, gens, target) {
  const sp = new Span(n);
  gens.forEach((g, i) => sp.insert(genVec(n, g), i));
  const [nf, comb] = sp.reduce(target);
  return nf.every(isZ) ? comb : null;
}

// shrink a combination to an inclusion-minimal set of generators (then its coefficients are unique)
function minimise(n, gens, target) {
  let keep = gens.slice();
  for (let i = keep.length - 1; i >= 0; i--) {
    const trial = keep.slice(0, i).concat(keep.slice(i + 1));
    if (solveIn(n, trial, target)) keep = trial;
  }
  const comb = solveIn(n, keep, target);
  return keep.map((g, i) => [g, comb.get(i) || Z]).filter(([, c]) => !isZ(c));
}

const sortPair = (a, b) => (a < b ? [a, b] : [b, a]);

// ---------- search ----------
function adjOf(n, Eset) {
  const adj = Array.from({ length: n }, () => new Array(n).fill(false));
  for (const e of Eset) { const [a, b] = e.split('-').map(Number); adj[a][b] = adj[b][a] = true; }
  return adj;
}
function gensFor(n, Eset, orient) {
  const adj = adjOf(n, Eset);
  const G = [];
  for (let u = 0; u < n; u++) for (let w = u + 1; w < n; w++) {
    const C = []; for (let v = 0; v < n; v++) if (adj[u][v] && adj[w][v]) C.push(v);
    for (let i = 0; i < C.length; i++) for (let j = i + 1; j < C.length; j++) {
      if (Math.min(C[i], C[j]) < u) continue; // each 4-cycle once: u is its smallest vertex
      G.push(['R', u, C[i], w, C[j]]);
    }
  }
  for (const [t, s] of [...orient].sort()) { const [a, b, c] = t.split(',').map(Number); G.push(['T', a, b, c, s]); }
  return { G, adj };
}
function triList(n, Eset) {
  const adj = adjOf(n, Eset), T = [];
  for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) if (adj[a][b]) for (let c = b + 1; c < n; c++) if (adj[a][c] && adj[b][c]) T.push(a + ',' + b + ',' + c);
  return T;
}
const ekey = (a, b) => (a < b ? a + '-' + b : b + '-' + a);

// One round of consequences at an edge set: every collision, every edge at a forced wrong length, every forced unit
// distance. With prov = true the span tracks which generators each conclusion uses.
function round(n, Eset, orient, prov) {
  const { G, adj } = gensFor(n, Eset, orient);
  const sp = new Span(n, prov);
  G.forEach((g, i) => sp.insert(genVec(n, g), i));
  const NF = {}, CB = {}, contra = [], forced = [];
  for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) {
    const [nf, comb] = sp.reduce(diffVec(n, a, b));
    NF[a + '-' + b] = nf; CB[a + '-' + b] = comb;
    if (nf.every(isZ)) contra.push({ type: 'collision', pair: [a, b] });
  }
  const E = [...Eset].map((e) => e.split('-').map(Number)).sort((p, q) => p[0] - q[0] || p[1] - q[1]);
  for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) {
    const dab = NF[a + '-' + b];
    if (dab.every(isZ)) continue;
    for (const [u, v] of E) {
      if (u === a && v === b) continue;
      const duv = NF[u + '-' + v];
      const k = duv.findIndex((x) => !isZ(x));
      if (k < 0 || isZ(dab[k])) continue;
      const zeta = mul(dab[k], inv(duv[k]));
      let par = true;
      for (let j = 0; j < n; j++) if (!eqq(dab[j], mul(zeta, duv[j]))) { par = false; break; }
      if (!par) continue;
      const unit = isUnit(zeta), isEdge = adj[a][b];
      if (isEdge && !unit) contra.push({ type: 'length', edge: [a, b], via: [u, v], zeta });
      else if (!isEdge && unit) forced.push({ edge: [a, b], via: [u, v], zeta });
      if (!prov) break; // the length |z_a - z_b| is now known; the fast path needs no second witness
    }
  }
  return { G, CB, contra, forced };
}

function fastClose(n, Eset, orient) {
  Eset = new Set(Eset);
  for (;;) {
    const r = round(n, Eset, orient, false);
    if (r.contra.length) return { contra: true, E: Eset };
    const add = [...new Set(r.forced.map((f) => ekey(...f.edge)))];
    if (!add.length) return { contra: false, E: Eset };
    for (const k of add) Eset.add(k);
  }
}

const stateKey = (Eset, orient, mirror) => [...Eset].sort().join(' ') + '|' + [...orient].sort().map((x) => x.join(':')).join(' ') + '|' + (mirror ? 'm' : '');

// Branch on the first unoriented triangle every time. Complete: it reaches every orientation of every triangle
// (unless a contradiction closes the branch first), so it refutes exactly when some case tree does.
function greedyPlan(n, Eset, orient, mirror) {
  const r = fastClose(n, Eset, orient);
  if (r.contra) return { leaves: 1, close: true };
  const T = triList(n, r.E).filter((t) => !orient.has(t));
  if (!T.length) return null;
  const cases = {}; let sum = 0;
  for (const s of mirror ? [1] : [1, -1]) {
    const o2 = new Map(orient); o2.set(T[0], s);
    const c = greedyPlan(n, r.E, o2, false);
    if (!c) return null;
    cases[s > 0 ? '+1' : '-1'] = c; sum += c.leaves;
  }
  return { leaves: sum, split: T[0], cases, greedy: true };
}

// Phase 1: the case tree with the fewest leaves (fewest separate contradictions). best(state, cap) returns the
// optimal plan if it has at most cap leaves, else null; a returned plan is the global optimum, because any plan with
// fewer leaves would also fit under cap and would have been found. Memoised; budgeted, with a greedy fallback.
function planTree(n, E0, budget) {
  const memo = new Map(); let calls = 0;
  function best(Eset, orient, mirror, cap) {
    const key = stateKey(Eset, orient, mirror);
    const m = memo.get(key);
    if (m) {
      if (m.plan) return m.plan.leaves <= cap ? m.plan : null;
      if (m.none) return null;
      if (m.atLeast > cap) return null;
    }
    if (++calls > budget) throw new Error('budget');
    const r = fastClose(n, Eset, orient);
    if (r.contra) { const plan = { leaves: 1, close: true }; memo.set(key, { plan }); return plan; }
    const T = triList(n, r.E).filter((t) => !orient.has(t));
    const signs = mirror ? [1] : [1, -1];
    let bestV = null, limit = cap;
    for (const t of T) {
      if (limit < signs.length) break;
      let sum = 0; const cases = {}; let ok = true;
      for (let i = 0; i < signs.length; i++) {
        const room = limit - sum - (signs.length - i - 1);
        if (room < 1) { ok = false; break; }
        const o2 = new Map(orient); o2.set(t, signs[i]);
        const c = best(r.E, o2, false, room);
        if (!c) { ok = false; break; }
        sum += c.leaves; cases[signs[i] > 0 ? '+1' : '-1'] = c;
      }
      if (ok) { bestV = { leaves: sum, split: t, cases }; limit = sum - 1; }
    }
    if (bestV) memo.set(key, { plan: bestV });
    else if (cap === Infinity) memo.set(key, { none: true });
    else memo.set(key, { atLeast: Math.max(cap + 1, (m && m.atLeast) || 0) });
    return bestV;
  }
  try { return best(E0, new Map(), true, Infinity); }
  catch (e) { if (e.message !== 'budget') throw e; return greedyPlan(n, E0, new Map(), true); }
}

// Phase 2: at each node, the contradiction whose whole proof (its own relations plus every forced edge it needs, and
// theirs) uses the fewest relations.
function genEdges(g) {
  if (g[0] === 'R') { const [, u, v, w, x] = g; return [ekey(u, v), ekey(v, w), ekey(w, x), ekey(x, u)]; }
  const [, a, b, c] = g; return [ekey(a, b), ekey(b, c), ekey(a, c)];
}
function height(comb) { let h = 0; for (const [, c] of comb) h += c[0].toString().length + c[1].toString().length + c[2].toString().length; return h; }

function readableNode(n, E, orient, wantEnd) {
  // run rounds; remember every forced edge with the round it appeared in and the generators of that round
  let Eset = new Set(E);
  const lemmaAt = new Map(); // ekey -> {rec, roundG, CB}
  for (let rd = 0; ; rd++) {
    const r = round(n, Eset, orient, true);
    const lemmaProof = (key) => {
      const L = lemmaAt.get(key);
      if (L.proof) return L.proof;
      let bestP = null;
      for (const f of L.options) {
        const target = diffVec(n, ...f.edge); const t2 = diffVec(n, ...f.via);
        for (let j = 0; j < n; j++) target[j] = sub(target[j], mul(f.zeta, t2[j]));
        const used = new Set([...L.CB[f.edge.join('-')].keys(), ...L.CB[f.via.join('-')].keys()]);
        const comb = minimise(n, [...used].map((i) => L.G[i]), target);
        const cand = { edge: f.edge, via: f.via, zeta: toStr(f.zeta), comb };
        if (!bestP || comb.length < bestP.comb.length || (comb.length === bestP.comb.length && height(comb) < height(bestP.comb))) bestP = cand;
      }
      L.proof = bestP; return bestP;
    };
    // everything a set of generators (plus some named edges) needs, transitively, as lemma keys
    const needs = (gens, edges) => {
      const need = new Set(); const stack = [];
      const visit = (k) => { if (lemmaAt.has(k) && !need.has(k)) { need.add(k); stack.push(k); } };
      for (const g of gens) genEdges(g).forEach(visit);
      for (const e of edges) visit(e);
      while (stack.length) { const p = lemmaProof(stack.pop()); for (const [g] of p.comb) genEdges(g).forEach(visit); visit(ekey(...p.via)); }
      return need;
    };
    if (r.contra.length) {
      let bestC = null;
      for (const c of r.contra) {
        let target, used;
        if (c.type === 'collision') { target = diffVec(n, ...c.pair); used = r.CB[c.pair.join('-')]; }
        else {
          target = diffVec(n, ...c.edge); const t2 = diffVec(n, ...c.via);
          for (let j = 0; j < n; j++) target[j] = sub(target[j], mul(c.zeta, t2[j]));
          used = new Set([...r.CB[c.edge.join('-')].keys(), ...r.CB[c.via.join('-')].keys()]);
        }
        const comb = minimise(n, [...(used instanceof Map ? used.keys() : used)].map((i) => r.G[i]), target);
        const end = c.type === 'collision' ? { type: 'collision', pair: c.pair, comb } : { type: 'length', edge: c.edge, via: c.via, zeta: toStr(c.zeta), comb };
        const need = needs(comb.map(([g]) => g), c.type === 'length' ? [ekey(...c.edge), ekey(...c.via)] : []);
        let cost = comb.length; for (const k of need) cost += lemmaProof(k).comb.length;
        const h = height(comb);
        if (!bestC || cost < bestC.cost || (cost === bestC.cost && h < bestC.h)) bestC = { cost, h, end, need };
      }
      const lemmas = [...lemmaAt.keys()].filter((k) => bestC.need.has(k)).map((k) => lemmaProof(k));
      return { lemmas, end: bestC.end };
    }
    const byEdge = new Map();
    for (const f of r.forced) { const k = ekey(...f.edge); if (!byEdge.has(k)) byEdge.set(k, []); byEdge.get(k).push(f); }
    if (!byEdge.size) {
      if (wantEnd) throw new Error('phase 2 found no contradiction where phase 1 did');
      const lemmas = [...lemmaAt.keys()].map((k) => lemmaProof(k));
      return { lemmas, E: Eset };
    }
    for (const [k, opts] of byEdge) lemmaAt.set(k, { options: opts, G: r.G, CB: r.CB, proof: null });
    Eset = new Set(Eset); for (const k of byEdge.keys()) Eset.add(k);
  }
}

export function search(n, edges, opts = {}) {
  const budget = opts.budget || 3000;
  const E0 = new Set(edges.map(([a, b]) => ekey(a, b)));
  const plan = planTree(n, E0, budget);
  if (!plan) return { refuted: false };
  function build(Eset, orient, mirror, p) {
    if (p.close) { const r = readableNode(n, Eset, orient, true); return { lemmas: r.lemmas, end: r.end }; }
    const r = readableNode(n, Eset, orient, false);
    if (r.end) return { lemmas: r.lemmas, end: r.end }; // a contradiction phase 1 did not need to split for
    const cases = {};
    for (const [k, c] of Object.entries(p.cases)) { const o2 = new Map(orient); o2.set(p.split, k === '+1' ? 1 : -1); cases[k] = build(r.E, o2, false, c); }
    return { lemmas: r.lemmas, split: { tri: p.split.split(',').map(Number), mirror, cases } };
  }
  const proof = prune(build(E0, new Map(), true, plan));
  return { refuted: true, proof, leaves: plan.leaves, greedy: !!plan.greedy };
}

// Phase 1 alone: the verdict, fast, for a live run in the browser.
export function quickRefute(n, edges) {
  const E0 = new Set(edges.map(([a, b]) => ekey(a, b)));
  return { refuted: !!greedyPlan(n, E0, new Map(), true) };
}

// Drop lemmas nothing downstream uses, and collapse a split whose cases never use its own triangle.
function prune(node) {
  const usesEdge = (g, [a, b]) => {
    const has = (p, q) => sortPair(p, q)[0] === Math.min(a, b) && sortPair(p, q)[1] === Math.max(a, b);
    if (g[0] === 'R') { const [, u, v, w, x] = g; return has(u, v) || has(v, w) || has(w, x) || has(x, u); }
    const [, p, q, r] = g; return has(p, q) || has(q, r) || has(p, r);
  };
  function need(n, lemmas, finalGens, extraEdges) {
    // walk lemmas backwards keeping those whose edge is used by a kept generator (or by a later kept lemma's generators)
    let gens = finalGens.slice(); const keep = new Array(lemmas.length).fill(false);
    const edgesNeeded = (extraEdges || []).slice();
    for (let i = lemmas.length - 1; i >= 0; i--) {
      const l = lemmas[i];
      const used = gens.some((g) => usesEdge(g, l.edge)) || edgesNeeded.some(([a, b]) => sortPair(a, b).join('-') === sortPair(...l.edge).join('-'));
      if (used) { keep[i] = true; gens = gens.concat(l.comb.map(([g]) => g)); edgesNeeded.push(l.via); }
    }
    return keep;
  }
  function walk(nd) {
    if (nd.end) {
      const gens = nd.end.comb.map(([g]) => g);
      const extra = nd.end.type === 'length' ? [nd.end.edge, nd.end.via] : [];
      const keep = need(0, nd.lemmas, gens, extra);
      return { lemmas: nd.lemmas.filter((_, i) => keep[i]), end: nd.end };
    }
    const cases = {};
    for (const k of Object.keys(nd.split.cases)) cases[k] = walk(nd.split.cases[k]);
    // gather what the subtree needs from this node: generators and edges mentioned anywhere below
    const below = [];
    const collect = (x) => { for (const l of x.lemmas) { below.push(...l.comb.map(([g]) => g)); } if (x.end) below.push(...x.end.comb.map(([g]) => g)); if (x.split) for (const c of Object.values(x.split.cases)) collect(c); };
    const tri = nd.split.tri;
    const edgesBelow = [];
    const collectEdges = (x) => { for (const l of x.lemmas) edgesBelow.push(l.via); if (x.end && x.end.type === 'length') edgesBelow.push(x.end.edge, x.end.via); if (x.split) { edgesBelow.push([x.split.tri[0], x.split.tri[1]], [x.split.tri[1], x.split.tri[2]], [x.split.tri[0], x.split.tri[2]]); for (const c of Object.values(x.split.cases)) collectEdges(c); } };
    for (const c of Object.values(cases)) { collect(c); collectEdges(c); }
    edgesBelow.push([tri[0], tri[1]], [tri[1], tri[2]], [tri[0], tri[2]]);
    const keep = need(0, nd.lemmas, below, edgesBelow);
    return { lemmas: nd.lemmas.filter((_, i) => keep[i]), split: { ...nd.split, cases } };
  }
  return walk(node);
}

// ---------- check: verify a proof object, no search ----------
// Returns { ok: true } or { ok: false, why }.
export function check(n, edges, proof) {
  const E0 = new Set(edges.map(([a, b]) => sortPair(a, b).join('-')));
  const hasE = (Eset, a, b) => a !== b && Eset.has(sortPair(a, b).join('-'));
  function validGen(g, Eset, orient) {
    if (g[0] === 'R') {
      const [, u, v, w, x] = g;
      if (new Set([u, v, w, x]).size !== 4 || [u, v, w, x].some((i) => !(Number.isInteger(i) && i >= 0 && i < n))) return 'rhombus vertices';
      if (!(hasE(Eset, u, v) && hasE(Eset, v, w) && hasE(Eset, w, x) && hasE(Eset, x, u))) return `4-cycle ${u}-${v}-${w}-${x} is not in the graph`;
      return null;
    }
    if (g[0] === 'T') {
      const [, a, b, c, s] = g;
      if (!(a < b && b < c && a >= 0 && c < n)) return 'triangle vertices';
      if (!(hasE(Eset, a, b) && hasE(Eset, b, c) && hasE(Eset, a, c))) return `triangle ${a},${b},${c} is not in the graph`;
      if (orient.get(`${a},${b},${c}`) !== s) return `triangle ${a},${b},${c} has not been oriented ${s} on this path`;
      return null;
    }
    return 'unknown generator';
  }
  function sumComb(comb, Eset, orient) {
    const v = new Array(n).fill(Z);
    for (const [g, c0] of comb) {
      const c = typeof c0 === 'string' ? fromStr(c0) : c0;
      const bad = validGen(g, Eset, orient); if (bad) throw new Error(bad);
      const gv = genVec(n, g);
      for (let j = 0; j < n; j++) v[j] = add(v[j], mul(c, gv[j]));
    }
    return v;
  }
  function target(a, b, u, v, zeta) {
    const t = diffVec(n, a, b);
    if (u !== undefined) { const d = diffVec(n, u, v); for (let j = 0; j < n; j++) t[j] = sub(t[j], mul(zeta, d[j])); }
    return t;
  }
  const same = (x, y) => x.every((e, j) => eqq(e, y[j]));
  function node(nd, Eset, orient, mirrorFree) {
    Eset = new Set(Eset);
    for (const l of nd.lemmas || []) {
      const [a, b] = l.edge, [u, v] = l.via, zeta = fromStr(l.zeta);
      if (hasE(Eset, a, b) || a === b) throw new Error(`lemma edge ${a}-${b} is already an edge`);
      if (!hasE(Eset, u, v)) throw new Error(`lemma copies ${u}-${v}, which is not an edge`);
      if (!isUnit(zeta)) throw new Error(`lemma ${a}-${b}: |zeta| is not 1`);
      if (!same(sumComb(l.comb, Eset, orient), target(a, b, u, v, zeta))) throw new Error(`lemma ${a}-${b}: the relations do not add up`);
      Eset.add(sortPair(a, b).join('-'));
    }
    if (nd.end) {
      const e = nd.end;
      if (e.type === 'collision') {
        const [a, b] = e.pair; if (a === b) throw new Error('collision of a vertex with itself');
        if (!same(sumComb(e.comb, Eset, orient), target(a, b))) throw new Error(`collision ${a}=${b}: the relations do not add up`);
        return 1;
      }
      if (e.type === 'length') {
        const [a, b] = e.edge, [u, v] = e.via, zeta = fromStr(e.zeta);
        if (!hasE(Eset, a, b) || !hasE(Eset, u, v)) throw new Error('length: both pairs must be edges');
        if (isUnit(zeta)) throw new Error('length: |zeta| = 1 is no contradiction');
        if (!same(sumComb(e.comb, Eset, orient), target(a, b, u, v, zeta))) throw new Error(`length ${a}-${b}: the relations do not add up`);
        return 1;
      }
      throw new Error('unknown ending');
    }
    if (nd.split) {
      const [a, b, c] = nd.split.tri;
      if (!(a < b && b < c) || !(hasE(Eset, a, b) && hasE(Eset, b, c) && hasE(Eset, a, c))) throw new Error('split on a non-triangle');
      const key = `${a},${b},${c}`;
      if (orient.has(key)) throw new Error('split on a triangle already oriented');
      const cases = nd.split.cases || {};
      const need = nd.split.mirror ? ['+1'] : ['+1', '-1'];
      if (nd.split.mirror && !mirrorFree) throw new Error('mirror used after an orientation was fixed');
      if (Object.keys(cases).length !== need.length || !need.every((k) => cases[k])) throw new Error('split does not cover its cases');
      let leaves = 0;
      for (const k of need) { const o2 = new Map(orient); o2.set(key, k === '+1' ? 1 : -1); leaves += node(cases[k], Eset, o2, false); }
      return leaves;
    }
    throw new Error('node with neither an ending nor a split');
  }
  try { const leaves = node(proof, E0, new Map(), true); return { ok: true, leaves }; } catch (e) { return { ok: false, why: e.message }; }
}

export function decodeG6(s) {
  const n = s.charCodeAt(0) - 63;
  const bits = [];
  for (const ch of s.slice(1)) { const v = ch.charCodeAt(0) - 63; for (let k = 5; k >= 0; k--) bits.push((v >> k) & 1); }
  const E = []; let k = 0;
  for (let j = 1; j < n; j++) for (let i = 0; i < j; i++) { if (bits[k]) E.push([i, j]); k++; }
  return { n, edges: E };
}
