#!/usr/bin/env node
/**
 * verify.mjs: offline checks for "Eight Is Not One More Than Seven".
 *
 *   node research/eight-is-not-seven-plus-one/verify.mjs
 *
 * The portal's claim is that four famous "how scrambled is it" numbers are four
 * readings of one curve, B(k) = the number of states reachable in at most k moves,
 * and that two of them are not comparable because they read different features of
 * different curves. So the checks fall into four groups:
 *
 *   A. the machinery is right          (group order and BFS tested against known answers)
 *   B. the four members' own numbers reproduce here, independently
 *   C. the new numbers this portal computes are right, and internally consistent
 *   D. the shipped page prints exactly these numbers and nothing else
 *
 * Nothing here imports a line from any member layer. Where a member's number is
 * used it is written out as that member's published claim, so that a disagreement
 * between their apparatus and this one goes red rather than silently reconciling.
 */

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  factorial, eulerianRow, ratioToDecimal, ratioToDecimalRounded, multiplicativeOrder,
  outShuffle, inShuffle, riffleSupport, riffleDistanceExact, distanceFloorFromSupport,
  cubeSearch, CUBE_STATES, dieHomeOrientations, dieOrientations,
  diameterFloor, mixingFloorFromCounting, deckLadder,
} from './engine.mjs';
import { groupOrder, cayleyBalls, permOrder, identity, compose,
         minimalBlockSystem, preservesBlocks } from './group.mjs';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(HERE, '..', '..');
const PAGE = path.join(ROOT, 'public', 'strata', 'eight-is-not-seven-plus-one', 'index.html');

let passed = 0, failed = 0;
const fails = [];
function check(name, cond, detail = '') {
  if (cond) { passed++; }
  else { failed++; fails.push(`${name}${detail ? ': ' + detail : ''}`); console.log(`  ✗ ${name}${detail ? ': ' + detail : ''}`); }
}
function group(title) { console.log(`\n${title}`); }
const commas = b => b.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');

/* ================================================================== A. machinery */

group('A. the machinery, against answers known independently');

// A permutation group's order, tested on groups whose order is not in doubt.
for (const n of [4, 5, 6, 7, 8, 9]) {
  const t = identity(n).slice(); [t[0], t[1]] = [t[1], t[0]];
  const c = Array.from({ length: n }, (_, i) => (i + 1) % n);
  check(`S_${n} order is ${n}!`, groupOrder([t, c], n) === factorial(n));
}
for (const n of [5, 7, 9]) {
  const t3 = identity(n).slice(); t3[0] = 1; t3[1] = 2; t3[2] = 0;
  const c = Array.from({ length: n }, (_, i) => (i + 1) % n);
  check(`A_${n} order is ${n}!/2`, groupOrder([t3, c], n) === factorial(n) / 2n);
}
// The trivial group and a single generator.
check('trivial group has order 1', groupOrder([identity(6)], 6) === 1n);
{
  const c = Array.from({ length: 12 }, (_, i) => (i + 1) % 12);
  check('one 12-cycle generates a group of order 12', groupOrder([c], 12) === 12n);
  check('permOrder agrees with the group order for a cycle', permOrder(c) === 12n);
}

// Exact arithmetic.
check('52! is the standard value',
  factorial(52) === 80658175170943878571660636856403766975289505440883277824000000000000n);
{
  const A = eulerianRow(52);
  check('Eulerian row of 52 sums to 52!', A.reduce((s, x) => s + x, 0n) === factorial(52));
  check('exactly one permutation of 52 has 51 descents (the reversal)', A[51] === 1n);
  check('exactly one permutation of 52 has 0 descents (the identity)', A[0] === 1n);
  const A5 = eulerianRow(5);
  check('Eulerian row of 5 is 1,26,66,26,1',
    A5.join(',') === '1,26,66,26,1', A5.join(','));
}
check('ratioToDecimal renders 1/8 exactly', ratioToDecimal(1n, 8n, 6) === '0.125000');
check('ratioToDecimal truncates 2/3', ratioToDecimal(2n, 3n, 6) === '0.666666');

/* ================================================================== B. the members */

group('B. the four members\' own published numbers, reproduced here');

