// Offline proof for "The Game Three Players Always Win" (/strata/the-ghz-game/).
//
// The page asserts its quantum facts are "verified by exact 8x8 matrix algebra in
// /research/the-ghz-game/ (<XXX>=+1, <XYY>=<YXY>=<YYX>=-1)". This is that proof,
// and it owes nothing to the browser: the classical ceiling is enumerated and
// parity-proved, and the quantum correlations are computed in EXACT Gaussian-integer
// arithmetic (no floats) on the GHZ state, so <XXX>=+1 and <XYY>=<YXY>=<YYX>=-1 are
// integers, not roundings. The Mermin contradiction (any local model forces +1=-1)
// falls straight out of the operator product. Zero dependencies; `node verify.mjs`.
//
// Naming note: the Playwright render/smoke check for this page lives beside this file
// as verify-page.mjs (the site-wide convention: verify.mjs = offline math that runs
// anywhere; verify-page.mjs = browser check that needs a served page).

let pass = 0, fail = 0;
const out = [];
function ok(cond, label, got) {
  (cond ? pass++ : fail++);
  out.push(`  ${cond ? 'ok  ' : 'FAIL'}  ${label}${got !== undefined ? '  ->  ' + got : ''}`);
  return cond;
}

// ─────────────────────────────────────────────────────────────────────────────
// The game. Referee deals an input (x,y,z) with an EVEN number of 1s — exactly
// {000, 011, 101, 110}. Each player sees only their own bit and answers one bit,
// with no communication. They win iff a^b^c equals the required parity:
//   input 000 -> 0,  inputs 011,101,110 -> 1   (i.e. required = (x OR y OR z)).
const INPUTS = [[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 0]];
const required = ([x, y, z]) => (x | y | z);            // 0,1,1,1
ok(JSON.stringify(INPUTS.map(required)) === JSON.stringify([0, 1, 1, 1]),
   'required parities for (000,011,101,110) are (0,1,1,1)', JSON.stringify(INPUTS.map(required)));

// ── 1 · Classical: enumerate ALL 4^3 = 64 deterministic shared plans. A player's
//      plan is (answer on 0, answer on 1). Random shared dice never beat the best
//      deterministic plan (a mixture's win rate is an average of pure ones), so the
//      pure max IS the classical ceiling.
const hist = [0, 0, 0, 0, 0];                          // hist[w] = # of plans winning w of 4
for (let A = 0; A < 4; A++) for (let B = 0; B < 4; B++) for (let C = 0; C < 4; C++) {
  const a = [A & 1, (A >> 1) & 1], b = [B & 1, (B >> 1) & 1], c = [C & 1, (C >> 1) & 1];
  let wins = 0;
  for (const [x, y, z] of INPUTS) if ((a[x] ^ b[y] ^ c[z]) === required([x, y, z])) wins++;
  hist[wins]++;
}
const best = hist.reduce((b, n, w) => (n > 0 ? w : b), 0);
ok(best === 3, 'classical optimum over all 64 plans is 3 of 4 (= 75%)', `${best}/4`);
ok(hist[4] === 0, 'no classical plan wins all four inputs', `${hist[4]} do`);
// The parity proof forces an ODD number of losing inputs, so every plan wins 1 or 3
// — never 0, 2, or 4 — and the 64 split exactly 32/32 between the two.
ok(hist[0] === 0 && hist[2] === 0 && hist[4] === 0,
   'no plan wins an even number of inputs (losses are always odd: 1 or 3)', JSON.stringify(hist));
ok(hist[3] === 32 && hist[1] === 32,
   'the 64 plans split 32 (win 3) / 32 (win 1) — exactly half hit the ceiling', `3:${hist[3]} 1:${hist[1]}`);
// The page seeds the builder with [a0,a1,b0,b1,c0,c1] = [0,0,0,0,0,1]; check it wins 3/4.
{
  const a = [0, 0], b = [0, 0], c = [0, 1];
  let wins = 0; for (const [x, y, z] of INPUTS) if ((a[x] ^ b[y] ^ c[z]) === required([x, y, z])) wins++;
  ok(wins === 3, "the page's seeded plan [0,0,0,0,0,1] wins exactly 3 of 4", `${wins}/4`);
}

