#!/usr/bin/env node
// research/secret-santa/verify.mjs: the checks behind /tools/secret-santa/.
//
//   node research/secret-santa/verify.mjs          # every family; exit 1 on any failure
//   node research/secret-santa/verify.mjs --quick  # fewer random cases
//
// The engine (public/tools/secret-santa/engine.mjs) is what the page runs. Everything it
// claims is re-derived here by a separate, slower route with its own code (it reads the named
// example groups with the page's parser, which family I checks separately): the
// brute force below lists draws itself, checks Hall's condition by trying every subset, and
// tests uniformity with its own chi-square. Each family also carries a NEGATIVE CONTROL, a
// deliberately wrong input the check must reject, because a check that cannot fail is not
// a check.
//
// Randomness here is seeded, so a run is reproducible: the same seed gives the same cases
// and the same draws every time.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import * as E from '../../public/tools/secret-santa/engine.mjs';
import { group, study, methodHat, hatRatios, smallGroups, lastDrawerRatio, SMALL, CASES, Q } from './bias.mjs';
import { render } from './build-method.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '../..');
const QUICK = process.argv.includes('--quick');

let pass = 0, fail = 0;
const failures = [];
function ok(cond, what) {
  if (cond) pass++;
  else { fail++; failures.push(what); if (failures.length <= 30) console.log('  FAIL', what); }
}
function family(name, fn) {
  const before = fail;
  fn();
  console.log(`${fail === before ? 'ok  ' : 'FAIL'} ${name}`);
}

// ── an independent PRNG (mulberry32), not the engine's ───────────────────────────────
function rng(seed) {
  let a = seed >>> 0;
  const next = () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = a;
    t = Math.imul(t ^ (t >>> 15), t | 1);
    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
    return ((t ^ (t >>> 14)) >>> 0);
  };
  return next;
}
const uni = (r) => r() / 4294967296;

// ── independent brute force ─────────────────────────────────────────────────────────
function bruteDraws(n, allow, keep = () => true) {
  const out = [], perm = new Array(n), used = new Array(n).fill(false);
  const rec = (g) => {
    if (g === n) { if (keep(perm)) out.push(perm.slice()); return; }
    for (let r = 0; r < n; r++) if (!used[r] && allow[g * n + r]) { used[r] = true; perm[g] = r; rec(g + 1); used[r] = false; }
  };
  rec(0);
  return out;
}
function hallHolds(n, allow) {
  // every non-empty set of givers may draw at least as many names as it has members
  for (let mask = 1; mask < (1 << n); mask++) {
    let nb = 0, k = 0;
    for (let g = 0; g < n; g++) if (mask & (1 << g)) { k++; for (let r = 0; r < n; r++) if (allow[g * n + r]) nb |= 1 << r; }
    let c = 0; for (let x = nb; x; x &= x - 1) c++;
    if (c < k) return false;
  }
  return true;
}
const twoCycle = (p) => p.some((r, g) => p[r] === g);
const oneCycle = (p) => { let len = 1; for (let v = p[0]; v !== 0; v = p[v]) len++; return len === p.length; };

function randomInstance(r, nMin, nMax) {
  const n = nMin + Math.floor(uni(r) * (nMax - nMin + 1));
  const dens = 0.25 + 0.75 * uni(r);
  const allow = new Uint8Array(n * n);
  for (let g = 0; g < n; g++) for (let x = 0; x < n; x++) allow[g * n + x] = g !== x && uni(r) < dens ? 1 : 0;
  return { n, allow, noMutual: false, oneLoop: false, units: [], blockers: [] };
}
const close = (a, b, eps = 1e-9) => Math.abs(a - b) <= eps;

// chi-square of observed counts against equal expected counts; returns a z score
function chiZ(counts) {
  const N = counts.reduce((s, x) => s + x, 0), k = counts.length, e = N / k;
  let x2 = 0; for (const o of counts) x2 += (o - e) ** 2 / e;
  return (x2 - (k - 1)) / Math.sqrt(2 * (k - 1));
}

// ══════════════════════════════════════════════════════════════════════════════════
console.log('Secret Santa: verifying engine.mjs against independent brute force\n');
const CASES_N = QUICK ? 600 : 2500;

family('A. feasibility agrees with Hall\'s condition checked over every subset', () => {
  const r = rng(20261101);
  for (let t = 0; t < CASES_N; t++) {
    const c = randomInstance(r, 2, 9);
    const m = E.maxMatching(c.n, c.allow);
    ok((m.size === c.n) === hallHolds(c.n, c.allow), `A: n=${c.n} case ${t}`);
    ok((m.size === c.n) === (bruteDraws(c.n, c.allow).length > 0), `A: brute n=${c.n} case ${t}`);
  }
  // control: Hall's check must say no to a matrix with an empty row
  const bad = new Uint8Array(9).fill(1); bad[0] = bad[1] = bad[2] = 0;
  ok(!hallHolds(3, bad), 'A control: empty row passes Hall');
});

family('B. every "impossible" verdict carries a proof a person can check, and it cannot be shortened', () => {
  const r = rng(77);
  let seen = 0;
  for (let t = 0; t < CASES_N && seen < (QUICK ? 150 : 600); t++) {
    const c = randomInstance(r, 2, 9);
    if (E.maxMatching(c.n, c.allow).size === c.n) continue;
    seen++;
    const w = E.hallWitness(c);
    // re-check the witness from scratch: every member's options lie inside w.options,
    // and there are fewer options than members
    const opt = new Set(w.options);
    let inside = true;
    for (const a of w.group) for (let b = 0; b < c.n; b++) {
      const al = w.side === 'givers' ? c.allow[a * c.n + b] : c.allow[b * c.n + a];
      if (al && !opt.has(b)) inside = false;
    }
    ok(inside && w.options.length < w.group.length, `B: witness invalid case ${t}`);
    // the options listed are exactly the members' options (none padded in)
    const real = new Set();
    for (const a of w.group) for (let b = 0; b < c.n; b++) if (w.side === 'givers' ? c.allow[a * c.n + b] : c.allow[b * c.n + a]) real.add(b);
    ok(real.size === w.options.length, `B: options padded case ${t}`);
    // inclusion-minimal: no proper non-empty subgroup is short (every subgroup tried)
    const G = w.group, K = G.length;
    for (let mask = 1; mask < (1 << K) - 1; mask++) {
      const sub = G.filter((_, i) => mask & (1 << i));
      const nb = new Set();
      for (const a of sub) for (let b = 0; b < c.n; b++) if (w.side === 'givers' ? c.allow[a * c.n + b] : c.allow[b * c.n + a]) nb.add(b);
      if (nb.size < sub.length) { ok(false, `B: a smaller group inside the witness is short, case ${t}`); break; }
    }
  }
  ok(seen > 50, `B: too few impossible cases (${seen})`);
  // control: a witness with one option added must be rejected by the engine's own checker
  const P = E.parsePeople('Ann & Ben & Cat\nDan');
  const cons = E.buildConstraints(P.people, P.houses, [], {});
  const w = E.hallWitness(cons);
  ok(E.checkWitness(cons, w), 'B: real witness fails checkWitness');
  ok(!E.checkWitness(cons, { ...w, options: [...w.options, w.group[0]] }), 'B control: padded witness accepted');
});

