#!/usr/bin/env node
// verify.mjs: Dobble / Spot It! comes from a finite projective plane, checked exactly.
//
// The claim of the stratum "Every Two Cards Share a Symbol":
//
//   In Dobble, ANY two cards share EXACTLY ONE symbol. That is not luck or
//   careful hand-tuning; it is a theorem. The retail deck omits two cards
//   from a finite projective plane: cards are the LINES, symbols are the
//   POINTS, and one axiom says "any two lines meet in exactly one point."
//   Build the plane from arithmetic over a finite field and the
//   exactly-one-match property is forced.
//
//   For order n the plane has:
//       n^2 + n + 1   points   (symbols in the universe)
//       n^2 + n + 1   lines    (cards in a full deck)
//       n + 1         points per line   (symbols per card)
//       n + 1         lines per point   (cards bearing any one symbol)
//   and EVERY pair of lines meets in exactly one point, EVERY pair of points
//   lies on exactly one common line.  (Self-dual: swap "card" and "symbol"
//   and the statement is unchanged.)
//
//   Real Dobble: 8 symbols per card => order n = 7 => 7^2+7+1 = 57 cards
//   possible from 57 symbols; the retail deck ships 55 (two are dropped, an
//   honest manufacturing fact, not a math fact).
//
// We construct the plane PG(2, q) for prime q from homogeneous coordinates
// over the field F_q and check, with integer arithmetic only:
//
//   §1  Counts: |points| = |lines| = q^2+q+1; every line has q+1 points;
//       every point lies on q+1 lines.
//   §2  THE GAME'S LAW: every pair of distinct lines (cards) shares EXACTLY
//       ONE point (symbol) — exhaustively, over all C(q^2+q+1, 2) pairs.
//   §3  Dual law: every pair of distinct points lies on exactly one common
//       line — exhaustively.
//   §4  Retail Dobble reconciliation: order 7 gives 57 cards / 8 per card;
//       the published deck of 55 still has the exactly-one-match property
//       (dropping cards can never create a second shared symbol).
//   §5  The honest frontier, stated as arithmetic where it can be:
//       Bruck–Ryser–Chowla forbids orders 6 and (with order 14, 21, 22 …)
//       certain n; order 10 was ruled out by Lam–Thiel–Swiercz (1989) by
//       exhaustive computer search; order 12 is OPEN. We verify the
//       Bruck–Ryser obstruction for n=6 (and that it does NOT obstruct the
//       prime-power orders we actually build).
//
// Run:  node research/dobble-projective-plane/verify.mjs

let PASS = 0, FAIL = 0;
const log = (ok, msg) => { (ok ? PASS++ : FAIL++); console.log(`  ${ok ? "✓" : "✗ FAIL"}  ${msg}`); };
const eq  = (a, b, msg) => log(a === b, `${msg}  (got ${a}${a === b ? "" : `, want ${b}`})`);

// ── finite field arithmetic over F_q, q prime ──────────────────────────────
const isPrime = (n) => {
  if (n < 2) return false;
  for (let d = 2; d * d <= n; d++) if (n % d === 0) return false;
  return true;
};

