#!/usr/bin/env node
// Offline verifier for the stratum "Seventeen and No More" — the 17 wallpaper groups.
//
// Two load-bearing, fully runnable results sit under the page:
//
//   I.  THE CRYSTALLOGRAPHIC RESTRICTION (Barlow 1894 / Fedorov).
//       A rotation that maps a 2-D lattice onto itself, written in a lattice
//       basis, is an integer matrix; its trace 2*cos(theta) must therefore be an
//       integer. So a lattice rotation of order n exists ONLY when
//       2*cos(2*pi/n) is an integer, which happens for n in {1,2,3,4,6} and for
//       no other n. We verify this exhaustively, show WHY n=5 and n>=7 fail
//       (their trace lies strictly between two integers / is an algebraic
//       irrational), and pin the n=5 value as a root of x^2 + x - 1 = 0.
//
//   II. CONWAY'S MAGIC THEOREM -> EXACTLY 17.
//       Conway (in "The Symmetries of Things", with Burgiel & Goodman-Strauss)
//       assigns a "cost" to the features of an orbifold:
//          o (handle)                     cost 2
//          x (cross-cap / "miracle")      cost 1
//          * (mirror boundary)            cost 1
//          gyration point of order n      cost (n-1)/n        (before any *)
//          corner point of order n        cost (n-1)/(2n)     (on a * boundary)
//       A symmetry group of the Euclidean plane is exactly a finite-order
//       orbifold symbol whose total cost is EXACTLY 2 (Euler characteristic 0).
//       For admissible signatures, cost < 2 => spherical; cost > 2 => hyperbolic
//       (infinitely many). We ENUMERATE every finite orbifold symbol of cost
//       exactly 2 from scratch, by exact rational arithmetic, and confirm the
//       result is precisely the 17 canonical wallpaper symbols, each carried with
//       its IUC (crystallographic) name. The enumeration is the proof of "17".
//
// Everything is exact: costs are reduced fractions over BigInt, never floats.
// The crystallographic-restriction numerics are checked against closed forms.
//
// Run:  node research/wallpaper-groups/verify.mjs
// Pure Node, no dependencies. Prints "PASS n/n" or throws on the first failure.

let pass = 0, total = 0;
const log = [];
function check(name, cond, detail = '') {
  total++;
  if (cond) { pass++; log.push(`  ok   ${name}${detail ? '  —  ' + detail : ''}`); }
  else { log.push(`  FAIL ${name}${detail ? '  —  ' + detail : ''}`); throw new Error('CHECK FAILED: ' + name + ' :: ' + detail); }
}
const near = (a, b, eps) => Math.abs(a - b) <= eps;

// ── exact rational arithmetic over BigInt ─────────────────────────────────────
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }
function frac(n, d = 1n) {
  n = BigInt(n); d = BigInt(d);
  if (d < 0n) { n = -n; d = -d; }
  const g = gcd(n, d) || 1n;
  return [n / g, d / g];
}
const fadd = ([a, b], [c, d]) => frac(a * d + c * b, b * d);
const feq = ([a, b], [c, d]) => a === c && b === d;
const fle = ([a, b], [c, d]) => a * d <= c * b;            // b,d > 0 always here
const TWO = frac(2n);

// cost pieces, exact
const coneCost = (n) => frac(BigInt(n) - 1n, BigInt(n));        // (n-1)/n
const cornerCost = (n) => frac(BigInt(n) - 1n, 2n * BigInt(n)); // (n-1)/(2n)
const MIRROR = frac(1n), CROSS = frac(1n), HANDLE = frac(2n);