// --- eight-perfect-shuffles: the out-shuffle returns after 8, the in-shuffle after 52,
//     and a 24-card packet returns after 11 rather than 8.
{
  check('out-shuffle on 52 has order 8', permOrder(outShuffle(52)) === 8n);
  check('in-shuffle on 52 has order 52', permOrder(inShuffle(52)) === 52n);
  check('out-shuffle order equals the multiplicative order of 2 mod 51',
    permOrder(outShuffle(52)) === multiplicativeOrder(2, 51));
  check('in-shuffle order equals the multiplicative order of 2 mod 53',
    permOrder(inShuffle(52)) === multiplicativeOrder(2, 53));
  check('out-shuffle on 24 has order 11, not 8', permOrder(outShuffle(24)) === 11n);
  // the shuffle group that layer cites for a 24-card packet
  check('the 24-card shuffle group has order 194,641,920 (the figure that layer cites)',
    groupOrder([outShuffle(24), inShuffle(24)], 24) === 194641920n);
}

// --- eleven-moves-from-anywhere: pocket-cube diameters and full depth histograms.
const HTM_PUBLISHED = [1, 9, 54, 321, 1847, 9992, 50136, 227536, 870072, 1887748, 623800, 2644];
const QTM_PUBLISHED = [1, 6, 27, 120, 534, 2256, 8969, 33058, 114149, 360508, 930588, 1350852, 782536, 90280, 276];
const htm = cubeSearch('htm');
const qtm = cubeSearch('qtm');
{
  check('pocket cube has 3,674,160 states', CUBE_STATES === 3674160);
  check('half-turn-metric BFS reaches every state', htm.reached === CUBE_STATES, `${htm.reached}`);
  check('quarter-turn-metric BFS reaches every state', qtm.reached === CUBE_STATES, `${qtm.reached}`);
  check('half-turn diameter is 11', htm.diameter === 11, `${htm.diameter}`);
  check('quarter-turn diameter is 14', qtm.diameter === 14, `${qtm.diameter}`);
  check('the half-turn depth histogram reproduces that layer\'s, term for term',
    JSON.stringify(htm.sphere) === JSON.stringify(HTM_PUBLISHED), JSON.stringify(htm.sphere));
  check('the quarter-turn depth histogram reproduces that layer\'s, term for term',
    JSON.stringify(qtm.sphere) === JSON.stringify(QTM_PUBLISHED), JSON.stringify(qtm.sphere));
  check('half-turn spheres sum to the state count',
    htm.sphere.reduce((a, b) => a + b, 0) === CUBE_STATES);
  check('quarter-turn spheres sum to the state count',
    qtm.sphere.reduce((a, b) => a + b, 0) === CUBE_STATES);
}

// --- half-the-ways-home: twelve of twenty-four orientations come home.
const die = dieHomeOrientations(6);
{
  check('the cube has 24 rotations', dieOrientations().length === 24);
  check('exactly 12 of the 24 orientations recur at the starting cell', die.atHome === 12, `${die.atHome}`);
  check('the die is not confined in position (many cells reached)', die.reachableCells > 60, `${die.reachableCells}`);
  const deeper = dieHomeOrientations(8);
  check('rolling further does not unlock a thirteenth orientation', deeper.atHome === 12, `${deeper.atHome}`);
}

// --- seven-shuffles: the exact Bayer-Diaconis distances.
const euler52 = eulerianRow(52), f52 = factorial(52);
const AD_PUBLISHED = ['1.000', '1.000', '1.000', '1.000', '0.924', '0.614', '0.334', '0.167', '0.085', '0.043'];
{
  for (let k = 1; k <= 10; k++) {
    const { p, q } = riffleDistanceExact(52, k, euler52, f52);
    const got = ratioToDecimalRounded(p, q, 3);
    check(`riffle distance after ${k} shuffles is ${AD_PUBLISHED[k - 1]} (Aldous-Diaconis)`,
      got === AD_PUBLISHED[k - 1], got);
  }
}

/* ================================================================== C. the new numbers */

group('C. the numbers this portal computes that no member holds');

const L = deckLadder(52);