// ── construct PG(2,q): the projective plane over F_q ────────────────────────
//
// Points and lines are both nonzero triples (a,b,c) in F_q^3, identified up to
// a nonzero scalar (homogeneous coordinates). We canonicalize each class by
// scaling so the first nonzero coordinate is 1. A point [x] lies on a line [L]
// iff the dot product L·x = 0 (mod q). This incidence is self-dual.
function buildPlane(q) {
  if (!isPrime(q)) throw new Error(`buildPlane needs a prime q (got ${q})`);

  // all canonical homogeneous triples = the q^2+q+1 projective points
  const reps = [];
  for (let a = 0; a < q; a++)
    for (let b = 0; b < q; b++)
      for (let c = 0; c < q; c++) {
        if (a === 0 && b === 0 && c === 0) continue;
        // canonical form: scale so leading nonzero coord is 1
        let lead;
        if (a !== 0) lead = a; else if (b !== 0) lead = b; else lead = c;
        // multiplicative inverse of lead mod q (q prime => exists)
        let inv = 1;
        for (let k = 1; k < q; k++) if ((lead * k) % q === 1) { inv = k; break; }
        const t = [(a * inv) % q, (b * inv) % q, (c * inv) % q];
        reps.push(t);
      }
  // de-duplicate (each class has exactly one canonical rep, so this just
  // collapses the scalar multiples we already folded — keep distinct strings)
  const seen = new Map();
  const points = [];
  for (const t of reps) {
    const key = t.join(",");
    if (!seen.has(key)) { seen.set(key, points.length); points.push(t); }
  }

  // lines: same set of canonical triples, read as coefficient vectors.
  // incidence(line, point) := (line · point) % q === 0
  const lines = points; // self-dual: identical index set
  const incident = (L, P) => ((L[0]*P[0] + L[1]*P[1] + L[2]*P[2]) % q) === 0;

  // For each line, list the indices of points on it (= the "symbols on a card")
  const lineToPoints = lines.map(L =>
    points.reduce((acc, P, i) => (incident(L, P) ? (acc.push(i), acc) : acc), [])
  );
  // For each point, list the indices of lines through it (= "cards with a symbol")
  const pointToLines = points.map(P =>
    lines.reduce((acc, L, i) => (incident(L, P) ? (acc.push(i), acc) : acc), [])
  );

  return { q, points, lines, lineToPoints, pointToLines };
}

// intersection size of two index-lists (both sorted ascending by construction)
function sharedCount(a, b) {
  const s = new Set(a);
  let n = 0;
  for (const x of b) if (s.has(x)) n++;
  return n;
}

console.log("\nDobble / Spot It! from a finite projective plane: exact verification\n");

// ── §1 counts ───────────────────────────────────────────────────────────────
console.log("§1  Structure counts for PG(2,q):");
for (const q of [2, 3, 5, 7]) {
  const plane = buildPlane(q);
  const N = q*q + q + 1;
  eq(plane.points.length, N, `q=${q}: number of symbols (points) = q²+q+1`);
  eq(plane.lines.length,  N, `q=${q}: number of cards (lines)   = q²+q+1`);
  const cardSizes = new Set(plane.lineToPoints.map(l => l.length));
  eq(cardSizes.size, 1, `q=${q}: every card has the same number of symbols`);
  eq([...cardSizes][0], q + 1, `q=${q}: symbols per card = q+1`);
  const pointDegs = new Set(plane.pointToLines.map(l => l.length));
  eq(pointDegs.size, 1, `q=${q}: every symbol appears on the same number of cards`);
  eq([...pointDegs][0], q + 1, `q=${q}: cards bearing any one symbol = q+1`);
}

// ── §2 THE GAME'S LAW: any two cards share exactly one symbol ───────────────
console.log("\n§2  Any two cards (lines) share EXACTLY ONE symbol (point) — all pairs:");
for (const q of [2, 3, 5, 7]) {
  const plane = buildPlane(q);
  const L = plane.lineToPoints;
  let pairs = 0, ok = true, minShare = Infinity, maxShare = -Infinity;
  for (let i = 0; i < L.length; i++)
    for (let j = i + 1; j < L.length; j++) {
      const s = sharedCount(L[i], L[j]);
      minShare = Math.min(minShare, s); maxShare = Math.max(maxShare, s);
      if (s !== 1) ok = false;
      pairs++;
    }
  const expectPairs = (L.length * (L.length - 1)) / 2;
  eq(pairs, expectPairs, `q=${q}: checked all C(${L.length},2)=${expectPairs} card pairs`);
  log(ok && minShare === 1 && maxShare === 1,
      `q=${q}: every pair shares exactly 1 symbol (min=${minShare}, max=${maxShare})`);
}