// ══════════════════════════════════════════════════════════════════════════════
//  PART I — THE CRYSTALLOGRAPHIC RESTRICTION
// ══════════════════════════════════════════════════════════════════════════════
// 2*cos(2*pi/n) is an integer  <=>  n in {1,2,3,4,6}.
{
  const allowed = [];
  const NMAX = 2000;
  for (let n = 1; n <= NMAX; n++) {
    const t = 2 * Math.cos(2 * Math.PI / n);
    // is t within a tight tolerance of an integer?
    const r = Math.round(t);
    if (Math.abs(t - r) < 1e-9) allowed.push(n);
  }
  check('crystallographic restriction: allowed orders are exactly {1,2,3,4,6}',
    JSON.stringify(allowed) === JSON.stringify([1, 2, 3, 4, 6]),
    `found {${allowed.join(',')}} up to n=${NMAX}`);

  // the five traces, against their exact closed forms
  const traces = { 1: 2, 2: -2, 3: -1, 4: 0, 6: 1 };
  for (const [n, want] of Object.entries(traces))
    check(`trace 2cos(2pi/${n}) = ${want}`, near(2 * Math.cos(2 * Math.PI / n), want, 1e-12));

  // n=5 fails: 2cos(72deg) = (sqrt5 - 1)/2, the reciprocal golden ratio, a root of x^2+x-1.
  const t5 = 2 * Math.cos(2 * Math.PI / 5);
  check('n=5 trace = (sqrt5-1)/2 ≈ 0.6180339887', near(t5, (Math.sqrt(5) - 1) / 2, 1e-12), t5.toFixed(10));
  check('n=5 trace is a root of x^2 + x - 1 (so irrational: disc 5 not a perfect square)',
    near(t5 * t5 + t5 - 1, 0, 1e-12));
  check('n=5 trace lies strictly between integers 0 and 1 (cannot be an integer)',
    t5 > 0 && t5 < 1);

  // n>=7: 2cos(2pi/n) lies strictly in the OPEN interval (1,2), never an integer.
  let allStrictlyBetween = true, witness = '';
  for (let n = 7; n <= 5000; n++) {
    const t = 2 * Math.cos(2 * Math.PI / n);
    if (!(t > 1 && t < 2)) { allStrictlyBetween = false; witness = `n=${n} -> ${t}`; break; }
  }
  check('for every n>=7, 2cos(2pi/n) is strictly between 1 and 2 — so never an integer',
    allStrictlyBetween, witness || 'held to n=5000');

  // a direct lattice check: a true integer rotation matrix exists for n in {3,4,6}
  // and demonstrably NOT for n=5, by hunting an integer 2x2 matrix of the right order.
  // Order-n integer matrix M of det 1 must satisfy M^n = I and trace(M) = 2cos(2pi/n).
  // We confirm trace must be integer by exhibiting concrete matrices for 3,4,6:
  const rot = {
    4: [[0, -1], [1, 0]],            // 90deg, trace 0
    6: [[1, -1], [1, 0]],            // 60deg in a hex basis, trace 1
    3: [[0, -1], [1, -1]],           // 120deg in a hex basis, trace -1
  };
  const matpow = (M, k) => { let R = [[1, 0], [0, 1]]; const mul = (A, B) => [[A[0][0] * B[0][0] + A[0][1] * B[1][0], A[0][0] * B[0][1] + A[0][1] * B[1][1]], [A[1][0] * B[0][0] + A[1][1] * B[1][0], A[1][0] * B[0][1] + A[1][1] * B[1][1]]]; for (let i = 0; i < k; i++) R = mul(R, M); return R; };
  const isI = (M) => M[0][0] === 1 && M[0][1] === 0 && M[1][0] === 0 && M[1][1] === 1;
  for (const [n, M] of Object.entries(rot)) {
    check(`integer lattice rotation of order ${n} exists (M^${n}=I, integer entries)`, isI(matpow(M, +n)),
      `trace ${M[0][0] + M[1][1]}`);
  }
}

// ══════════════════════════════════════════════════════════════════════════════
//  PART II — CONWAY'S MAGIC THEOREM: ENUMERATE COST-2 ORBIFOLDS -> EXACTLY 17
// ══════════════════════════════════════════════════════════════════════════════
//
// A finite orbifold symbol over the plane is built from:
//   * handles h          (each cost 2)
//   * cross-caps x        (each cost 1)
//   * gyration orders     a multiset of integers >= 2, written before any * (cones)
//   * mirror boundaries   a list of boundaries, each a (possibly empty) multiset
//                         of corner orders >= 2 (each boundary costs 1 + corners)
// A wallpaper group <=> the total cost is EXACTLY 2.  We generate every such
// symbol and read off the set. Orders are searched up to a generous cap; we then
// re-run at a far larger cap to prove the cap never binds.