// --- C1. what perfect shuffles can reach at all.
{
  const G = L.shuffleGroup;
  check('the 52-card perfect-shuffle group has order 2^26 * 26!',
    G === (2n ** 26n) * factorial(26), `${G}`);
  check('that order is 27,064,431,817,106,664,380,040,216,576,000,000',
    G === 27064431817106664380040216576000000n);
  check('perfect shuffles reach one ordering in 2,980,227,913,743,310,874,726,229,193,921,875',
    f52 / G === 2980227913743310874726229193921875n, `${f52 / G}`);
  check('the reachable set is a vanishing fraction of the deck', G * 10n ** 33n < f52);

  // WHY it is exactly this many: the two shuffles preserve a pairing of the deck, and the
  // group of a pairing of 2m objects has order exactly 2^m * m!. Equal orders plus containment
  // is equality, so the shuffles generate the whole pairing group and not one element more.
  {
    const bs = minimalBlockSystem([outShuffle(52), inShuffle(52)], 52, 2);
    check('the two shuffles preserve a block system of 26 pairs', bs !== null && bs.blocks.length === 26);
    check('both shuffles map every block onto a block',
      bs !== null && preservesBlocks([outShuffle(52), inShuffle(52)], bs.blocks));
    check('the pairing is the mirror one: position i is paired with position 51 minus i',
      bs !== null && bs.blocks.every(([a, b]) => a + b === 51), bs && JSON.stringify(bs.blocks.slice(0, 3)));
    check('the group of a pairing of 52 objects has order 2^26 * 26!, so containment plus equal order is equality',
      (2n ** 26n) * factorial(26) === L.shuffleGroup);
    // and the mirror pairing is the ONLY thing preserved: a finer or coarser system would
    // give a different order, so the equality above already rules them out.
    const bs4 = minimalBlockSystem([outShuffle(52), inShuffle(52)], 52, 4);
    check('there is no block system of size 4 that both shuffles preserve',
      bs4 === null || !preservesBlocks([outShuffle(52), inShuffle(52)], bs4.blocks));
  }

  // Two independent computations of the same quantity on decks small enough to enumerate.
  for (const size of [8, 10, 12]) {
    const chain = groupOrder([outShuffle(size), inShuffle(size)], size);
    const bfs = cayleyBalls([outShuffle(size), inShuffle(size)], size, 2e6);
    check(`deck of ${size}: stabiliser chain and brute-force enumeration agree on the group order`,
      !bfs.partial && BigInt(bfs.size) === chain, `chain ${chain} vs bfs ${bfs.size}`);
  }
  // And on 24 cards, against the order the member layer cites from the literature.
  check('deck of 24: the chain reproduces the cited 2^11:M12 order',
    groupOrder([outShuffle(24), inShuffle(24)], 24) === 2n ** 11n * 95040n);
}

// --- C2. the out-shuffle's "8" is the SIZE of a reachable set, not a step count.
{
  const out52 = outShuffle(52);
  const cyclic = cayleyBalls([out52], 52, 1e5);
  check('repeating the out-shuffle reaches exactly 8 arrangements', cyclic.size === 8, `${cyclic.size}`);
  check('and its Cayley graph has diameter 7, one less than its order', cyclic.diameter === 7, `${cyclic.diameter}`);
  check('so the number 8 counts a set, and that set is 8 of 52! arrangements',
    BigInt(cyclic.size) === permOrder(out52));
}

