#!/usr/bin/env node
// verify.mjs — the seven-shuffles theorem, computed exactly (BigInt).
//
// Bayer & Diaconis (1992), "Trailing the dovetail shuffle to its lair",
// Ann. Appl. Probab. 2(2):294–313. The Gilbert–Shannon–Reeds (GSR) model.
//
// Theorem (Bayer–Diaconis). An "a-shuffle" of an n-card deck produces a given
// permutation π with probability
//
//        P_a(π) = C(a + n - r, n) / a^n
//
// where r = r(π) is the number of RISING SEQUENCES of π (maximal runs of
// consecutive values appearing in order). Shuffles compose multiplicatively:
// an a-shuffle followed by a b-shuffle is an (ab)-shuffle, so k independent
// ordinary riffle shuffles = one a-shuffle with a = 2^k.
//
// The number of permutations of n with exactly r rising sequences equals the
// Eulerian number <n, r-1> (permutations with r-1 descents). So the total
// variation distance to the uniform distribution after a 2^k-shuffle is
//
//   TV(k) = (1/2) * sum_{r=1..n} <n,r-1> * | C(2^k+n-r, n)/2^(kn) - 1/n! |.
//
// The total-variation sum is an exact integer ratio, so we compute TV(k) as an
// exact BigInt fraction and only convert to a float at the very end. The
// canonical table (Bayer–Diaconis 1992; reproduced in Diaconis 2003)
// for a 52-card deck is the target we reproduce.

let CHECKS = 0, FAILS = 0;
function check(name, cond, detail = "") {
  CHECKS++;
  if (!cond) { FAILS++; console.log(`  ✗ ${name} ${detail}`); }
  else console.log(`  ✓ ${name}${detail ? "  " + detail : ""}`);
}

// ---- exact integer helpers -------------------------------------------------

// Binomial C(n, k) as BigInt, valid for integer n>=0, k>=0; 0 if k>n.
function binom(n, k) {
  if (k < 0n || k > n) return 0n;
  if (k > n - k) k = n - k;
  let num = 1n, den = 1n;
  for (let i = 0n; i < k; i++) { num *= (n - i); den *= (i + 1n); }
  return num / den;
}

function factorial(n) { let f = 1n; for (let i = 2n; i <= n; i++) f *= i; return f; }

// gcd for fraction reduction
function gcd(a, b) { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b) { [a, b] = [b, a % b]; } return a; }

// Eulerian triangle row <n, j>, j = 0..n-1 (j = number of descents), BigInt.
// Recurrence: A(n,j) = (j+1) A(n-1,j) + (n-j) A(n-1,j-1).
function eulerianRow(n) {
  let row = [1n]; // n=1: <1,0> = 1
  for (let m = 2; m <= n; m++) {
    const next = new Array(m).fill(0n);
    for (let j = 0; j < m; j++) {
      const a = (j < row.length) ? row[j] : 0n;
      const b = (j - 1 >= 0 && j - 1 < row.length) ? row[j - 1] : 0n;
      next[j] = BigInt(j + 1) * a + BigInt(m - j) * b;
    }
    row = next;
  }
  return row; // length n, row[j] = <n,j>
}

// Convert exact fraction p/q (BigInt) to a ROUND-half-up decimal string with
// `digits` places. We scale by 10^digits, round, then place the point.
function fracToDecimal(p, q, digits = 12) {
  const neg = (p < 0n) !== (q < 0n);
  p = p < 0n ? -p : p; q = q < 0n ? -q : q;
  const scale = 10n ** BigInt(digits);
  // round(p/q * scale) = floor((p*scale*2 + q) / (2q))  (round half up)
  let scaled = (p * scale * 2n + q) / (2n * q);
  let intPart = scaled / scale;
  let frac = (scaled % scale).toString().padStart(digits, "0");
  return (neg ? "-" : "") + intPart.toString() + (digits > 0 ? "." + frac : "");
}

// ---- the core computation --------------------------------------------------