function canonical(sym) {
  // produce Conway's canonical string for a generated symbol
  // order convention: handles 'o', cones (desc), then each '*' with its corners (desc), then crosses 'x'
  const cones = [...sym.cones].sort((a, b) => b - a).join('');
  const bnds = sym.boundaries.map(c => '*' + [...c].sort((a, b) => b - a).join('')).join('');
  const crosses = 'x'.repeat(sym.crosses);
  const handles = 'o'.repeat(sym.handles);
  const s = handles + cones + bnds + crosses;
  return s === '' ? 'o?' : s;   // (the empty symbol never reaches cost 2)
}

function enumerateCost2(CAP) {
  const found = new Set();
  // bounded multiset generator: nondecreasing orders in [2..CAP], up to maxCount items,
  // whose accumulated cost (via costOf) does not exceed remaining budget.
  function* multisets(maxCount, minOrder, costOf, budgetRemaining) {
    yield [];                                  // the empty multiset
    if (maxCount === 0) return;
    for (let n = minOrder; n <= CAP; n++) {
      const c = costOf(n);
      if (!fle(c, budgetRemaining)) continue;  // this single item already overflows
      for (const rest of multisets(maxCount - 1, n, costOf, fadd(budgetRemaining, frac(-c[0], c[1])))) {
        yield [n, ...rest];
      }
    }
  }

  // handles: 0 or 1 (2 handles = cost 4)
  for (let h = 0; h <= 1; h++) {
    const afterH = fadd(TWO, frac(-(HANDLE[0] * BigInt(h)), HANDLE[1] || 1n));
    if (afterH[0] < 0n) continue;
    // crosses: 0..2
    for (let x = 0; x <= 2; x++) {
      const afterX = fadd(afterH, frac(-BigInt(x), 1n));
      if (afterX[0] < 0n) continue;
      // boundaries: 0,1,2  (each empty boundary already costs 1)
      for (let b = 0; b <= 2; b++) {
        const afterB = fadd(afterX, frac(-BigInt(b), 1n));
        if (afterB[0] < 0n) continue;
        // cones (gyrations): a multiset of orders, cost (n-1)/n each, <=4 of them
        for (const cones of multisets(4, 2, coneCost, afterB)) {
          let used = afterB;
          for (const n of cones) used = fadd(used, frac(-(coneCost(n)[0]), coneCost(n)[1]));
          // now distribute corners across the b boundaries.
          // generate b corner-multisets recursively, each cost (m-1)/(2m).
          function* corners(k, budget) {
            if (k === 0) { yield []; return; }
            for (const first of multisets(8, 2, cornerCost, budget)) {
              let rem = budget;
              for (const m of first) rem = fadd(rem, frac(-(cornerCost(m)[0]), cornerCost(m)[1]));
              for (const rest of corners(k - 1, rem)) yield [first, ...rest];
            }
          }
          for (const bnds of corners(b, used)) {
            let cost = used;
            for (const c of bnds) for (const m of c) cost = fadd(cost, frac(-(cornerCost(m)[0]), cornerCost(m)[1]));
            if (feq(cost, frac(0n))) {
              // total used exactly 2 -> a wallpaper symbol
              found.add(canonical({ handles: h, crosses: x, cones, boundaries: bnds }));
            }
          }
        }
      }
    }
  }
  return found;
}

// The 17 canonical Conway symbols and their IUC (International) names.
const SEVENTEEN = [
  ['o', 'p1'], ['2222', 'p2'], ['xx', 'pg'], ['*x', 'cm'], ['**', 'pm'],
  ['22x', 'pgg'], ['22*', 'pmg'], ['*2222', 'pmm'], ['2*22', 'cmm'],
  ['442', 'p4'], ['*442', 'p4m'], ['4*2', 'p4g'],
  ['333', 'p3'], ['*333', 'p3m1'], ['3*3', 'p31m'],
  ['632', 'p6'], ['*632', 'p6m'],
];
const wantSet = new Set(SEVENTEEN.map(([c]) => c));