family('C. exact counts and pairing chances agree with listing every draw', () => {
  const r = rng(4242);
  for (let t = 0; t < CASES_N; t++) {
    const c = randomInstance(r, 2, 8);
    const draws = bruteDraws(c.n, c.allow);
    ok(E.countExact(c) === BigInt(draws.length), `C: count n=${c.n} case ${t}`);
    if (!draws.length) continue;
    const pc = E.pairChances(c);
    const P = new Float64Array(c.n * c.n);
    for (const d of draws) d.forEach((x, g) => { P[g * c.n + x] += 1 / draws.length; });
    let same = true;
    for (let i = 0; i < P.length; i++) if (!close(P[i], pc.P[i])) same = false;
    ok(same, `C: chances n=${c.n} case ${t}`);
  }
  // control: a perturbed table must not match
  const c = randomInstance(rng(5), 6, 6);
  const draws = bruteDraws(c.n, c.allow);
  if (draws.length) {
    const pc = E.pairChances(c);
    const g = draws[0][0];
    pc.P[g] += 1e-6;
    let max = 0;
    const P = new Float64Array(c.n * c.n);
    for (const d of draws) d.forEach((x, gg) => { P[gg * c.n + x] += 1 / draws.length; });
    for (let i = 0; i < P.length; i++) max = Math.max(max, Math.abs(P[i] - pc.P[i]));
    ok(max > 1e-9, 'C control: perturbed chances accepted');
  }
  // the page's own example, by name
  const ex = E.parsePeople('Ann & Ben\nCat & Dan\nEve\nFay & Gus & Hal');
  const exR = E.parseRules('Eve > Fay', ex.people);
  const exC = E.buildConstraints(ex.people, ex.houses, exR.rules, {});
  ok(E.countExact(exC) === 2496n, 'C: the page example has 2,496 valid draws');
  ok(bruteDraws(exC.n, exC.allow).length === 2496, 'C: brute force agrees on 2,496');
});

family('D. forced and impossible pairings agree with listing every draw', () => {
  const r = rng(99);
  for (let t = 0; t < CASES_N; t++) {
    const c = randomInstance(r, 2, 8);
    const draws = bruteDraws(c.n, c.allow);
    if (!draws.length) continue;
    const cl = E.pairingClasses(c);
    const hit = new Map();
    for (const d of draws) d.forEach((x, g) => hit.set(g * c.n + x, (hit.get(g * c.n + x) || 0) + 1));
    const forced = new Set(cl.forced.map(([g, x]) => g * c.n + x)), never = new Set(cl.never.map(([g, x]) => g * c.n + x));
    let good = true;
    for (let g = 0; g < c.n; g++) for (let x = 0; x < c.n; x++) {
      if (!c.allow[g * c.n + x]) continue;
      const k = hit.get(g * c.n + x) || 0;
      if ((k === draws.length) !== forced.has(g * c.n + x)) good = false;
      if ((k === 0) !== never.has(g * c.n + x)) good = false;
    }
    ok(good, `D: classes n=${c.n} case ${t}`);
  }
  // control: a wrong classifier (call every pairing in one matching "forced") must be caught
  const c = randomInstance(rng(3), 6, 6);
  c.allow.fill(1); for (let i = 0; i < 6; i++) c.allow[i * 6 + i] = 0;
  const m = E.maxMatching(6, c.allow);
  const wrong = new Set(Array.from(m.matchL, (x, g) => g * 6 + x));
  const draws = bruteDraws(6, c.allow);
  const hit = new Map(); for (const d of draws) d.forEach((x, g) => hit.set(g * 6 + x, (hit.get(g * 6 + x) || 0) + 1));
  let caught = false; for (const k of wrong) if ((hit.get(k) || 0) !== draws.length) caught = true;
  ok(caught, 'D control: a classifier calling every matched pairing forced was not caught');
});

family('E. what your own slip tells you, by conditioning, agrees with listing every draw', () => {
  const r = rng(1234);
  for (let t = 0; t < (QUICK ? 150 : 500); t++) {
    const c = randomInstance(r, 3, 7);
    const draws = bruteDraws(c.n, c.allow);
    if (!draws.length) continue;
    const g1 = E.guessYourSanta(c);
    for (let i = 0; i < c.n; i++) {
      // P(guess right) = sum over j of max over k of P(i->j and k->i)
      const tally = new Map();
      for (const d of draws) { const k = d.indexOf(i); const key = d[i] * c.n + k; tally.set(key, (tally.get(key) || 0) + 1); }
      let hit = 0;
      for (let j = 0; j < c.n; j++) { let best = 0; for (let k = 0; k < c.n; k++) best = Math.max(best, tally.get(j * c.n + k) || 0); hit += best; }
      ok(close(hit / draws.length, g1[i].guess), `E: guess n=${c.n} person ${i} case ${t}`);
    }
  }
  // three people, no rules: everyone can always work it out
  const P = E.parsePeople('Ann\nBen\nCat');
  const g = E.guessYourSanta(E.buildConstraints(P.people, P.houses, [], {}));
  ok(g.every((x) => close(x.guess, 1)), 'E: three people can always deduce');
  // control: the blind-guess figure (1/2 for three people) must NOT pass as the slip figure
  ok(g.every((x) => !close(x.blind, x.guess)), 'E control: the blind guess passed as the slip guess');
});

