// verify.mjs — the proof, run offline. Every claim the stratum makes is decided
// here by exact integer arithmetic.  node research/sicherman-dice/verify.mjs
import {
  pmul, peq, pAt1, facesToPoly, polyToFaces, searchPairs,
  STANDARD, SICH_A, SICH_B, X, PHI2, PHI3, PHI6, trim,
} from './engine.mjs';
import { writeFileSync } from 'fs';

let fails = 0;
const ok = (name, cond, extra = '') => { if (!cond) fails++; console.log(`${cond ? '  ok' : 'FAIL'}  ${name}${extra ? '   ' + extra : ''}`); };
const dist = (fa, fb) => pmul(facesToPoly(fa), facesToPoly(fb));

console.log('\n— The target: two standard dice —');
const target = dist(STANDARD, STANDARD);
// sums run 2..12; coefficients are the famous triangle 1,2,3,4,5,6,5,4,3,2,1.
const triangle = [0, 0, 1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1];
ok('standard pair sum-distribution is the 1..6..1 triangle', peq(target, triangle), JSON.stringify(target.slice(2)));
ok('there are 36 equally likely outcomes', pAt1(target) === 36);

console.log('\n— Claim 1: the Sicherman pair rolls the SAME sums —');
const sich = dist(SICH_A, SICH_B);
ok('Sicherman faces are {1,2,2,3,3,4} and {1,3,4,5,6,8}',
   JSON.stringify(SICH_A) === '[1,2,2,3,3,4]' && JSON.stringify(SICH_B) === '[1,3,4,5,6,8]');
ok('Sicherman sum-distribution is identical to standard', peq(sich, target), JSON.stringify(sich.slice(2)));
ok('the Sicherman dice are genuinely different from standard',
   JSON.stringify(SICH_A) !== JSON.stringify(STANDARD) || JSON.stringify(SICH_B) !== JSON.stringify(STANDARD));
ok('both Sicherman dice carry six faces, all positive integers',
   SICH_A.length === 6 && SICH_B.length === 6 && [...SICH_A, ...SICH_B].every((f) => Number.isInteger(f) && f >= 1));

console.log('\n— Claim 2: uniqueness, by exhaustive assumption-free search —');
// Every unordered pair of six positive-integer dice (faces 1..11) with the
// standard sum-distribution. No factorization assumed: brute force + exact
// polynomial division. Faces can't exceed 11 (largest sum 12, smallest partner 1).
const found = searchPairs(target, 6, 11);
const asKey = (pr) => pr.map((d) => d.join(',')).sort().join('  ×  ');
const keys = found.map(asKey).sort();
ok('exactly two unordered solutions exist', found.length === 2, `found ${found.length}`);
ok('one solution is the standard pair', keys.includes('1,2,3,4,5,6  ×  1,2,3,4,5,6'));
ok('the only nonstandard solution is the Sicherman pair', keys.includes('1,2,2,3,3,4  ×  1,3,4,5,6,8'));
console.log('     solutions:'); keys.forEach((k) => console.log('       ' + k));

console.log('\n— Claim 3: WHY — the generating-function factorization —');
// x + x^2 + ... + x^6  =  x * (1+x) * (1+x+x^2) * (1-x+x^2)
const oneDie = facesToPoly(STANDARD);
const factored = pmul(pmul(X, PHI2), pmul(PHI3, PHI6));
ok('x+...+x^6  =  x·(1+x)·(1+x+x^2)·(1-x+x^2)', peq(oneDie, factored), JSON.stringify(factored));
// The product of two dice is that, squared: each irreducible appears twice.
const sq = pmul(factored, factored);
ok('the two-dice product is the factorization squared', peq(sq, target));

// Now: a die is any product of a SUBSET of {x, x, Φ2, Φ2, Φ3, Φ3, Φ6, Φ6} that
// is a legal die — non-negative integer coeffs, exactly 6 faces (P(1)=6), no
// constant term (min face ≥ 1). Enumerate every way to split the 8 factors into
// two dice and keep the legal splits. Z[x] is a UFD, so this is exhaustive:
// any factorization of the product into two dice IS such a split.
const factors = [
  { name: 'x',  p: X },    { name: 'x',  p: X },
  { name: 'Φ2', p: PHI2 }, { name: 'Φ2', p: PHI2 },
  { name: 'Φ3', p: PHI3 }, { name: 'Φ3', p: PHI3 },
  { name: 'Φ6', p: PHI6 }, { name: 'Φ6', p: PHI6 },
];
const legal = (poly) => poly.every((c) => c >= 0) && pAt1(poly) === 6 && trim(poly)[0] === 0;
const splitSeen = new Set(); const splits = [];
for (let mask = 0; mask < (1 << 8); mask++) {
  let A = [1], B = [1];
  for (let i = 0; i < 8; i++) (mask & (1 << i) ? (A = pmul(A, factors[i].p)) : (B = pmul(B, factors[i].p)));
  if (!legal(A) || !legal(B)) continue;
  if (!peq(pmul(A, B), target)) continue;                    // safety: must reconstruct the product
  const fa = polyToFaces(A).join(','), fb = polyToFaces(B).join(',');
  const key = [fa, fb].sort().join('  ×  ');
  if (splitSeen.has(key)) continue; splitSeen.add(key); splits.push(key);
}
ok('factor-redistribution yields exactly the same two pairs', splits.sort().join(' || ') === keys.join(' || '),
   splits.join(' || '));