// --- C3. the riffle's reachable set: diameter 6, mixing time 7.
{
  const support = [];
  for (let k = 1; k <= 8; k++) support.push(riffleSupport(52, k, euler52));
  check('after 5 riffles some arrangements are still unreachable', support[4] < f52);
  check('after 6 riffles every arrangement is reachable', support[5] === f52);
  check('so the riffle walk has diameter exactly 6', support[4] < f52 && support[5] === f52);
  check('but the deck is not random until 7', L.mixedAt === 7, `${L.mixedAt}`);
  check('covering the space and covering it evenly differ by exactly one shuffle',
    L.mixedAt - 6 === 1);
  // How many arrangements genuinely need the sixth riffle. An earlier draft of this page said
  // "exactly one, the reversal", which is FALSE and is corrected here: the reversal is unique
  // only in carrying the MAXIMUM number of rising sequences.
  const needSix = f52 - support[4];
  check('1.517e65 arrangements cannot be produced by five riffles, not one',
    needSix === 151706512551444814120700127652998499269204008764705163930790422064n, `${needSix}`);
  check('that is 0.001880857237 of the deck',
    ratioToDecimal(needSix, f52, 12) === '0.001880857237', ratioToDecimal(needSix, f52, 12));
  check('the unreachable share IS the counting floor at five, by definition',
    (() => { const fl = distanceFloorFromSupport(support[4], f52);
             return ratioToDecimal(fl.p, fl.q, 12) === ratioToDecimal(needSix, f52, 12); })());
  check('the reversal is the unique arrangement with the maximum 52 rising sequences',
    euler52[51] === 1n);
  check('but many descent classes are unreachable at five, not just the top one',
    (() => { let c = 0; for (let d = 32; d < 52; d++) if (euler52[d] > 0n) c++; return c === 20; })());
}

// --- C4. the counting floor, and the flat part of the cliff.
{
  const s4 = riffleSupport(52, 4, euler52), s5 = riffleSupport(52, 5, euler52);
  const frac4 = ratioToDecimal(s4, f52, 12), frac5 = ratioToDecimal(s5, f52, 12);
  check('after 4 riffles the reachable set is 0.000000466568 of the deck', frac4 === '0.000000466568', frac4);
  check('after 5 riffles it is 0.998119142762 of the deck', frac5 === '0.998119142762', frac5);

  const fl4 = distanceFloorFromSupport(s4, f52), fl5 = distanceFloorFromSupport(s5, f52);
  const b4 = ratioToDecimal(fl4.p, fl4.q, 9), b5 = ratioToDecimal(fl5.p, fl5.q, 9);
  check('counting alone forces the distance after 4 riffles to be at least 0.999999533',
    b4 === '0.999999533', b4);
  check('counting alone says almost nothing after 5 riffles (at least 0.001880857)',
    b5 === '0.001880857', b5);

  // the bound is a genuine lower bound on the exact answer, at every k
  for (let k = 1; k <= 10; k++) {
    const s = riffleSupport(52, k, euler52);
    const fl = distanceFloorFromSupport(s, f52);
    const ex = riffleDistanceExact(52, k, euler52, f52);
    // fl.p/fl.q <= ex.p/ex.q  <=>  fl.p*ex.q <= ex.p*fl.q
    check(`the counting floor is below the exact distance at k=${k}`,
      fl.p * ex.q <= ex.p * fl.q);
  }
  check('the counting floor stops binding at 5', L.mixingCountingFloor === 5, `${L.mixingCountingFloor}`);
  check('the true mixing time is two shuffles later than the counting floor',
    L.mixedAt - L.mixingCountingFloor === 2);
}

// --- C5. counting floors for the diameters, against the truth.
{
  // Pocket cube, half-turn metric: 9 first moves, then never the same face twice, so 6.
  const htmFloor = diameterFloor(CUBE_STATES, 6, 9);
  const qtmFloor = diameterFloor(CUBE_STATES, 5, 6);
  check('counting forces the half-turn diameter to be at least 9', htmFloor === 9, `${htmFloor}`);
  check('the truth is 11, so counting leaves a gap of 2', htm.diameter - htmFloor === 2);
  check('counting forces the quarter-turn diameter to be at least 10', qtmFloor === 10, `${qtmFloor}`);
  check('the truth is 14, so counting leaves a gap of 4', qtm.diameter - qtmFloor === 4);

  // The ball really does grow at close to the branching rate before it saturates.
  const ratios = [];
  for (let i = 2; i < 6; i++) ratios.push(htm.balls[i] / htm.balls[i - 1]);
  check('after the first move the half-turn ball grows 5 to 7 times per move, the branching rate',
    ratios.every(r => r > 5 && r < 7), ratios.map(r => r.toFixed(2)).join(' '));
  check('the first move multiplies the ball by 10, its own branching of 9 plus the start',
    htm.balls[1] === 10);

  // The perfect-shuffle diameter is out of reach, and counting says how far.
  check('counting forces the perfect-shuffle diameter to be at least 114',
    L.perfectDiameterFloor === 114, `${L.perfectDiameterFloor}`);
  check('114 is the smallest d with 2^(d+1) - 1 at least the group order',
    2n ** 115n - 1n >= L.shuffleGroup && 2n ** 114n - 1n < L.shuffleGroup);
  // The floor depends on what counts as a move, and the page states all three rather than
  // quoting the largest one and calling it the answer.
  check('allowing the inverses as moves lowers the floor to 72',
    diameterFloor(L.shuffleGroup, 3, 4) === 72, `${diameterFloor(L.shuffleGroup, 3, 4)}`);
  check('not excluding an immediate undo lowers it further to 57',
    diameterFloor(L.shuffleGroup, 4, 4) === 57, `${diameterFloor(L.shuffleGroup, 4, 4)}`);
  check('all three floors are genuinely below one another', 57 < 72 && 72 < 114);
}