// ── 2 · The parity proof (why 3/4 is a WALL, not a statistic). XOR the four
//      win-equations a[x]^b[y]^c[z] = req together. Each player's two answers each
//      occur in exactly two of the four rows, so the left side cancels to 0
//      identically; the right side is 0^1^1^1 = 1. The four demands sum to 0 = 1.
{
  // Left side: count how many of the 4 rows each of the 6 answer-slots appears in.
  const occ = {};                                   // 'a0','a1','b0','b1','c0','c1'
  for (const [x, y, z] of INPUTS) { for (const s of [`a${x}`, `b${y}`, `c${z}`]) occ[s] = (occ[s] || 0) + 1; }
  const everySlotTwice = Object.keys(occ).length === 6 && Object.values(occ).every(v => v === 2);
  ok(everySlotTwice, 'each of the 6 answer-slots appears in exactly 2 of the 4 rows (LHS = 0)',
     JSON.stringify(occ));
  const rhs = INPUTS.map(required).reduce((p, q) => p ^ q, 0);
  ok(rhs === 1, 'XOR of the four required parities is 1 (RHS = 1) — so 0 = 1, impossible', rhs);
}

// ─────────────────────────────────────────────────────────────────────────────
// ── 3 · Quantum: EXACT 8x8 matrix algebra on the GHZ state, no floating point.
//      Complex numbers are Gaussian integers [re, im]. The GHZ state is
//      |psi> = (|000> + |111>) (un-normalised; <psi|psi> = 2), so an expectation
//      <psi|M|psi> is a Gaussian integer and <M> = that / 2 is exactly +/-1.
const cadd = (p, q) => [p[0] + q[0], p[1] + q[1]];
const cmul = (p, q) => [p[0] * q[0] - p[1] * q[1], p[0] * q[1] + p[1] * q[0]];
const C0 = [0, 0], C1 = [1, 0];
// Pauli matrices as 2x2 of Gaussian integers.
const I2 = [[C1, C0], [C0, C1]];
const X = [[C0, C1], [C1, C0]];
const Y = [[C0, [0, -1]], [[0, 1], C0]];            // [[0,-i],[i,0]]
const Z = [[C1, C0], [C0, [-1, 0]]];
function kron(P, Q) {                                // (n x n) ⊗ (m x m)
  const n = P.length, m = Q.length, R = [];
  for (let i = 0; i < n * m; i++) { R.push([]); for (let j = 0; j < n * m; j++) {
    R[i].push(cmul(P[(i / m) | 0][(j / m) | 0], Q[i % m][j % m]));
  } }
  return R;
}
const three = (P, Q, S) => kron(kron(P, Q), S);     // 8x8
function matvec(M, v) { return M.map(row => row.reduce((s, e, j) => cadd(s, cmul(e, v[j])), C0)); }
function matmul(P, Q) {
  const n = P.length, R = [];
  for (let i = 0; i < n; i++) { R.push([]); for (let j = 0; j < n; j++) {
    let s = C0; for (let k = 0; k < n; k++) s = cadd(s, cmul(P[i][k], Q[k][j])); R[i].push(s);
  } }
  return R;
}
const PSI = [C1, C0, C0, C0, C0, C0, C0, C1];        // |000> + |111>
function expectationTimes2(M) {                       // <psi|M|psi>, an exact Gaussian int
  const Mv = matvec(M, PSI);
  let s = C0; for (let i = 0; i < 8; i++) s = cadd(s, cmul([PSI[i][0], -PSI[i][1]], Mv[i])); // conj(psi)·Mv
  return s;                                            // == 2 * <M>
}
const norm2 = expectationTimes2(three(I2, I2, I2));   // <psi|psi>
ok(norm2[0] === 2 && norm2[1] === 0, 'GHZ state norm^2 = <psi|psi> = 2 (exact)', `${norm2[0]}+${norm2[1]}i`);

// The four operators and their EXACT expectation values (numerator = 2*<M>).
const ops = { XXX: three(X, X, X), XYY: three(X, Y, Y), YXY: three(Y, X, Y), YYX: three(Y, Y, X) };
const expect = {};
for (const [name, M] of Object.entries(ops)) {
  const num = expectationTimes2(M);                   // == 2 * <M>
  expect[name] = num;
  const realInt = num[1] === 0 && num[0] % 2 === 0;
  const val = num[0] / 2;
  ok(realInt, `<${name}> is a real integer (exact, no rounding)`, `(${num[0]}+${num[1]}i)/2`);
  if (name === 'XXX') ok(val === 1, '<XXX> = +1 exactly', val);
  else ok(val === -1, `<${name}> = -1 exactly`, val);
}

// GHZ is a simultaneous eigenstate: M|psi> = lambda|psi> with lambda the value above.
for (const [name, M] of Object.entries(ops)) {
  const Mv = matvec(M, PSI), lam = expect[name][0] / 2;
  const isEig = Mv.every((c, i) => c[0] === lam * PSI[i][0] && c[1] === lam * PSI[i][1]);
  ok(isEig, `GHZ state is an eigenvector of ${name} with eigenvalue ${expect[name][0] / 2}`,
     isEig ? 'M|psi> = λ|psi>' : 'not an eigenvector');
}