family('F. options (no swaps, one circle): exact numbers agree with listing every draw', () => {
  const r = rng(31337);
  for (let t = 0; t < (QUICK ? 200 : 700); t++) {
    const c = randomInstance(r, 3, 8);
    c.noMutual = uni(r) < 0.5; c.oneLoop = !c.noMutual || uni(r) < 0.3;
    const keep = (p) => (!c.noMutual || !twoCycle(p)) && (!c.oneLoop || oneCycle(p));
    const draws = bruteDraws(c.n, c.allow, keep);
    const e = E.enumerateAll(c);
    ok(e && e.count === draws.length, `F: count n=${c.n} case ${t}`);
    if (draws.length && e) {
      const P = new Float64Array(c.n * c.n);
      for (const d of draws) d.forEach((x, g) => { P[g * c.n + x] += 1 / draws.length; });
      let same = true; for (let i = 0; i < P.length; i++) if (!close(P[i], e.P[i])) same = false;
      ok(same, `F: chances n=${c.n} case ${t}`);
    }
  }
  const two = E.parsePeople('Ann & Ben\nCat & Dan');
  const tc = E.buildConstraints(two.people, two.houses, [], { noMutual: true });
  ok(E.analyse(tc).count === 2n, 'F: two couples with no swaps leave exactly 2 draws');
  // control: the same group WITHOUT the option has 4 draws; an engine ignoring the option fails
  const tcOff = E.buildConstraints(two.people, two.houses, [], {});
  ok(E.analyse(tcOff).count === 4n && bruteDraws(4, tcOff.allow).length === 4, 'F control: the option made no difference');
});

family('G. every draw follows the rules, and the samplers are uniform (seeded chi-square)', () => {
  const r = rng(8);
  const src = E.seededSource(20261101);
  for (let t = 0; t < (QUICK ? 200 : 800); t++) {
    const c = randomInstance(r, 3, 12);
    c.noMutual = uni(r) < 0.2; c.oneLoop = uni(r) < 0.15;
    const d = E.draw(c, { source: src, deadlineMs: 3000 });
    if (!d.ok) continue;
    const p = d.perm, used = new Set(p);
    let good = used.size === c.n;
    p.forEach((x, g) => { if (!c.allow[g * c.n + x]) good = false; });
    if (c.noMutual && twoCycle(p)) good = false;
    if (c.oneLoop && !oneCycle(p)) good = false;
    ok(good, `G: draw broke a rule n=${c.n} case ${t}`);
  }
  // uniformity of each method on fixed instances, every valid draw tallied
  const tally = (cons, method, N, seed) => {
    const all = bruteDraws(cons.n, cons.allow, (p) => (!cons.noMutual || !twoCycle(p)) && (!cons.oneLoop || oneCycle(p)));
    const idx = new Map(all.map((p, i) => [p.join(','), i]));
    const counts = new Array(all.length).fill(0);
    const s = E.seededSource(seed);
    const table = method === 'table' ? E.countTable(cons) : null;
    for (let k = 0; k < N; k++) {
      let p;
      if (method === 'bound') { do { p = Array.from(E.boundSample(cons, s)); } while (!E.meetsOptions(cons, p)); }
      else { const d = E.draw(cons, { source: s, table, shuffleFirst: method === 'shuffle' ? 1e9 : undefined }); ok(d.method === method, `G: expected method ${method}, got ${d.method}`); p = d.perm; }
      counts[idx.get(p.join(','))]++;
    }
    return counts;
  };
  const N = QUICK ? 60000 : 200000;
  const fam = E.parsePeople('Ann & Ben\nCat & Dan\nEve\nFay');
  const famR = E.parseRules('Eve > Fay', fam.people);
  const famC = E.buildConstraints(fam.people, fam.houses, famR.rules, {});
  const famNo = E.buildConstraints(fam.people, fam.houses, famR.rules, { noMutual: true });
  const seven = E.parsePeople('A\nB\nC\nD\nE\nF\nG');
  const sevenC = E.buildConstraints(seven.people, seven.houses, [], {});
  for (const [label, cons, method, seed] of [
    ['family/table', famC, 'table', 11], ['family/shuffle', { ...famC, n: famC.n }, 'shuffle', 12], ['family/bound', famC, 'bound', 13],
    ['family no-swaps/table', famNo, 'table', 14], ['seven/bound', sevenC, 'bound', 15], ['seven/table', sevenC, 'table', 16],
  ]) {
    const z = chiZ(tally(label.includes('shuffle') ? { ...cons } : cons, method, method === 'bound' && label.startsWith('seven') ? N : N, seed));
    ok(Math.abs(z) < 4, `G: ${label} not uniform (z = ${z.toFixed(2)})`);
    console.log(`     ${label.padEnd(24)} chi-square z = ${z.toFixed(2)}`);
  }
  // NEGATIVE CONTROL: the hat method (greedy with restart) on the same family must FAIL the
  // same test at the same sample size, or the test is too weak to mean anything
  const all = bruteDraws(famC.n, famC.allow);
  const idx = new Map(all.map((p, i) => [p.join(','), i]));
  const counts = new Array(all.length).fill(0);
  const s = rng(17);
  for (let k = 0; k < N; k++) {
    for (;;) {
      const used = new Array(famC.n).fill(false), p = [];
      let dead = false;
      for (let g = 0; g < famC.n && !dead; g++) {
        const opts = []; for (let x = 0; x < famC.n; x++) if (!used[x] && famC.allow[g * famC.n + x]) opts.push(x);
        if (!opts.length) { dead = true; break; }
        const x = opts[Math.floor(uni(s) * opts.length)]; used[x] = true; p.push(x);
      }
      if (!dead) { counts[idx.get(p.join(','))]++; break; }
    }
  }
  const zHat = chiZ(counts);
  console.log(`     ${'family/hat (control)'.padEnd(24)} chi-square z = ${zHat.toFixed(2)}`);
  ok(zHat > 10, `G control: the hat method passed the uniformity test (z = ${zHat.toFixed(2)})`);
});

