#!/usr/bin/env node
// Offline verifier for "Every Pair, Once": the fifteen schoolgirls of Kirkman
// (1850), read as the Steiner triple system S(2,3,15) that IS the finite
// projective space PG(3,2) over F_2. The values behind the page's live readouts
// are asserted here from first principles; the page's prose is not read.
//
// Run:  node research/every-pair-once/verify.mjs
// Or:   node verify-every-pair-once.mjs   (same file re-exported at repo root)

import {
  POINTS, computeLines, allPairs, findResolution, meetingDayOf,
  pairsCoveredOnce, dayPartitionsOk, enumerateResolutions,
  AG23_POINTS, ag23Lines, ag23Resolution, ag23PairsCoveredOnce,
} from '../../public/strata/every-pair-once/engine/kirkman.mjs';

let n = 0, ok = 0, fail = 0;
const check = (label, cond, detail = '') => {
  n++;
  if (cond) { ok++; console.log(`  ✓ ${label}${detail ? '  ' + detail : ''}`); }
  else      { fail++; console.log(`  ✗ ${label}${detail ? '  ' + detail : ''}`); }
};

console.log('\nEvery Pair, Once: the fifteen schoolgirls, verified from first principles\n');

// -------- Section 1: the object of PG(3,2) --------
console.log('Section 1. The object: PG(3,2) as F_2^4 minus zero');

check('POINTS has 15 members (F_2^4 minus zero)', POINTS.length === 15);
check('POINTS is exactly {1..15}', POINTS.every((v, i) => v === i + 1));

const LINES = computeLines();
check('35 lines emerge (C(15,2)/C(3,2) = 105/3 = 35)', LINES.length === 35);

const allXorZero = LINES.every(([a, b, c]) => (a ^ b ^ c) === 0);
check('every line XORs to zero (F_2-linear-dependent triple)', allXorZero);

const allLen3 = LINES.every(l => l.length === 3);
check('every line has exactly 3 points', allLen3);

// Distinct.
const lineKeys = new Set(LINES.map(l => l.slice().sort((a,b)=>a-b).join(',')));
check('all 35 lines distinct after sort', lineKeys.size === 35);

// -------- Section 2: the S(2,3,15) property (Kirkman's target) --------
console.log('\nSection 2. S(2,3,15): every pair of girls in exactly one triple');

const PAIRS = allPairs();
check('105 pairs enumerated (C(15,2))', PAIRS.length === 105);

const pairCount = new Map();
const pk = (a, b) => `${Math.min(a,b)},${Math.max(a,b)}`;
for (const [a, b, c] of LINES) {
  pairCount.set(pk(a, b), (pairCount.get(pk(a, b)) || 0) + 1);
  pairCount.set(pk(a, c), (pairCount.get(pk(a, c)) || 0) + 1);
  pairCount.set(pk(b, c), (pairCount.get(pk(b, c)) || 0) + 1);
}
let coveredOnce = 0, badPair = 0, missingPair = 0;
for (const [a, b] of PAIRS) {
  const c = pairCount.get(pk(a, b)) || 0;
  if (c === 1) coveredOnce++;
  else if (c === 0) missingPair++;
  else badPair++;
}
check('each of the 105 pairs appears in exactly ONE line', coveredOnce === 105 && badPair === 0 && missingPair === 0, `(covered ${coveredOnce}, missing ${missingPair}, overfull ${badPair})`);

// Fisher's inequality corollary for r: every point lies on exactly r = (15-1)/(3-1) = 7 lines.
const linesThroughPoint = new Array(16).fill(0);
for (const [a, b, c] of LINES) { linesThroughPoint[a]++; linesThroughPoint[b]++; linesThroughPoint[c]++; }
let ptOk = true, minr = 999, maxr = 0;
for (let p = 1; p <= 15; p++) { minr = Math.min(minr, linesThroughPoint[p]); maxr = Math.max(maxr, linesThroughPoint[p]); if (linesThroughPoint[p] !== 7) ptOk = false; }
check('every point lies on exactly r = 7 lines', ptOk, `(min ${minr}, max ${maxr})`);

// b = 35, v = 15, r = 7, k = 3, lambda = 1: the classical (v,k,lambda) = (15,3,1) BIBD.
check('parameters (v,b,r,k,λ) = (15, 35, 7, 3, 1)', LINES.length === 35 && POINTS.length === 15);

// -------- Section 3: a resolution, the seven days --------
console.log('\nSection 3. A resolution: 35 lines partition into 7 days of 5');

const schedule = findResolution(LINES, 0);
check('a resolution exists (found by exhaustive backtracking)', !!schedule);
check('7 days', schedule && schedule.length === 7);
check('each day has 5 lines', schedule && schedule.every(d => d.length === 5));
check('every day partitions the 15 girls (five disjoint triples)', dayPartitionsOk(schedule));

const spread = pairsCoveredOnce(schedule);
check('across the seven days, every pair meets exactly once', spread.ok, `(105 pairs, all singleton)`);

// Every line used exactly once across the schedule.
const usedLines = new Set();
for (const day of schedule) for (const line of day) usedLines.add(line.slice().sort((a,b)=>a-b).join(','));
check('all 35 lines used exactly once (no line unused, no line repeated)', usedLines.size === 35);

// A named property of KTS(15) is Cole's 1922 theorem: exactly seven Kirkman
// triple systems on 15 points exist up to isomorphism (Cole, Bull. AMS 28:435).
// The bounded enumeration here does NOT canonicalise up to relabelling, so it
// counts labelled resolutions, of which there are more; we only assert that a
// modest cap finds several distinct labelled resolutions, i.e. that a single
// resolution is not accidentally unique in labels.
const found = enumerateResolutions(LINES, 20);
check('bounded enumeration finds several distinct labelled resolutions (cap 20)', found.length >= 8, `(found ${found.length} with cap 20)`);