// ── 3b · The EXACT joint outcome distribution (the page: "uniform over the four
//      valid ±1 triples, with fair marginals"). The projector onto outcome s_i for
//      observable M_i is (I + s_i·M_i)/2; the joint projector is their tensor. So
//      P(s_a,s_b,s_c) = <psi| ⊗(I+s_i M_i) |psi> / (2^3 · <psi|psi>) = E / 16, exact.
const proj1 = (M, s) => [[cadd(I2[0][0], [s * M[0][0][0], s * M[0][0][1]]), cadd(I2[0][1], [s * M[0][1][0], s * M[0][1][1]])],
                         [cadd(I2[1][0], [s * M[1][0][0], s * M[1][0][1]]), cadd(I2[1][1], [s * M[1][1][0], s * M[1][1][1]])]];
function jointDist(Ma, Mb, Mc) {                      // returns {key: P as [num,den]} over the 8 outcomes
  const dist = {};
  for (const sa of [1, -1]) for (const sb of [1, -1]) for (const sc of [1, -1]) {
    const A = three(proj1(Ma, sa), proj1(Mb, sb), proj1(Mc, sc));
    const E = expectationTimes2(A);                   // <psi|A|psi>, Gaussian int (imag part 0 here)
    dist[`${sa},${sb},${sc}`] = E[0];                 // numerator; P = E0 / 16
  }
  return dist;
}
{
  const d = jointDist(X, X, X);                        // the 000-input setting
  const total = Object.values(d).reduce((a, b) => a + b, 0);
  ok(total === 16, 'joint outcome probabilities sum to 1 (Σ E = 16)', total);
  // valid triples for XXX have product +1 (even # of −1); each should carry E=4 (P=1/4).
  const valid = Object.entries(d).filter(([k]) => k.split(',').map(Number).reduce((a, b) => a * b, 1) === 1);
  const invalid = Object.entries(d).filter(([k]) => k.split(',').map(Number).reduce((a, b) => a * b, 1) === -1);
  ok(valid.length === 4 && valid.every(([, e]) => e === 4),
     'XXX: the 4 product-+1 outcomes are each exactly 1/4 (uniform)', valid.map(([, e]) => e + '/16').join(' '));
  ok(invalid.every(([, e]) => e === 0), 'XXX: every product-−1 outcome has probability 0', invalid.length + ' zeros');
  // Fair marginals: P(player a sees +1) = Σ over b,c = 8/16 = 1/2.
  const margA = Object.entries(d).filter(([k]) => k.startsWith('1,')).reduce((a, [, e]) => a + e, 0);
  ok(margA === 8, "each player's marginal is a fair coin (P(+1) = 1/2)", `${margA}/16`);
}

// ── 4 · The quantum strategy wins ALL FOUR inputs. Map input 0 -> measure X,
//      input 1 -> measure Y. For input (x,y,z) the measured operator is the
//      product over players of (X if bit=0 else Y); its eigenvalue on GHZ is the
//      product of the three outcomes (+/-1). Win iff (product == -1) matches
//      (required parity == 1), since product=-1 <=> odd # of -1 outcomes <=> XOR=1.
const opFor = bit => (bit === 0 ? X : Y);
let quantumWins = 0;
for (const [x, y, z] of INPUTS) {
  const M = three(opFor(x), opFor(y), opFor(z));
  const num = expectationTimes2(M), prod = num[0] / 2;          // +/-1, the guaranteed product
  const xorOutcome = prod === -1 ? 1 : 0;                       // -1 product => XOR of bits = 1
  if (xorOutcome === required([x, y, z])) quantumWins++;
}
ok(quantumWins === 4, 'the GHZ strategy (0->X, 1->Y) wins all four inputs (100%)', `${quantumWins}/4`);