// the load-bearing reason it's exactly two: every legal die needs exactly one x
// (else a zero face), one Φ2 and one Φ3 (the only factors > 1 at x=1, product
// must be 6 = 2·3), leaving only the two Φ6's (value 1 at x=1) free — both
// shared (standard) or both on one die (Sicherman). Two choices.
const std  = pmul(pmul(X, PHI2), pmul(PHI3, PHI6));            // one Φ6 each
const both = pmul(pmul(X, PHI2), pmul(PHI3, pmul(PHI6, PHI6)));// both Φ6 here
const none = pmul(X, pmul(PHI2, PHI3));                         // no Φ6 here
ok('the die that keeps NEITHER Φ6 is the compact Sicherman die {1,2,2,3,3,4}',
   polyToFaces(none).join(',') === '1,2,2,3,3,4');
ok('the die that takes BOTH Φ6 is the stretched Sicherman die {1,3,4,5,6,8}',
   polyToFaces(both).join(',') === '1,3,4,5,6,8');
ok('sharing one Φ6 each is the standard die {1,2,3,4,5,6}', polyToFaces(std).join(',') === '1,2,3,4,5,6');

console.log('\n— Claim 4: the honest edges (what makes uniqueness break) —');
// (a) Drop "positive integers": shift one die down by 1 and the other up by 1.
//     Same sums, trivially, for any pair — so a 0/negative face gives infinitely
//     many "solutions". We show one and confirm equal sums.
const shiftedLo = STANDARD.map((f) => f - 1);  // {0,1,2,3,4,5}
const shiftedHi = STANDARD.map((f) => f + 1);  // {2,3,4,5,6,7}
ok('a 0-face pair {0..5}×{2..7} rolls the same sums (so faces≥1 is load-bearing)',
   peq(dist(shiftedLo, shiftedHi), target));
// (b) Drop "six faces": a single 36-face die and a 1-face die trivially match,
//     and other face-counts admit their own Sicherman partners. Show n=4.
const tgt4 = dist([1, 2, 3, 4], [1, 2, 3, 4]);
const found4 = searchPairs(tgt4, 4, 7);
const keys4 = found4.map((pr) => pr.map((d) => d.join(',')).sort().join('  ×  ')).sort();
ok('four-sided dice have their own Sicherman partner {1,2,2,3}×{1,3,3,5}',
   keys4.includes('1,2,2,3  ×  1,3,3,5'), keys4.join(' | '));
ok('and exactly two solutions there too (standard + one Sicherman)', found4.length === 2, `found ${found4.length}`);
// (c) n where it does NOT happen: a prime p has 1+x+...+x^{p-1} irreducible
//     (cyclotomic Φ_p), so a p-sided die admits NO nonstandard partner.
//     Demonstrate p=5: only the standard pair.
const tgt5 = dist([1, 2, 3, 4, 5], [1, 2, 3, 4, 5]);
const found5 = searchPairs(tgt5, 5, 9);
ok('a five-sided (prime) die has NO Sicherman partner — only the standard pair',
   found5.length === 1, `found ${found5.length}`);

// (d) composites richer than 6: how many nonstandard pairs at n = 8, 9?
const count = (n, maxF) => searchPairs(dist([...Array(n)].map((_, i) => i + 1), [...Array(n)].map((_, i) => i + 1)), n, maxF).length - 1;
const n8 = count(8, 15), n9 = count(9, 17);
ok('an eight-sided die admits more than one nonstandard partner', n8 >= 1, `nonstandard pairs at n=8: ${n8}`);
ok('a nine-sided die admits at least one nonstandard partner', n9 >= 1, `nonstandard pairs at n=9: ${n9}`);
console.log(`     nonstandard pairs — n=4:1, n=5:0, n=6:1, n=8:${n8}, n=9:${n9}`);

// ---- machine-readable dump the page is checked against ----------------------
const results = {
  target: target.slice(2),                 // coefficients for sums 2..12
  sicherman: { A: SICH_A, B: SICH_B, dist: sich.slice(2) },
  factorization: 'x * (1+x) * (1+x+x^2) * (1-x+x^2)',
  solutions_d6: keys,
  solutions_d4: keys4,
  d5_solutions: found5.length,
  generated: new Date().toISOString().slice(0, 10),
};
writeFileSync(new URL('./results.json', import.meta.url), JSON.stringify(results, null, 2) + '\n');

console.log(`\n${fails === 0 ? '✓ ALL CHECKS PASS' : '✗ ' + fails + ' FAILED'} — results.json written\n`);
process.exit(fails ? 1 : 0);