// --- C6. the ladder is internally consistent: reachable <= nominal, everywhere.
{
  check('the cube reaches all of its nominal states', htm.reached === CUBE_STATES);
  check('the die reaches half of its nominal orientations', die.atHome * 2 === 24);
  check('the riffle reaches all of 52!', riffleSupport(52, 6, euler52) === f52);
  check('perfect shuffles reach fewer orderings than riffles do', L.shuffleGroup < f52);
  check('one repeated out-shuffle reaches fewer than two shuffles do', 8n < L.shuffleGroup);
}

/* ============================================ C7. the credit this page gives its members */

// The page narrows its own novelty claim by crediting two members that already draw this curve
// for one system each. That credit is a factual claim about their shipped bytes, so it is gated:
// if either page stops carrying what is quoted, this goes red rather than the page going stale.
group('C7. the members this page credits still say what it says they say');
{
  const readPage = slug => {
    const f = path.join(ROOT, 'public', 'strata', slug, 'index.html');
    return fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : null;
  };
  const half = readPage('half-the-ways-home');
  check('half-the-ways-home exists as a shipped page', half !== null);
  if (half) {
    check('it ships a reachable-in-at-most-n row, and the numbers quoted here are its numbers',
      ['1', '5', '17', '53', '153', '369', '684', '1060'].every(n => half.includes('>' + n + '<')) &&
      /reachable in (&le;|≤|at most)/i.test(half));
    check('it says the interesting invariant is the ceiling rather than the count',
      /interesting invariant isn.{1,3}t the count/i.test(half));
  }
  const eight = readPage('eight-perfect-shuffles');
  check('eight-perfect-shuffles exists as a shipped page', eight !== null);
  if (eight) {
    check('it does ask the group question, so this page may not say it never does',
      /add the in-shuffle and consider every arrangement reachable/i.test(eight));
    check('and it answers by citing Diaconis, Graham and Kantor rather than computing',
      /Diaconis, Graham,? and Kantor/i.test(eight));
    check('it names the Mathieu group and is explicit that it checks the order, not the theorem',
      /Mathieu/i.test(eight) && /checks the resulting order, not the theorem/i.test(eight));
    check('and the 24-card order it checks is the one this chain re-derives',
      groupOrder([outShuffle(24), inShuffle(24)], 24) === 194641920n);
  }
  // Eleven Moves computes its histogram live in the browser, so the literals live in its
  // verifier rather than its page. Gate there, since that is where they actually are.
  {
    const f = path.join(ROOT, 'research', 'eleven-moves-from-anywhere',
                        'verify-eleven-moves-from-anywhere.mjs');
    const src = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '';
    check('eleven-moves-from-anywhere still asserts the depth histogram whose running totals are B(k)',
      HTM_PUBLISHED.every(n => new RegExp(`\\b${n}\\b`).test(src)));
  }
}

/* ================================================================== D. negative controls */

group('D. negative controls: the checks above can go red');

// Each control below deliberately feeds a wrong input or asserts a distinctness that
// would collapse if the machinery were trivial, and returns true when it behaves.
function control(name, fn) {
  let ok = false;
  try { ok = fn() === true; } catch (e) { ok = false; }
  check(name, ok);
}
control('a wrong out-shuffle formula does not give order 8',
  () => permOrder(Array.from({ length: 52 }, (_, i) => (2 * i) % 52)) !== 8n);