family('H. the bound sampler: every weight sum stays at or below 1 along real paths', () => {
  // Huber & Law's Lemma 3.2, checked where the sampler actually uses it
  const r = rng(555);
  const h = E.hlH;
  let checked = 0;
  for (let t = 0; t < (QUICK ? 300 : 1200); t++) {
    const c = randomInstance(r, 2, 9);
    const rows = Array.from({ length: c.n }, (_, i) => { let s = 0; for (let j = 0; j < c.n; j++) s += c.allow[i * c.n + j]; return s; });
    const assigned = new Array(c.n).fill(false);
    for (let j = 0; j < c.n; j++) {
      const cand = []; let Q = 1;
      for (let k = 0; k < c.n; k++) if (!assigned[k] && c.allow[k * c.n + j]) { cand.push(k); Q *= h(rows[k] - 1) / h(rows[k]); }
      const sum = cand.reduce((s, k) => s + Math.E * Q / h(rows[k] - 1), 0);
      ok(sum <= 1 + 1e-12, `H: weights sum to ${sum} at column ${j} case ${t}`);
      checked++;
      if (!cand.length) break;
      const pick = cand[Math.floor(uni(r) * cand.length)];
      assigned[pick] = true;
      for (const k of cand) if (k !== pick) rows[k] -= 1;
    }
  }
  ok(checked > 1000, 'H: too few columns checked');
  // control: expanding along a ROW instead (the wrong orientation) must exceed 1 on this
  // five-person family with two couples
  const fam = [[0,1,1,1,1],[1,0,0,1,1],[1,0,0,1,1],[1,1,1,0,0],[1,1,1,0,0]];
  const rs = fam.map((row) => row.reduce((a, b) => a + b, 0));
  let sumRow = 0;
  for (let j = 0; j < 5; j++) if (fam[0][j]) {
    let ratio = Math.E / h(rs[0]);
    for (let k = 1; k < 5; k++) if (fam[k][j]) ratio *= h(rs[k] - 1) / h(rs[k]);
    sumRow += ratio;
  }
  ok(sumRow > 1, `H control: the wrong orientation did not exceed 1 (${sumRow})`);
  ok(sumRow.toFixed(4) === '1.0099', `H: the method page says 1.0099, computed ${sumRow.toFixed(4)}`);
  console.log(`     wrong-orientation weights on the two-couple family sum to ${sumRow.toFixed(4)} (> 1, so it would be unfair)`);
});

family('I. reading names and rules', () => {
  const P = E.parsePeople('Ann & Ben\n  Cat, Dan  \n# a comment\nEve and Fay\nGus + Hal\nÉlodie');
  ok(P.people.length === 9 && P.houses.length === 5, 'I: households read');
  ok(P.errors.length === 0, 'I: no errors on good input');
  ok(E.parsePeople('Ann\nann').errors.length === 1, 'I: duplicate (case-folded) caught');
  ok(E.parsePeople('A<b').errors.length === 1, 'I: angle bracket refused');
  const R = E.parseRules("Ann > Cat\nBen <> Dan\nEve can't draw Fay\nGus cannot draw Hal\nAnn -> Élodie", P.people);
  ok(R.errors.length === 0 && R.rules.length === 5, 'I: rule forms read');
  ok(R.rules[1].both && !R.rules[0].both, 'I: one-way and both-ways told apart');
  ok(E.parseRules('Ann > Zed', P.people).errors.length === 1, 'I: unknown name caught');
  ok(E.parseRules('Ann likes Ben', P.people).errors.length === 1, 'I: unreadable rule caught');
  const cons = E.buildConstraints(P.people, P.houses, R.rules, {});
  ok(!cons.allow[0 * 9 + 1] && !cons.allow[1 * 9 + 0], 'I: household forbids both ways');
  ok(!cons.allow[0 * 9 + 2] && cons.allow[2 * 9 + 0], 'I: one-way rule is one way');
  const off = E.buildConstraints(P.people, P.houses, R.rules, { households: false });
  ok(off.allow[0 * 9 + 1] === 1, 'I: households can be switched off');
  // names as people really paste them (found by the accessibility and names review)
  ok(E.foldName('\u0130pek') === E.foldName('ipek') && E.foldName('Strau\u00DF') === E.foldName('STRAUSS') && E.foldName('I\u015F\u0131l') === E.foldName('I\u015EIL'), 'I: Turkish and German case folding');
  const inv = E.parsePeople('\u200EAnn\nBen\nCat');
  ok(inv.people[0].name === 'Ann' && E.parseRules('Ann > Ben', inv.people).errors.length === 0, 'I: an invisible mark from a chat app breaks a rule');
  ok(E.parsePeople('Ann\n\u200EAnn').errors.length === 1, 'I: a look-alike duplicate is accepted');
  ok(E.parsePeople('\u5F20\u4F1F\uFF0C\u738B\u82B3\n\u0645\u062D\u0645\u062F\u060C \u0641\u0627\u0637\u0645\u0629\nAnn').houses.length === 3, 'I: CJK and Arabic commas do not split a household');
  ok(E.parsePeople('Zo\u00EB\u{1F475}\u{1F3FD}'.repeat(1)).errors.length === 0 && E.parsePeople('A' + '\u{1F475}\u{1F3FD}'.repeat(30)).errors.length === 0, 'I: emoji counted as more than one character each');
  const iso = E.witnessSentence([{ name: 'A' }, { name: 'B' }, { name: 'C' }], { side: 'givers', group: [0, 1], options: [2] }, true);
  ok(iso.includes('\u2068A\u2069') && iso.includes('\u2068C\u2069'), 'I: names in the proof sentence are not isolated for right-to-left scripts');
  ok(E.parseSetupFragment('#names=100% Dan,Ben,Cat').people === '100% Dan\nBen\nCat', 'I: a raw % drops the hand-off');
  ok(E.parsePeople('Dan #2 & Eve\nFay\nGus').people.length === 4, 'I: a # inside a line drops a person');
  ok(E.foldName('O\u2019Brien') === E.foldName("O'Brien"), 'I: curly and straight apostrophes are different names');
  {
    const big = E.parsePeople(Array.from({ length: 11 }, (_, i) => 'P' + i).join('\n'));
    const t0 = Date.now(); const a = E.analyse(E.buildConstraints(big.people, big.houses, [], { oneLoop: true }));
    ok(Date.now() - t0 < 1000 && a.feasible === null, 'I: listing draws with an option on is not bounded in time');
  }
});