// Exact TV distance to uniform after a 2^k-shuffle of an n-card deck.
// Returns { tvNum, tvDen } as a reduced BigInt fraction.
function tvExact(n, k, euler, nFact) {
  const a = 2n ** BigInt(k);
  const aN = a ** BigInt(n);              // a^n  = common scale for P_a
  const N = BigInt(n);
  // Common denominator for |P_a(π) - 1/n!| is D = a^n * n!.
  // term_r = <n,r-1> * | C(a+n-r,n)*n! - a^n |   (numerator over D)
  const D = aN * nFact;
  let sumNum = 0n;
  // sanity: probabilities must sum to 1  ->  sum_r <n,r-1> C(a+n-r,n) = a^n
  let probSumNum = 0n;
  for (let r = 1; r <= n; r++) {
    const c = binom(a + N - BigInt(r), N);   // C(a+n-r, n)
    const weight = euler[r - 1];              // <n, r-1>
    probSumNum += weight * c;
    const diff = c * nFact - aN;              // numerator of (P_a - 1/n!) over D
    const absDiff = diff < 0n ? -diff : diff;
    sumNum += weight * absDiff;
  }
  // TV = (1/2) * sumNum / D
  let num = sumNum, den = 2n * D;
  const g = gcd(num, den);
  num /= g; den /= g;
  return { num, den, probSumNum, aN };
}

console.log("seven-shuffles — exact verification (Bayer–Diaconis GSR model)\n");

// --- 1. formula sanity on a tiny deck we can reason about by hand -----------
console.log("[1] tiny deck: one riffle (a=2) of n=2 cards");
{
  // P_2(identity, r=1) should be 3/4; P_2(transposition, r=2) should be 1/4.
  const pId = binom(2n + 2n - 1n, 2n);      // C(3,2)=3, over a^n=4
  const pTr = binom(2n + 2n - 2n, 2n);      // C(2,2)=1, over 4
  check("P_2(identity)=3/4", pId === 3n, `(C(3,2)=${pId})`);
  check("P_2(transposition)=1/4", pTr === 1n, `(C(2,2)=${pTr})`);
  check("they sum to a^n=4", pId + pTr === 4n);
}

// --- 2. Eulerian row checks --------------------------------------------------
console.log("\n[2] Eulerian numbers (the rising-sequence counts)");
{
  const e4 = eulerianRow(4); // known: 1, 11, 11, 1
  check("<4,*> = 1,11,11,1", e4.join(",") === "1,11,11,1", `(${e4.join(",")})`);
  const e5 = eulerianRow(5); // known: 1, 26, 66, 26, 1
  check("<5,*> = 1,26,66,26,1", e5.join(",") === "1,26,66,26,1", `(${e5.join(",")})`);
  const e52 = eulerianRow(52);
  const sum = e52.reduce((s, x) => s + x, 0n);
  check("sum of row 52 = 52!", sum === factorial(52), "(rising-seq counts partition all 52! orders)");
  check("row 52 is symmetric", e52[0] === e52[51] && e52[10] === e52[41], "(<n,j>=<n,n-1-j>)");
}

// --- 3. normalization checked at k=1..12 (Worpitzky/Bayer–Diaconis) ---------
console.log("\n[3] P_a normalization checked for k=1..12 (n=52)");
{
  const e52 = eulerianRow(52);
  const f52 = factorial(52);
  let allOne = true;
  for (let k = 1; k <= 12; k++) {
    const { probSumNum, aN } = tvExact(52, k, e52, f52);
    if (probSumNum !== aN) allOne = false;
  }
  check("sum_r <52,r-1> C(2^k+52-r,52) = 2^(52k) for k=1..12", allOne,
        "(GSR probabilities sum to 1 exactly)");
}