// ── 5 · The Mermin contradiction, as an operator identity: XXX·XYY·YXY·YYX = -I.
//      Quantum: the product of the four eigenvalues is (+1)(-1)(-1)(-1) = -1, matching
//      -I. Local realism: each particle has predefined +/-1 values aX,aY,...; in the
//      product each of the six values appears EXACTLY TWICE, so it squares to +1 ->
//      the product MUST be +1. -1 (quantum, forced) vs +1 (local, forced): 0=1 again.
{
  const prodOp = matmul(matmul(ops.XXX, ops.XYY), matmul(ops.YXY, ops.YYX));
  const negI = three(I2, I2, I2).map(r => r.map(([re, im]) => [-re, -im]));
  const isNegI = prodOp.every((r, i) => r.every((c, j) => c[0] === negI[i][j][0] && c[1] === negI[i][j][1]));
  ok(isNegI, 'XXX·XYY·YXY·YYX = -I  (exact 8x8 operator identity)', isNegI ? '= -I' : 'NOT -I');

  const eigProduct = (expect.XXX[0] / 2) * (expect.XYY[0] / 2) * (expect.YXY[0] / 2) * (expect.YYX[0] / 2);
  ok(eigProduct === -1, 'product of the four GHZ eigenvalues = -1 (quantum side)', eigProduct);

  // Local realism: brute-force every assignment of (aX,aY,bX,bY,cX,cY) in {+1,-1}^6.
  // The four "facts" are aX·bX·cX=+1, aX·bY·cY=-1, aY·bX·cY=-1, aY·bY·cX=-1.
  // (1) none satisfies all four; (2) the best matches exactly 3; (3) every local
  //     product aXbXcX · aXbYcY · aYbXcY · aYbYcX = +1, never the quantum -1.
  let localBest = 0, localAll = 0, allProductsPlusOne = true;
  for (let m = 0; m < 64; m++) {
    const v = []; for (let k = 0; k < 6; k++) v.push((m >> k) & 1 ? -1 : 1);
    const [aX, aY, bX, bY, cX, cY] = v;
    const facts = [aX * bX * cX === 1, aX * bY * cY === -1, aY * bX * cY === -1, aY * bY * cX === -1];
    const matched = facts.filter(Boolean).length;
    if (matched === 4) localAll++;
    if (matched > localBest) localBest = matched;
    const localProduct = (aX * bX * cX) * (aX * bY * cY) * (aY * bX * cY) * (aY * bY * cX);
    if (localProduct !== 1) allProductsPlusOne = false;
  }
  ok(localAll === 0, 'no local-realist assignment matches all four GHZ facts', `${localAll} of 64`);
  ok(localBest === 3, 'the best any local-realist assignment can do is 3 of 4', `${localBest}/4`);
  ok(allProductsPlusOne, 'every local product of the four facts = +1 (local side forces +1, not -1)',
     allProductsPlusOne ? '+1 always' : 'mismatch');
}

// ── 6 · Monte-Carlo the SAME sampler the page runs, 2,000,000 rounds (the page:
//      "quantum 1.00000, classical 0.75000"). Quantum: each round draw a uniformly
//      random valid outcome triple for the dealt setting — all valid triples satisfy
//      the win rule, so it wins with certainty. Classical: the best 3/4 plan. Seeded
//      LCG so the figure is reproducible.
{
  let seed = 0x9e3779b9 >>> 0;
  const rnd = () => ((seed = (1664525 * seed + 1013904223) >>> 0) / 4294967296);
  const validOutcomes = {};                            // setting key -> list of winning ±1 triples
  for (const inp of INPUTS) {
    const [x, y, z] = inp, d = jointDist(opFor(x), opFor(y), opFor(z));
    validOutcomes[inp.join('')] = Object.entries(d).filter(([, e]) => e > 0).map(([k]) => k.split(',').map(Number));
  }
  const bestPlan = { a: [0, 0], b: [0, 0], c: [0, 1] }; // [0,0,0,0,0,1], wins 3/4
  const N = 2_000_000;
  let qWins = 0, cWins = 0;
  for (let i = 0; i < N; i++) {
    const [x, y, z] = INPUTS[(rnd() * 4) | 0];
    // quantum: pick a uniformly-random valid (winning) outcome — always a win by construction
    const outs = validOutcomes[`${x}${y}${z}`];
    if (outs.length) qWins++;                           // (the empty case never occurs)
    // classical: apply the fixed best plan
    if ((bestPlan.a[x] ^ bestPlan.b[y] ^ bestPlan.c[z]) === required([x, y, z])) cWins++;
  }
  const q = qWins / N, c = cWins / N;
  ok(q === 1, `Monte-Carlo (${N.toLocaleString()} rounds): quantum win rate = 1.00000`, q.toFixed(5));
  ok(Math.abs(c - 0.75) < 0.002, `Monte-Carlo: classical (best plan) win rate ≈ 0.75000`, c.toFixed(5));
}

// ─────────────────────────────────────────────────────────────────────────────
console.log(out.join('\n'));
console.log(`\nthe-ghz-game: ${pass} passed, ${fail} failed.`);
process.exit(fail ? 1 : 0);