family('J. fixes: each suggested change really makes a draw possible, and no other single change does', () => {
  const cases = [
    ['Ann & Ben & Cat\nDan', ''],
    ['Ann & Ben\nCat & Dan\nEve', 'Eve > Ann\nEve > Ben\nEve > Cat\nEve > Dan'],
    ['Ann\nBen\nCat\nDan', 'Ann > Ben\nAnn > Cat\nAnn > Dan'],
    ['Ann & Ben\nCat\nDan', 'Cat <> Dan\nCat > Ann\nDan > Ann'],
    ['Ann & Ben & Cat & Dan\nEve\nFay', 'Eve <> Fay'],
  ];
  for (const [ppl, rl] of cases) {
    const P = E.parsePeople(ppl), R = E.parseRules(rl, P.people);
    const cons = E.buildConstraints(P.people, P.houses, R.rules, {});
    ok(!E.hasPerfect(cons.n, cons.allow), `J: case should be impossible: ${ppl}`);
    const f = E.fixes(cons);
    const listed = new Set(f.singles.map((u) => u.id));
    for (const u of cons.units.filter((x) => x.removable)) {
      const a = cons.allow.slice();
      for (const [i, j] of u.cells) if (cons.blockers[i * cons.n + j].every((b) => b === u.id)) a[i * cons.n + j] = 1;
      ok(E.hasPerfect(cons.n, a) === listed.has(u.id), `J: fix list wrong for "${u.label}"`);
    }
  }
});

family('J2. fixes: when pairs of changes are too many to try, the result says so', () => {
  // twenty people, many one-way rules, two separate shortfalls: no single change fixes it, and
  // there are too many pairs to try, so the flags must not claim the pairs were all checked
  const names = Array.from({ length: 20 }, (_, i) => 'P' + i);
  const P = E.parsePeople(names.join('\n'));
  const rules = [];
  // P0, P1, P2 may only draw P3; P4, P5, P6 may only draw P7
  for (const g of [0, 1, 2]) for (let k = 0; k < 20; k++) if (k !== g && k !== 3) rules.push(`P${g} > P${k}`);
  for (const g of [4, 5, 6]) for (let k = 0; k < 20; k++) if (k !== g && k !== 7) rules.push(`P${g} > P${k}`);
  const R = E.parseRules(rules.join('\n'), P.people);
  const cons = E.buildConstraints(P.people, P.houses, R.rules, {});
  ok(!E.hasPerfect(cons.n, cons.allow), 'J2: the planted case should be impossible');
  const f = E.fixes(cons, 50, 5000);
  ok(f.singlesComplete === true && f.singles.length === 0, 'J2: single changes were not all tried, or one was found');
  ok(f.pairsTried !== true, 'J2: pairs reported as all tried when there were too many');
});