control('the group order is not 52! (a real subgroup, not everything)',
  () => L.shuffleGroup !== f52);
control('the counting floor is not the true mixing time',
  () => L.mixingCountingFloor !== L.mixedAt);
control('a corrupted Eulerian row does not sum to 52!',
  () => { const A = eulerianRow(52); A[10] += 1n; return A.reduce((s, x) => s + x, 0n) !== f52; });
control('the half-turn histogram is not the quarter-turn one',
  () => JSON.stringify(htm.sphere) !== JSON.stringify(qtm.sphere));
control('shrinking the cube state count breaks the BFS total',
  () => htm.reached !== CUBE_STATES - 1);

/* ================================================================== E. the shipped page */

group('E. the shipped page prints these numbers and no others');

if (!fs.existsSync(PAGE)) {
  check('the page exists at public/strata/eight-is-not-seven-plus-one/index.html', false);
} else {
  const html = fs.readFileSync(PAGE, 'utf8');
  // Every literal figure the prose states is recomputed here and matched against the
  // page's bytes, so a number that drifts in either direction goes red.
  const must = [
    ['52! in full', commas(f52)],
    ['the perfect-shuffle group order',
      commas(L.shuffleGroup)],
    ['how rare a reachable ordering is',
      commas(f52 / L.shuffleGroup)],
    ['the 4-riffle reachable share',
      ratioToDecimal(riffleSupport(52, 4, euler52), f52, 12)],
    ['the 5-riffle reachable share',
      ratioToDecimal(riffleSupport(52, 5, euler52), f52, 12)],
    ['the 4-riffle counting floor',
      (() => { const f = distanceFloorFromSupport(riffleSupport(52, 4, euler52), f52);
               return ratioToDecimal(f.p, f.q, 9); })()],
    ['the 5-riffle counting floor',
      (() => { const f = distanceFloorFromSupport(riffleSupport(52, 5, euler52), f52);
               return ratioToDecimal(f.p, f.q, 9); })()],
    ['the exact 5-riffle distance',
      (() => { const d = riffleDistanceExact(52, 5, euler52, f52);
               return ratioToDecimal(d.p, d.q, 6); })()],
    ['the perfect-shuffle diameter floor', String(L.perfectDiameterFloor)],
    ['the pocket cube state count', commas(BigInt(CUBE_STATES))],
  ];
  for (const [what, needle] of must) {
    check(`the page carries ${what}`, html.includes(needle), needle);
  }
  // The page must print a command that runs, and it must be this file.
  check('the page cites this verifier by a path that exists',
    html.includes('research/eight-is-not-seven-plus-one/verify.mjs'));
  // The page must not claim a diameter for the perfect-shuffle graph, which is not computed.
  check('the page does not claim a computed perfect-shuffle diameter',
    !/perfect-shuffle diameter is \d/i.test(html));
  // The engine the page loads must be the engine this verifier loaded.
  for (const mod of ['engine.mjs', 'group.mjs']) {
    const a = fs.readFileSync(path.join(HERE, mod), 'utf8');
    const mirrored = path.join(ROOT, 'public', 'strata', 'eight-is-not-seven-plus-one', 'engine', mod);
    check(`the page's copy of ${mod} is byte-identical to the lab's`,
      fs.existsSync(mirrored) && fs.readFileSync(mirrored, 'utf8') === a);
  }

  // The page states how many offline checks stand behind it. That literal is gated against
  // this run's own total, counting this check, so it cannot quietly drift.
  {
    const total = passed + failed + 1;
    check(`the page states its own offline check count (${total})`,
      html.includes(`Offline: ${total} checks`),
      `page says: ${(html.match(/Offline: (\d+) checks/) || [, 'nothing'])[1]}`);
  }

}

/* ================================================================== */

console.log(`\n${passed} checks passed, ${failed} failed.`);
if (failed) { console.log('\nFAILURES:'); for (const f of fails) console.log('  - ' + f); process.exit(1); }