// ── §3 dual law: any two symbols lie on exactly one common card ─────────────
console.log("\n§3  Any two symbols (points) share EXACTLY ONE card (line) — all pairs (self-duality):");
for (const q of [2, 3, 5, 7]) {
  const plane = buildPlane(q);
  const P = plane.pointToLines;
  let ok = true, minShare = Infinity, maxShare = -Infinity;
  for (let i = 0; i < P.length; i++)
    for (let j = i + 1; j < P.length; j++) {
      const s = sharedCount(P[i], P[j]);
      minShare = Math.min(minShare, s); maxShare = Math.max(maxShare, s);
      if (s !== 1) ok = false;
    }
  log(ok && minShare === 1 && maxShare === 1,
      `q=${q}: every pair of symbols shares exactly 1 card (min=${minShare}, max=${maxShare})`);
}

// ── §4 retail Dobble reconciliation (order 7) ───────────────────────────────
console.log("\n§4  Retail Dobble = order 7:");
{
  const plane = buildPlane(7);
  eq(plane.lines.length, 57, "full deck would be 57 cards (7²+7+1)");
  eq(plane.lineToPoints[0].length, 8, "8 symbols per card (7+1) — the printed value");
  eq(plane.points.length, 57, "57 distinct symbols across the deck");
  // The retail deck ships 55 cards (two dropped). Removing cards never creates
  // a second shared symbol — the property is hereditary. Check on a 55-card
  // subset that exactly-one-match still holds.
  const L = plane.lineToPoints.slice(0, 55);
  let ok = true;
  for (let i = 0; i < L.length; i++)
    for (let j = i + 1; j < L.length; j++)
      if (sharedCount(L[i], L[j]) !== 1) ok = false;
  log(ok, "a 55-card subset still has exactly-one-match (property is hereditary)");
}

// ── §5 the honest frontier: which orders can exist ──────────────────────────
console.log("\n§5  Which orders n admit a projective plane (the honest frontier):");
// Bruck–Ryser theorem (1949): if a projective plane of order n exists
// and n ≡ 1 or 2 (mod 4), then n must be a sum of two integer squares.
// Consequence: n=6 (6≡2 mod4, and 6 is NOT a sum of two squares) is impossible.
function sumOfTwoSquares(n) {
  for (let a = 0; a * a <= n; a++) {
    const r = n - a * a;
    const b = Math.round(Math.sqrt(r));
    if (b * b === r) return true;
  }
  return false;
}
function bruckRyserForbids(n) {
  // returns true iff BRC's necessary condition fails for this n
  const m = n % 4;
  if (m === 1 || m === 2) return !sumOfTwoSquares(n);
  return false; // BRC says nothing for n ≡ 0,3 (mod 4)
}
log(bruckRyserForbids(6), "order 6 is forbidden by Bruck–Ryser (6≡2 mod 4, not a sum of two squares)");
log(!sumOfTwoSquares(6), "  …because 6 = a²+b² has no integer solution");
log(!bruckRyserForbids(7), "order 7 is NOT forbidden by Bruck–Ryser (it's prime — and we built it)");
log(!bruckRyserForbids(10), "order 10 is NOT forbidden by Bruck–Ryser (10=1²+3²) — yet it does not exist");
// Order 10 was eliminated by exhaustive computer search (Lam, Thiel, Swiercz 1989) —
// a result we cite, not re-run here (months of CPU time). Order 12 remains OPEN.
log(sumOfTwoSquares(10), "  10 = 1²+3², so its nonexistence needed a computer proof, not BRC (Lam 1989)");
// Order 12 ≡ 0 (mod 4), so BRC is silent on it; it is neither built nor forbidden — OPEN.
log(!bruckRyserForbids(12), "order 12: Bruck–Ryser is silent (12≡0 mod 4) — the order stays OPEN");

// Every prime is a prime power, so PG(2,p) exists for it; we actually built p≤7.
// Assert the non-trivial fact: none of the small primes is BRC-forbidden.
for (const q of [2,3,5,7,11]) log(!bruckRyserForbids(q), `order ${q} is prime ⇒ a plane exists, and BRC does not forbid it`);

// ── tally ───────────────────────────────────────────────────────────────────
console.log(`\n${FAIL === 0 ? "✓ ALL PASS" : "✗ FAILURES"}  —  ${PASS} passed, ${FAIL} failed.\n`);
process.exit(FAIL === 0 ? 0 : 1);