family('K. links: a slip round-trips, carries no readable name, and differs every time', () => {
  const src = E.seededSource(9);
  const names = ['Ann', 'José María', 'Zoë', '李雷', 'O\'Brien', 'Anne-Marie 🎄'];
  for (const g of names) for (const r of names) {
    if (g === r) continue;
    const s = E.encodeSlip({ giver: g, recipient: r, draw: 'K7Q2X', title: 'Family', budget: '£20', date: 'Xmas Eve', note: 'Wrap it' }, src);
    const back = E.decodeSlip(s);
    ok(back.giver === g && back.recipient === r && back.budget === '£20' && back.draw === 'K7Q2X', `K: round trip ${g}->${r}`);
    const body = s.slice(3);
    ok(/^[A-Za-z0-9_-]+$/.test(body), 'K: slip is URL-safe');
    // the recipient's name must not be readable in the link, as text or as plain base64
    const plainB64 = Buffer.from(JSON.stringify(r)).toString('base64').replace(/=+$/, '').slice(2, 8);
    ok(!s.includes(r) && !s.includes(encodeURIComponent(r)) && !(plainB64.length >= 6 && s.includes(plainB64)), `K: name readable in link ${r}`);
  }
  // length must not leak the recipient: padded slips of one draw are all the same length,
  // whatever the recipients' names (the control: unpadded, they differ)
  const people = ['Al', 'Bartholomew-Fitzgerald', 'Zoë', '李雷', 'Anne-Marie 🎄', 'Bo'];
  const perm = [1, 2, 3, 4, 5, 0];
  const slipsOf = people.map((g, i) => ({ giver: 'Same', recipient: people[perm[i]], draw: 'K7Q2X', budget: '£20' }));
  const padTo = Math.max(...slipsOf.map(E.slipLength));
  const padded = slipsOf.map((sl) => E.encodeSlip(sl, src, padTo));
  ok(new Set(padded.map((x) => x.length)).size === 1, 'K: padded links of one draw differ in length');
  ok(padded.every((x, i) => E.decodeSlip(x).recipient === people[perm[i]]), 'K: a padded slip does not round-trip');
  const unpadded = slipsOf.map((sl) => E.encodeSlip(sl, src));
  ok(new Set(unpadded.map((x) => x.length)).size > 1, 'K control: unpadded links were already equal, so the test proves nothing');
  const appSrc = fs.readFileSync(path.join(ROOT, 'public/tools/secret-santa/app.mjs'), 'utf8');
  ok(/E\.encodeSlip\(sl, undefined, padTo\)/.test(appSrc) && /padTo = E\.padTarget\(dr\.names, \{ \.\.\.ev, round: 999999 \}, dr\.code, \[\.\.\.H\.hints\.values\(\)\]\)/.test(appSrc), 'K: the page does not pad its links to the input-only size');
  // the padded length must not depend on WHO DREW WHOM: the same setup, every possible draw,
  // one length (the reviewer's case: one long hint). Control: padding to the longest actual
  // slip, as the page first did, gives different lengths for different draws.
  {
    const names = ['Jo', 'Eddie', 'Christopher', 'Max'], hints = new Map([[0, 'loves anything to do with tea, especially the smoky kind, and a mug to go with it']]);
    const ev = { budget: '£20' }, code = 'K7Q2X';
    const P4 = E.parsePeople(names.join('\n'));
    const all = []; E.enumerate(E.buildConstraints(P4.people, P4.houses, [], {}), 1e6, (p) => all.push(Array.from(p)));
    const lensFixed = new Set(), lensMax = new Set();
    for (const perm of all) {
      const sl = names.map((g, i) => ({ giver: g, recipient: names[perm[i]], draw: code, ...ev, hint: hints.get(perm[i]) || '' }));
      const fixed = E.padTarget(names, ev, code, [...hints.values()]);
      sl.forEach((x) => lensFixed.add(E.encodeSlip(x, src, fixed).length));
      const mx = Math.max(...sl.map(E.slipLength));
      lensMax.add(E.encodeSlip(sl[0], src, mx).length);
    }
    ok(lensFixed.size === 1, `K: link length depends on the draw (${[...lensFixed].join(', ')})`);
    // and on how many draws were made: the counter is padded to a fixed width
    const t9 = E.padTarget(names, { ...ev, round: 999999 }, code, [...hints.values()]);
    const l1 = E.encodeSlip({ giver: 'Jo', recipient: 'Max', draw: code, ...ev, round: 1 }, src, t9).length;
    const l10 = E.encodeSlip({ giver: 'Jo', recipient: 'Max', draw: code, ...ev, round: 10 }, src, t9).length;
    ok(l1 === l10, `K: the first and tenth draws give links of different lengths (${l1}, ${l10})`);
    ok(lensMax.size > 1, 'K control: padding to the longest actual slip did not vary, so the test proves nothing');
  }
  const a = E.encodeSlip({ giver: 'Ann', recipient: 'Ben', draw: 'X' }, src), b = E.encodeSlip({ giver: 'Ann', recipient: 'Ben', draw: 'X' }, src);
  ok(a !== b, 'K: two links to the same pairing look alike');
  // a changed character is refused, not shown as a different name (the slip carries a checksum)
  {
    const sl = E.encodeSlip({ giver: 'Ann', recipient: 'Bartholomew', draw: 'K7Q2X' }, src), body = sl.slice(3);
    const al = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
    let garbled = 0, tried = 0;
    for (let i = 0; i < body.length; i++) for (const ch of al) {
      if (ch === body[i]) continue; tried++;
      try { const d = E.decodeSlip('s1.' + body.slice(0, i) + ch + body.slice(i + 1)); if (d.recipient !== 'Bartholomew' || d.giver !== 'Ann') garbled++; } catch {}
    }
    ok(garbled === 0 && tried > 1000, `K: ${garbled} of ${tried} one-character edits showed a different name`);
  }
  // chat apps glue punctuation or tracking parameters onto the end of a link; the slip still reads
  {
    const sl = E.encodeSlip({ giver: 'Ann', recipient: 'Zo\u00EB', draw: 'K7Q2X' }, src);
    ok(/^s2\.[0-9A-Za-z]+$/.test(sl), 'K: a slip uses characters outside base 62');
    ok(['.', ')', ',', '&fbclid=IwAR0abc', '?utm_source=x', '%20'].every((t) => E.decodeSlip(sl + t).recipient === 'Zo\u00EB'), 'K: trailing junk from a chat app breaks a good link');
  }
  let threw = false; try { E.decodeSlip('s1.' + 'A'.repeat(10)); } catch { threw = true; }
  ok(threw, 'K control: a truncated slip decoded');
  threw = false; try { E.decodeSlip(a.slice(0, a.length - 6)); } catch { threw = true; }
  ok(threw, 'K control: a cut-off slip decoded');
  // the hand-off fragment
  const setup = { people: 'Ann & Ben\nCat\nDan & Eve', rules: 'Cat > Dan\nAnn <> Eve', title: 'Office party', budget: '$30', date: 'Dec 19', note: '', noMutual: true, oneLoop: false, households: true };
  const back = E.parseSetupFragment(E.setupFragment(setup));
  ok(back.people === setup.people && back.rules === setup.rules && back.title === setup.title && back.budget === '$30' && back.noMutual === true, 'K: setup fragment round trip');
  ok(E.parseSetupFragment('#foo=bar') === null, 'K: a fragment without names is ignored');
});