// --- 4. the canonical 52-card table -----------------------------------------
console.log("\n[4] total-variation distance to uniform, 52-card deck");
console.log("    (target = Bayer–Diaconis 1992, reproduced in Diaconis 2003)\n");
{
  const e52 = eulerianRow(52);
  const f52 = factorial(52);
  // Canonical rounded values (3 decimals) from the literature.
  const target = {
    1: "1.000", 2: "1.000", 3: "1.000", 4: "1.000", 5: "0.924",
    6: "0.614", 7: "0.334", 8: "0.167", 9: "0.085", 10: "0.043",
  };
  console.log("     k   TV(k) (exact, 6 dp)   rounded   literature");
  console.log("    ───  ──────────────────   ───────   ──────────");
  for (let k = 1; k <= 10; k++) {
    const { num, den } = tvExact(52, k, e52, f52);
    const dec = fracToDecimal(num, den, 6);
    const rounded = fracToDecimal(num, den, 3);
    const match = rounded === target[k];
    if (!match) FAILS++;
    CHECKS++;
    console.log(`    ${String(k).padStart(3)}  ${dec.padEnd(18)}   ${rounded}     ${target[k]}   ${match ? "✓" : "✗ MISMATCH"}`);
  }
}

// --- 5. the cutoff location --------------------------------------------------
console.log("\n[5] the cutoff: where TV crosses 1/2, and the (3/2)log2 n law");
{
  const e52 = eulerianRow(52);
  const f52 = factorial(52);
  // find smallest k with TV < 1/2
  let crossing = null;
  for (let k = 1; k <= 12; k++) {
    const { num, den } = tvExact(52, k, e52, f52);
    if (2n * num < den) { crossing = k; break; }  // TV < 1/2
  }
  check("first k with TV<1/2 is 7", crossing === 7,
        `(seven shuffles is where the deck first crosses half-mixed; TV(7)≈0.334)`);
  // theoretical cutoff (3/2) log2(n)
  const cutoff = 1.5 * Math.log2(52);
  check("(3/2)log2(52) ≈ 8.55 (asymptotic center)", Math.abs(cutoff - 8.55) < 0.01,
        `(cutoff = ${cutoff.toFixed(3)}; finite-n deck is half-mixed a bit earlier, at 7)`);
}

// --- 6. monotonicity of P_a in r (justifies the one-crossing structure) -----
console.log("\n[6] structural: P_a(π) strictly decreases as rising sequences grow");
{
  const a = 128n; // a=2^7
  let mono = true;
  for (let r = 1; r < 52; r++) {
    const c1 = binom(a + 52n - BigInt(r), 52n);
    const c2 = binom(a + 52n - BigInt(r + 1), 52n);
    if (!(c1 > c2)) mono = false;
  }
  check("C(a+n-r,n) strictly decreasing in r at k=7", mono,
        "(more rising sequences = rarer outcome = the shuffle's fingerprint)");
}

// --- 7. the browser's logic, certified offline ------------------------------
// The interactive page (a) counts rising sequences and (b) performs GSR riffle
// shuffles. We certify both here so the in-page code rests on a checked base.

// rising sequences of a deck given as an array of values (a permutation of 1..n):
// r = 1 + #{ v in 1..n-1 : position(v) > position(v+1) }.
function risingSequences(deck) {
  const n = deck.length;
  const pos = new Array(n + 1);
  for (let i = 0; i < n; i++) pos[deck[i]] = i;
  let r = 1;
  for (let v = 1; v < n; v++) if (pos[v] > pos[v + 1]) r++;
  return r;
}

// one GSR (Gilbert–Shannon–Reeds) riffle shuffle of `deck`, using rng()∈[0,1).
function gsrShuffle(deck, rng) {
  const n = deck.length;
  // cut: m ~ Binomial(n, 1/2)
  let m = 0; for (let i = 0; i < n; i++) if (rng() < 0.5) m++;
  let i = 0, j = m;                  // top packet [0,m), bottom packet [m,n)
  const out = [];
  while (i < m && j < n) {
    const a = m - i, b = n - j;      // cards left in each packet
    if (rng() < a / (a + b)) out.push(deck[i++]); else out.push(deck[j++]);
  }
  while (i < m) out.push(deck[i++]);
  while (j < n) out.push(deck[j++]);
  return out;
}