// -------- Section 4: the sibling AG(2,3): nine girls, four days --------
console.log('\nSection 4. The sibling: AG(2,3), nine girls in four days');

const AG_LINES = ag23Lines();
check('AG(2,3) has 9 points', AG23_POINTS.length === 9);
check('AG(2,3) has 12 lines (four parallel classes × 3)', AG_LINES.length === 12);
const agUnique = new Set(AG_LINES.map(l => l.slice().sort((a,b)=>a-b).join(',')));
check('12 lines are distinct', agUnique.size === 12);

// Every point on exactly 4 lines.
const ptLines = new Array(9).fill(0);
for (const l of AG_LINES) for (const p of l) ptLines[p]++;
check('every point on r = 4 lines', ptLines.every(x => x === 4));

const agSched = ag23Resolution();
check('AG(2,3) resolves into 4 parallel classes of 3 lines', agSched.length === 4 && agSched.every(d => d.length === 3));
check('every AG(2,3) day partitions the 9 points', agSched.every(day => {
  const seen = new Set();
  for (const line of day) for (const p of line) { if (seen.has(p)) return false; seen.add(p); }
  return seen.size === 9;
}));
const agSpread = ag23PairsCoveredOnce(agSched);
check('across four days, every AG(2,3) pair meets exactly once (36 pairs)', agSpread.ok, `(${agSpread.once} pairs, singleton)`);

// -------- Section 5: XOR-tests the browser will run --------
console.log('\nSection 5. XOR triple test (the browser instrument)');

// The browser will test any triple {a,b,c}: it is a PG(3,2) line iff a^b^c === 0.
// We enumerate every C(15,3) = 455 triple and count how many pass, and check that
// exactly the 35 lines pass.
let triplesPass = 0;
const lineKey = new Set(LINES.map(l => l.slice().sort((a,b)=>a-b).join(',')));
for (let i = 1; i <= 15; i++) for (let j = i + 1; j <= 15; j++) for (let k = j + 1; k <= 15; k++) {
  if ((i ^ j ^ k) === 0) {
    triplesPass++;
    if (!lineKey.has(`${i},${j},${k}`)) { fail++; console.log('  ✗ XOR-zero triple is not a listed line:', i, j, k); }
  }
}
check('of C(15,3) = 455 triples, exactly 35 have XOR = 0', triplesPass === 35, `(pass ${triplesPass})`);

// -------- Section 6a: Fano subplane count (a claim the page states) --------
// Every three linearly-independent points of PG(3,2) span a Fano plane
// (PG(2,2)): 7 non-zero vectors closed under XOR. How many distinct such
// planes sit inside PG(3,2)? Gaussian binomial [4;3]_2 = 15. Verify by
// enumeration: run over every unordered triple {a,b,c} with a^b^c != 0,
// generate {a, b, c, a^b, a^c, b^c, a^b^c}, canonicalise, count distinct.
{
  const seen = new Set();
  for (let i = 1; i <= 15; i++) for (let j = i + 1; j <= 15; j++) for (let k = j + 1; k <= 15; k++) {
    if ((i ^ j ^ k) === 0) continue; // collinear, spans a line, not a plane
    const s = new Set([i, j, k, i ^ j, i ^ k, j ^ k, i ^ j ^ k]);
    const key = [...s].sort((a, b) => a - b).join(',');
    seen.add(key);
  }
  check('exactly 15 Fano subplanes (PG(2,2)) sit inside PG(3,2)', seen.size === 15, `(found ${seen.size})`);
  // Every Fano has exactly 7 non-zero points.
  const sizes = [...seen].map(s => s.split(',').length);
  check('each Fano subplane has 7 points', sizes.every(x => x === 7));
}

// -------- Section 6: sanity of the F_2-vector-space claim --------
console.log('\nSection 6. F_2^4 vector-space structure (bit labels)');

// Any two distinct non-zero vectors span a 1-dim subspace pair; their XOR is the
// unique third non-zero vector such that {a,b,a^b} is closed under XOR (a 2-flat
// through 0 minus 0 = a line of PG(3,2)).
let closureOk = true;
for (const [a, b, c] of LINES) {
  const closed = [0, a, b, c];
  // check XOR-closure of {0,a,b,c}
  const set = new Set(closed);
  let ok = true;
  for (const x of closed) for (const y of closed) if (!set.has(x ^ y)) { ok = false; break; }
  if (!ok) closureOk = false;
}
check('for every line, {0,a,b,c} is closed under XOR (a 2-flat of F_2^4)', closureOk);

// -------- Section 7: the honest frontier. Kirkman triple systems --------
console.log('\nSection 7. The honest frontier');

// Ray-Chaudhuri and Wilson (1971) proved a Kirkman triple system KTS(v) exists
// iff v ≡ 3 (mod 6). The nine-girl (v=9) and fifteen-girl (v=15) cases are the
// two smallest witnesses; v=3 is trivial. This module ONLY witnesses v=9 and
// v=15 by explicit construction; we do not re-prove Ray-Chaudhuri–Wilson here.
// v ≡ 3 (mod 6) prints as: 3, 9, 15, 21, 27, 33, ...
const smallV = [3, 9, 15, 21, 27, 33].filter(v => v % 6 === 3);
check('the v ≡ 3 (mod 6) witnesses this file builds are 9 and 15', true, `(witnessed v: 9, 15; predicted v: ${smallV.join(', ')})`);

// -------- Summary --------
console.log(`\n${ok}/${n} checks pass; ${fail} failed.`);
if (fail !== 0) process.exit(1);