{
  const got12 = enumerateCost2(12);
  const got24 = enumerateCost2(24);

  check('enumeration is stable: cap 12 and cap 24 give the same set (the cap never binds)',
    got12.size === got24.size && [...got12].every(s => got24.has(s)),
    `cap12=${got12.size}, cap24=${got24.size}`);

  check('exactly 17 finite orbifold symbols have cost 2', got12.size === 17, `got ${got12.size}: ${[...got12].sort().join(' ')}`);

  const missing = [...wantSet].filter(s => !got12.has(s));
  const extra = [...got12].filter(s => !wantSet.has(s));
  check('the enumerated 17 are exactly the canonical wallpaper symbols', missing.length === 0 && extra.length === 0,
    `missing=[${missing}] extra=[${extra}]`);

  // independently, each canonical symbol parses to cost exactly 2
  function costOfSymbol(s) {
    let cost = frac(0n);
    let i = 0, onBoundary = false;
    while (i < s.length) {
      const ch = s[i];
      if (ch === 'o') { cost = fadd(cost, HANDLE); i++; }
      else if (ch === 'x') { cost = fadd(cost, CROSS); i++; }
      else if (ch === '*') { cost = fadd(cost, MIRROR); onBoundary = true; i++; }
      else if (ch >= '0' && ch <= '9') {
        const n = +ch;                       // all orders here are single digits 2..6
        cost = fadd(cost, onBoundary ? cornerCost(n) : coneCost(n));
        i++;
      } else i++;
    }
    return cost;
  }
  let allTwo = true, bad = '';
  for (const [sym] of SEVENTEEN) if (!feq(costOfSymbol(sym), TWO)) { allTwo = false; bad = sym; break; }
  check('each of the 17 canonical symbols independently has cost exactly 2', allTwo, bad ? `failed at ${bad}` : '');

  // the four rotation-only groups: cone multisets with sum (1-1/n_i) = 2 are exactly
  // {2,2,2,2},{3,3,3},{2,4,4},{2,3,6} -> p2,p3,p4,p6
  const rotOnly = [...got12].filter(s => /^[0-9]+$/.test(s)).sort();
  check('the four rotation-only groups are exactly {2222,333,442,632}',
    JSON.stringify(rotOnly) === JSON.stringify(['2222', '333', '442', '632']),
    rotOnly.join(' '));

  // the four full-mirror (single-boundary, all corners) groups
  const mirrorOnly = [...got12].filter(s => /^\*[0-9]+$/.test(s)).sort();
  check('the four kaleidoscopic groups are exactly {*2222,*333,*442,*632}',
    JSON.stringify(mirrorOnly) === JSON.stringify(['*2222', '*333', '*442', '*632']),
    mirrorOnly.join(' '));

  // names are distinct and there are 17 of them
  const names = new Set(SEVENTEEN.map(([, iuc]) => iuc));
  check('17 distinct IUC names', names.size === 17, [...names].join(' '));
}

// ══════════════════════════════════════════════════════════════════════════════
//  PART III — THE OTHER TWO GEOMETRIES (the same machine, different total)
// ══════════════════════════════════════════════════════════════════════════════
// For admissible signatures: cost < 2 -> spherical; cost > 2 -> hyperbolic.
// MN and *MN with M != N (including an omitted 1) are inadmissible spherical cases.
// A tiny corroboration: the cone-only EUCLIDEAN solutions sum to exactly 2, the
// canonical SPHERICAL triples (2,2,n),(2,3,3),(2,3,4),(2,3,5) sum to < 2, and a
// hyperbolic triple like (2,3,7) sums to > 2 — the signature of "infinitely many".
{
  const triCost = (a, b, c) => fadd(fadd(coneCost(a), coneCost(b)), coneCost(c));
  check('(2,3,6) is Euclidean: cost = 2', feq(triCost(2, 3, 6), TWO));
  check('(2,4,4) is Euclidean: cost = 2', feq(triCost(2, 4, 4), TWO));
  check('(3,3,3) is Euclidean: cost = 2', feq(triCost(3, 3, 3), TWO));
  check('(2,3,5) is spherical: cost < 2', fle(triCost(2, 3, 5), TWO) && !feq(triCost(2, 3, 5), TWO));
  check('(2,3,4) is spherical: cost < 2', fle(triCost(2, 3, 4), TWO) && !feq(triCost(2, 3, 4), TWO));
  check('(2,3,7) is hyperbolic: cost > 2', !fle(triCost(2, 3, 7), TWO));
}

// ── report ────────────────────────────────────────────────────────────────────
console.log(log.join('\n'));
console.log(pass === total ? `\nPASS ${pass}/${total}` : `\nFAIL ${pass}/${total}`);
if (pass !== total) process.exit(1);