family('L. privacy, read from the files the page serves', () => {
  const dir = path.join(ROOT, 'public/tools/secret-santa');
  const app = fs.readFileSync(path.join(dir, 'app.mjs'), 'utf8');
  const eng = fs.readFileSync(path.join(dir, 'engine.mjs'), 'utf8');
  const html = fs.readFileSync(path.join(dir, 'index.html'), 'utf8');
  const code = (s) => s.replace(/\/\/[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '');
  for (const [name, src] of [['app.mjs', app], ['engine.mjs', eng]]) {
    for (const api of ['fetch(', 'XMLHttpRequest', 'sendBeacon', 'WebSocket', 'EventSource', 'importScripts']) ok(!code(src).includes(api), `L: ${name} uses ${api}`);
  }
  // the hash is read and wiped by the first script in <head>, before anything else can run
  const head = html.slice(0, html.indexOf('</head>'));
  const firstScript = head.indexOf('<script');
  ok(firstScript >= 0 && head.indexOf('replaceState', firstScript) > firstScript && head.indexOf('</script>', firstScript) > head.indexOf('replaceState', firstScript), 'L: first script does not strip the hash');
  ok(head.indexOf('<script') === firstScript && !/<script[^>]*src=/.test(head.slice(0, head.indexOf('</script>', firstScript))), 'L: an external script precedes the hash strip');
  const csp = (html.match(/http-equiv="Content-Security-Policy" content="([^"]+)"/) || [])[1] || '';
  ok(/connect-src 'self'/.test(csp) && /default-src 'self'/.test(csp) && /form-action 'self'/.test(csp), 'L: CSP missing or loose');
  ok(!/https?:\/\/(?!artwaste\.land)[a-z]/i.test(code(app)), 'L: app.mjs names another site');
  ok(/name="referrer" content="no-referrer"/.test(html), 'L: no-referrer meta missing');
  // the gift hint belongs to the recipient, so it stays hidden until "Show me", like the name
  ok(!/\['Their hint'/.test(app) && /\$\('rv-hint'\)\.hidden = false/.test(app) && /id="rv-hint" hidden/.test(html), 'L: the gift hint shows before Show me');
  // a person's link never flashes the organiser's form, and a second link in the same tab is re-read
  ok(/replaceState\(slip \? \{ ssSlip: slip \}/.test(head) && /hashchange/.test(head) && /\.ss-reveal #organiser\{display:none/.test(html) && !/sessionStorage\.setItem/.test(code(app)), 'L: the reveal is not bound to its own history entry');
  ok(E.parsePeople('Aisha\tKate\tUma\nBen\tLiam\tVik').errors.length === 2, 'L: spreadsheet columns merge into one person');
  // control: the same detector, pointed at a planted call, must fire
  ok(code('const x = 1;\nfetch("/api")').includes('fetch('), 'L control: the network-call detector is blind');
  ok(!code('// fetch( only in a comment').includes('fetch('), 'L control: comments are not stripped');
});

family('M. the bias study: the hat figures re-derived by simulation', () => {
  // bias.mjs computes the hat method's exact probabilities by algebra; simulate the hat
  // literally (slips, put your own back, start over when stuck) and compare
  const G = group(['Ann', 'Ben', 'Cat', 'Dan']);
  const s = study(G);
  ok(s.valid === 9, 'M: four people have 9 valid draws');
  const draws = bruteDraws(4, Uint8Array.from(G.allow.flat().map(Number)));
  const exact = methodHat(G, draws).P.map((q) => q.toNumber());
  const r = rng(2026), N = QUICK ? 200000 : 600000;
  const counts = new Array(draws.length).fill(0);
  const idx = new Map(draws.map((p, i) => [p.join(','), i]));
  let restarts = 0, runs = 0;
  for (let k = 0; k < N; k++) {
    for (;;) {
      runs++;
      const hat = [0, 1, 2, 3], p = [];
      let stuck = false;
      for (let g = 0; g < 4; g++) {
        if (hat.every((x) => x === g)) { stuck = true; break; }
        let x;
        do { x = hat[Math.floor(uni(r) * hat.length)]; } while (x === g); // own name goes back in
        hat.splice(hat.indexOf(x), 1); p.push(x);
      }
      if (!stuck) { counts[idx.get(p.join(','))]++; break; }
      restarts++;
    }
  }
  let worst = 0;
  counts.forEach((c, i) => { worst = Math.max(worst, Math.abs(c / N - exact[i]) / Math.sqrt(exact[i] * (1 - exact[i]) / N)); });
  ok(worst < 4.5, `M: simulated hat disagrees with the exact figures (worst ${worst.toFixed(2)} standard errors)`);
  // control: the same simulation must be able to tell the hat from a fair draw
  let worstFair = 0;
  counts.forEach((c) => { const f = 1 / draws.length; worstFair = Math.max(worstFair, Math.abs(c / N - f) / Math.sqrt(f * (1 - f) / N)); });
  ok(worstFair > 20, `M control: the simulation cannot tell the hat from fair (${worstFair.toFixed(1)} SE)`);
  const restartExact = s.methods.hat.restartChanceApprox;
  const restartSim = restarts / runs;
  ok(Math.abs(restartSim - restartExact) < 0.004, `M: restart chance ${restartSim} vs exact ${restartExact}`);
  console.log(`     hat, four people: worst draw within ${worst.toFixed(2)} SE of the exact figure; restart ${(restartSim * 100).toFixed(2)}% simulated vs ${(restartExact * 100).toFixed(2)}% exact`);
  // and the same literal hat for every group in the method page's tables, rules and restarts
  // included: pairing frequencies and the restart rate against the exact fractions
  {
    const NS = QUICK ? 30000 : 120000;
    let worstAll = 0, restartWorst = 0;
    for (const c of CASES) {
      const Gc = group(c.lines, c.rules);
      const drawsC = bruteDraws(Gc.n, Uint8Array.from(Gc.allow.flat().map(Number)));
      const Pc = methodHat(Gc, drawsC);
      const exactPair = Array.from({ length: Gc.n }, () => new Array(Gc.n).fill(0));
      drawsC.forEach((d, i) => d.forEach((x, g) => { exactPair[g][x] += Pc.P[i].toNumber(); }));
      const tally = Array.from({ length: Gc.n }, () => new Array(Gc.n).fill(0));
      const rr = rng(4000 + c.id.length);
      let restarts = 0, runs = 0;
      for (let k = 0; k < NS; k++) {
        for (;;) {
          runs++;
          const hat = Array.from({ length: Gc.n }, (_, i) => i), p = [];
          let stuck = false;
          for (let g = 0; g < Gc.n && !stuck; g++) {
            if (!hat.some((x) => Gc.allow[g][x])) { stuck = true; break; }
            let x;
            do { x = hat[Math.floor(uni(rr) * hat.length)]; } while (!Gc.allow[g][x]); // not allowed: back in the hat
            hat.splice(hat.indexOf(x), 1); p.push(x);
          }
          if (!stuck) { p.forEach((x, g) => tally[g][x]++); break; }
          restarts++;
        }
      }
      for (let g = 0; g < Gc.n; g++) for (let x = 0; x < Gc.n; x++) {
        const e = exactPair[g][x]; if (e <= 0 || e >= 1) continue;
        worstAll = Math.max(worstAll, Math.abs(tally[g][x] / NS - e) / Math.sqrt(e * (1 - e) / NS));
      }
      const re = 1 - Pc.success.toNumber(), rs = restarts / runs;
      restartWorst = Math.max(restartWorst, Math.abs(rs - re) / Math.sqrt(re * (1 - re) / runs));
    }
    ok(worstAll < 5.5 && restartWorst < 5, `M: the literal hat disagrees with the exact tables (pairings ${worstAll.toFixed(2)} SE, restarts ${restartWorst.toFixed(2)} SE)`);
    console.log(`     literal hat, all ${CASES.length} table groups: worst pairing ${worstAll.toFixed(2)} SE, worst restart rate ${restartWorst.toFixed(2)} SE from exact`);
  }
  // OEIS A102262 (Grossman, 2005): the chance the last person is left with only their own name
  {
    const A102262 = ['1/4', '5/36', '19/144', '203/1800', '4343/43200', '63853/705600'];
    const mine = [3, 4, 5, 6, 7, 8].map((n) => { const Gn = group(Array.from({ length: n }, (_, i) => 'P' + i)); const s1 = methodHat(Gn, bruteDraws(n, Uint8Array.from(Gn.allow.flat().map(Number)))).success; return new Q(s1.d - s1.n, s1.d).toString(); });
    ok(JSON.stringify(mine) === JSON.stringify(A102262), `M: the hat's stuck chances ${mine.join(', ')} differ from OEIS A102262`);
    const kept = fs.readFileSync(path.join(HERE, 'sources/oeis-A102262.txt'), 'utf8');
    ok(A102262.every((f) => kept.includes(f)), 'M: the kept copy of A102262 does not list these values');
  }
  // the committed bias.json must be what the script computes now
  const committed = JSON.parse(fs.readFileSync(path.join(HERE, 'bias.json'), 'utf8'));
  const now = CASES.map((c) => ({ id: c.id, label: c.label, rules: c.rules || [], ...study(group(c.lines, c.rules)) }));
  ok(JSON.stringify(committed.results) === JSON.stringify(now), 'M: bias.json is stale; rerun node research/secret-santa/bias.mjs --json');
  // the small-group secrecy table: brute force in bias.mjs, cross-checked against the
  // page's own engine (analyse() runs guessYourSanta or the listing, as the page does)
  const small = smallGroups();
  ok(JSON.stringify(committed.smallGroups) === JSON.stringify(small), 'M: bias.json smallGroups stale');
  for (const [i, g] of SMALL.entries()) {
    const P = E.parsePeople(g.lines.join('\n'));
    const a = E.analyse(E.buildConstraints(P.people, P.houses, [], { noMutual: !!g.noSwaps }));
    const worst = Math.max(...a.guess.map((x) => x.guess));
    ok(Math.abs(worst - small[i].guessMaxApprox) < 1e-9 && Number(a.count) === small[i].valid, `M: engine and brute force disagree on "${g.label}" (${worst} vs ${small[i].guessMaxApprox})`);
  }
  // the Possibly Wrong figure the pages quote, recomputed exactly (control: n = 8 differs)
  const ldr = lastDrawerRatio(9);
  ok(ldr.ratio === '88340/45333' && ldr.ratioApprox.toFixed(5) === '1.94869' && JSON.stringify(committed.lastDrawerRatio) === JSON.stringify(ldr), `M: last-drawer ratio at nine is ${ldr.ratio}`);
  ok(lastDrawerRatio(8).ratioApprox.toFixed(5) !== '1.94869', 'M control: the ratio does not depend on n');
  // the n - 1 law, as computed (not assumed) for n = 3..9
  const ratios = hatRatios();
  ok(ratios.every((x) => x.maxOverMin === String(x.n - 1)), 'M: the hat max/min ratio is not n - 1');
  ok(JSON.stringify(committed.hatRatios) === JSON.stringify(ratios), 'M: bias.json hatRatios stale');
  // and the three-person case by hand: draws A->B->C->A and A->C->B->A come out 1/3 and 2/3
  const G3 = group(['A', 'B', 'C']);
  const d3 = bruteDraws(3, Uint8Array.from(G3.allow.flat().map(Number)));
  const p3 = methodHat(G3, d3).P.map(String).sort();
  ok(JSON.stringify(p3) === JSON.stringify(['1/3', '2/3']), `M: three-person hat is ${p3}`);
});

console.log('     N. the method page shows the computed figures, and a hand edit is caught');
{
  const page = fs.readFileSync(path.join(ROOT, 'public/tools/secret-santa/method/index.html'), 'utf8');
  const before = fail;
  ok(render(page) === page, 'N: method page tables are stale (node research/secret-santa/build-method.mjs)');
  const planted = page.replace('<td>4</td><td>9</td><td>3&times;</td>', '<td>4</td><td>9</td><td>2&times;</td>');
  ok(planted !== page, 'N control: could not plant an edit (the four-person row moved?)');
  ok(render(planted) !== planted, 'N control: a hand-edited figure survived');
  // and the claims in the page's prose that are numbers, read from the page itself
  ok(page.includes('come out <strong>2/3 and 1/3</strong>'), 'N: the three-person hand calculation is missing');
  const fam = JSON.parse(fs.readFileSync(path.join(HERE, 'bias.json'), 'utf8')).results.find((r) => r.id === 'family');
  ok(fam.methods.hat.mostLikelyTimesFair / fam.methods.hat.leastLikelyTimesFair > 14.999 && fam.methods.hat.mostLikelyTimesFair / fam.methods.hat.leastLikelyTimesFair < 15.001 && page.includes('fifteen times as likely as its least likely'), 'N: the "fifteen times" sentence does not match the family case');
  ok(page.includes('add up to 1.0099'), 'N: the wrong-orientation figure is missing from the page');
  // the prose under the small-groups table says what the table shows
  const sg = Object.fromEntries(JSON.parse(fs.readFileSync(path.join(HERE, 'bias.json'), 'utf8')).smallGroups.map((g) => [g.id, g]));
  ok(sg.three.everyoneKnows && page.includes('Three people can never keep the secret'), 'N: the three-people sentence does not match the table');
  ok(Math.abs(sg.four.guessMaxApprox - sg.four.blindForWorstApprox) < 1e-12 && page.includes('your slip tells you nothing about your Santa beyond a blind guess'), 'N: the four-people sentence does not match the table');
  ok(sg['two-couples'].learnsAnotherMaxApprox === 1 && Math.abs(sg['two-couples'].guessMaxApprox - sg['two-couples'].blindForWorstApprox) < 1e-12 && page.includes('it always tells you who your partner is buying for'), 'N: the two-couples sentence does not match the table');
  const tool = fs.readFileSync(path.join(ROOT, 'public/tools/secret-santa/index.html'), 'utf8');
  ok(tool.includes('With four people your slip tells you nothing about who your Santa is') && tool.includes('will each know who their partner is buying for'), 'N: the tool page FAQ does not match the table');
  console.log(`${fail === before ? 'ok  ' : 'FAIL'} N. (checked)`);
}

console.log(`\n${pass} checks passed, ${fail} failed.`);
if (fail) { console.log(`First failures:\n  ${failures.slice(0, 10).join('\n  ')}`); process.exit(1); }