console.log("\n[7] the rising-sequence counter, exhaustively (n=6, all 720 orders)");
{
  const n = 6;
  const counts = new Array(n + 1).fill(0); // counts[r] = #perms with r rising seqs
  const perm = [1, 2, 3, 4, 5, 6];
  // Heap's algorithm over all 720 permutations
  const c = new Array(n).fill(0);
  const tally = (p) => counts[risingSequences(p)]++;
  tally(perm.slice());
  let iH = 0;
  while (iH < n) {
    if (c[iH] < iH) {
      const sw = iH % 2 === 0 ? 0 : c[iH];
      [perm[sw], perm[iH]] = [perm[iH], perm[sw]];
      tally(perm.slice());
      c[iH]++; iH = 0;
    } else { c[iH] = 0; iH++; }
  }
  const e6 = eulerianRow(6); // <6,j>, j=0..5
  // counts[r] should equal <6, r-1>
  let ok = true;
  for (let r = 1; r <= n; r++) if (counts[r] !== Number(e6[r - 1])) ok = false;
  check("rising-seq counts match Eulerian <6,r-1>", ok,
        `(observed ${counts.slice(1).join(",")} vs <6,·> ${e6.join(",")})`);
}

console.log("\n[8] the GSR shuffle, Monte-Carlo against the exact law (n=4, a=2)");
{
  const n = 4, trials = 4_000_000;
  // exact P_2(π) depends only on rising sequences r: C(2+4-r,4)/2^4.
  const exactByR = {};
  for (let r = 1; r <= n; r++) exactByR[r] = Number(binom(2n + 4n - BigInt(r), 4n)) / 16;
  // a seeded LCG so the check is deterministic
  let s = 0x2545f491 >>> 0;
  const rng = () => { s |= 0; s = (s + 0x6D2B79F5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  const obsByR = { 1: 0, 2: 0, 3: 0, 4: 0 };
  const base = [1, 2, 3, 4];
  for (let t = 0; t < trials; t++) {
    const d = gsrShuffle(base, rng);
    obsByR[risingSequences(d)]++;
  }
  // each permutation with r rising seqs has prob exactByR[r]; there are <4,r-1> of them.
  const e4 = eulerianRow(4); // 1,11,11,1
  let maxErr = 0;
  for (let r = 1; r <= n; r++) {
    const expFrac = Number(e4[r - 1]) * exactByR[r];   // P(observe r rising seqs)
    const obsFrac = obsByR[r] / trials;
    maxErr = Math.max(maxErr, Math.abs(expFrac - obsFrac));
  }
  check("empirical rising-seq distribution matches GSR law (4M trials)", maxErr < 0.002,
        `(max |obs−exact| = ${maxErr.toExponential(2)} over 4 classes)`);
}

console.log("\n[9] the detector: rising sequences cannot exceed 2^k after k riffles");
{
  // A 2^k-shuffle composes k 2-shuffles; a 2-shuffle at most doubles the rising
  // sequences (Bayer–Diaconis), so after k shuffles r ≤ 2^k. Verify empirically.
  const n = 52;
  let s = 12345 >>> 0;
  const rng = () => { s |= 0; s = (s + 0x6D2B79F5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
  let ok = true;
  for (let trial = 0; trial < 2000; trial++) {
    let d = Array.from({ length: n }, (_, i) => i + 1);
    for (let k = 1; k <= 6; k++) {
      d = gsrShuffle(d, rng);
      if (risingSequences(d) > 2 ** k) ok = false;
    }
  }
  check("after k riffles, rising sequences ≤ 2^k (2000 decks, k≤6)", ok,
        "(the fingerprint in 'Trailing the dovetail shuffle to its lair')");
}

console.log(`\n${FAILS === 0 ? "ALL PASS" : "FAILURES"} — ${CHECKS - FAILS}/${CHECKS} checks`);
process.exit(FAILS === 0 ? 0 : 1);
