import assert from 'node:assert/strict';
import { execSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { homedir } from 'node:os';

const HERE = dirname(fileURLToPath(import.meta.url));

function modPow(base, exponent, modulus) {
  let result = 1;
  let factor = base % modulus;
  let power = exponent;
  while (power > 0) {
    if (power % 2 === 1) result = (result * factor) % modulus;
    factor = (factor * factor) % modulus;
    power = Math.floor(power / 2);
  }
  return result;
}

function multiplicativeOrder(base, modulus) {
  let value = 1;
  for (let exponent = 1; exponent <= modulus; exponent += 1) {
    value = (value * base) % modulus;
    if (value === 1) return exponent;
  }
  throw new Error(`No multiplicative order found for ${base} modulo ${modulus}`);
}

function outPosition(position, size) {
  assert.equal(size % 2, 0, 'A perfect two-packet shuffle needs an even packet');
  return position === size - 1 ? position : (2 * position) % (size - 1);
}

function inPosition(position, size) {
  assert.equal(size % 2, 0, 'A perfect two-packet shuffle needs an even packet');
  return (2 * position + 1) % (size + 1);
}

function permutation(size, positionMap) {
  return Array.from({ length: size }, (_, position) => positionMap(position, size));
}

function compose(left, right) {
  return left.map((_, position) => left[right[position]]);
}

function isIdentity(perm) {
  return perm.every((destination, origin) => destination === origin);
}

function permutationOrder(perm) {
  const identity = perm.map((_, position) => position);
  let power = identity;
  for (let exponent = 1; exponent <= 10000; exponent += 1) {
    power = compose(perm, power);
    if (isIdentity(power)) return exponent;
  }
  throw new Error('Permutation order exceeded verifier bound');
}

function cycleLengths(perm) {
  const seen = Array(perm.length).fill(false);
  const lengths = [];
  for (let start = 0; start < perm.length; start += 1) {
    if (seen[start]) continue;
    let cursor = start;
    let length = 0;
    do {
      assert.equal(seen[cursor], false, 'Permutation cycle closed at the wrong point');
      seen[cursor] = true;
      cursor = perm[cursor];
      length += 1;
    } while (cursor !== start);
    lengths.push(length);
  }
  return lengths.sort((a, b) => a - b);
}

function applyShuffleToDeck(deck, positionMap) {
  const shuffled = Array(deck.length);
  for (let oldPosition = 0; oldPosition < deck.length; oldPosition += 1) {
    shuffled[positionMap(oldPosition, deck.length)] = deck[oldPosition];
  }
  assert.equal(shuffled.every((card) => card !== undefined), true);
  return shuffled;
}

function elmsleySequence(target) {
  return target.toString(2).split('').map((bit) => (bit === '1' ? 'in' : 'out'));
}

function steerTopCard(target, size) {
  let deck = Array.from({ length: size }, (_, card) => card);
  for (const shuffle of elmsleySequence(target)) {
    deck = applyShuffleToDeck(deck, shuffle === 'in' ? inPosition : outPosition);
  }
  return deck.indexOf(0);
}

const out52 = permutation(52, outPosition);
const in52 = permutation(52, inPosition);
const out24 = permutation(24, outPosition);

const out52ModularOrder = multiplicativeOrder(2, 51);
const in52ModularOrder = multiplicativeOrder(2, 53);
const out24ModularOrder = multiplicativeOrder(2, 23);

assert.equal(modPow(2, 8, 51), 1);
assert.equal(out52ModularOrder, 8);
assert.equal(permutationOrder(out52), 8);
const out52Power = 2 ** out52ModularOrder;
const out52Quotient = (out52Power - 1) / 51;
assert.equal(out52Power, 256);
assert.equal(out52Quotient, 5);

assert.equal(modPow(2, 52, 53), 1);
assert.equal(in52ModularOrder, 52);
assert.equal(permutationOrder(in52), 52);

const out52Cycles = cycleLengths(out52);
assert.deepEqual(out52Cycles, [1, 1, 2, 8, 8, 8, 8, 8, 8]);
assert.equal(out52Cycles.every((length) => 8 % length === 0), true);

const steeringResults = Array.from({ length: 52 }, (_, target) => ({
  target,
  landing: steerTopCard(target, 52),
}));
assert.equal(steeringResults.every(({ target, landing }) => target === landing), true);

assert.equal(modPow(2, 8, 23), 3);
assert.equal(modPow(2, 11, 23), 1);
assert.equal(out24ModularOrder, 11);
assert.equal(permutationOrder(out24), 11);
assert.deepEqual(cycleLengths(out24), [1, 1, 11, 11]);
const out24PowerAtEight = 2 ** 8;
const out24QuotientAtEight = Math.floor(out24PowerAtEight / 23);
const out24PowerAtReturn = 2 ** out24ModularOrder;
const out24QuotientAtReturn = (out24PowerAtReturn - 1) / 23;
assert.equal(out24PowerAtEight, 256);
assert.equal(out24QuotientAtEight, 11);
assert.equal(out24PowerAtReturn, 2048);
assert.equal(out24QuotientAtReturn, 89);

const m12Order = (2 ** 6) * (3 ** 3) * 5 * 11;
assert.equal(m12Order, 95040);
const shuffleGroup24Order = (2 ** 11) * m12Order;
assert.equal(shuffleGroup24Order, 194641920);

console.log('52-card out-shuffle');
console.log(`  2^8 = ${out52Power} = ${out52Quotient} * 51 + ${modPow(2, 8, 51)}`);
console.log(`  multiplicative order of 2 mod 51 = ${out52ModularOrder}`);
console.log(`  permutation cycle lengths = ${out52Cycles.join(', ')}`);
console.log('52-card in-shuffle');
console.log(`  2^52 mod 53 = ${modPow(2, 52, 53)}`);
console.log(`  multiplicative order of 2 mod 53 = ${in52ModularOrder}`);
console.log('Elmsley steering');
console.log(`  exhaustive targets landed correctly = ${steeringResults.length}/${steeringResults.length}`);
console.log('24-card out-shuffle');
console.log(`  2^8 = ${out24PowerAtEight} = ${out24QuotientAtEight} * 23 + ${modPow(2, 8, 23)} (not restored)`);
console.log(`  2^11 = ${out24PowerAtReturn} = ${out24QuotientAtReturn} * 23 + ${modPow(2, 11, 23)} (restored)`);
console.log(`  multiplicative order of 2 mod 23 = ${out24ModularOrder}`);
console.log('24-card shuffle group, cited structure 2^11 : M12');
console.log(`  |M12| = 2^6 * 3^3 * 5 * 11 = ${m12Order}`);
console.log(`  2^11 * ${m12Order} = ${shuffleGroup24Order}`);
// ---- THE KERNEL PROOF (Lean) — the return law for EVERY deck, no instance ---------
// The checks above INSTANTIATE the return law at two deck sizes: they build the actual
// 52- and 24-card permutations and compute their cycle order, matching it to the
// multiplicative order of 2. A permutation built at one size only ever settles that one
// deck. lean/PerfectShuffle.lean proves the law for ALL sizes at once: the perfect
// out-shuffle of a deck of m+1 cards is restored after k shuffles exactly when
// 2^k mod m = 1, so the return count is ord_m(2) — with no search. Here we (a) confirm
// the Lean model (position p<m goes to 2p mod m; the last card is fixed; restored iff
// 2^k mod m = 1) matches the engine's own outPosition/permutation-order over a sweep of
// even decks, and (b) when `lean` is on PATH, typecheck the file live and assert its
// [propext] / [propext, Quot.sound] axiom footprint.
console.log('The kernel proof (Lean): out-shuffle return count = ord_{deck-1}(2), for EVERY deck');
{
  // (a) MODEL FIDELITY. The Lean file operates outStep m p = (p==m) ? p : (2p) mod m,
  // and Restores m k := every position p<=m returns. Assert this is byte-for-byte the
  // engine's outPosition (with m = size-1), and that its return count agrees with the
  // real permutation's cycle order AND with ord_m(2), across every even deck 4..120.
  const leanOutStep = (m, p) => (p === m ? p : (2 * p) % m);
  const leanRestores = (m, k) => {
    for (let p = 0; p <= m; p += 1) {
      let cur = p;
      for (let s = 0; s < k; s += 1) cur = leanOutStep(m, cur);
      if (cur !== p) return false;
    }
    return true;
  };
  let stepMismatch = 0, orderMismatch = 0, restoreMismatch = 0, decks = 0;
  for (let size = 4; size <= 120; size += 2) {
    const m = size - 1;
    decks += 1;
    // engine outPosition == Lean outStep for every position of every deck
    for (let p = 0; p < size; p += 1) {
      if (outPosition(p, size) !== leanOutStep(m, p)) stepMismatch += 1;
    }
    // the return count three ways: real permutation order, ord_m(2), Lean Restores
    const permOrder = permutationOrder(permutation(size, outPosition));
    const modOrder = multiplicativeOrder(2, m);
    if (permOrder !== modOrder) orderMismatch += 1;
    // Restores m k holds at k = the order and fails below it (2^k mod m = 1 iff restored)
    if (!leanRestores(m, modOrder)) restoreMismatch += 1;
    for (let k = 1; k < modOrder; k += 1) if (leanRestores(m, k)) restoreMismatch += 1;
    if ((modPow(2, modOrder, m) === 1) !== leanRestores(m, modOrder)) restoreMismatch += 1;
  }
  assert.equal(stepMismatch, 0, 'Lean outStep == engine outPosition for every position of every deck');
  assert.equal(orderMismatch, 0, 'permutation cycle order == ord_{deck-1}(2) for every even deck 4..120');
  assert.equal(restoreMismatch, 0, 'Lean Restores(m,k) == (2^k mod m == 1) and first return = ord_m(2)');
  console.log(`  model fidelity: ${decks} even decks (4..120), 0 mismatches across step / order / return`);

  // the specific numbers the Lean file settles by decide, recomputed independently here
  assert.equal(leanRestores(51, 8), true);          // deck52_returns_after_eight
  assert.equal(leanRestores(51, 7), false);         // deck52_no_fewer (last of 1..7)
  assert.equal(leanRestores(23, 8), false);         // deck24_not_after_eight
  assert.equal(leanRestores(23, 11), true);         // deck24_returns_after_eleven
  console.log('  concrete: Restores(51,8)=T, Restores(51,<8)=F, Restores(23,8)=F, Restores(23,11)=T — matches Lean decides');

  // THE PERIOD (§3b): the deck is home at EXACTLY the multiples of the order, never else —
  // deck52_period (Restores 51 k <=> 8|k) and deck24_period (<=> 11|k). Cross-check the
  // full divisibility claim over a k-range, independently of the first-return check above.
  let periodMismatch = 0;
  for (const [m, ord] of [[51, 8], [23, 11]]) {
    for (let k = 0; k <= 5 * ord + 3; k += 1) {
      if (leanRestores(m, k) !== (k % ord === 0)) periodMismatch += 1;
    }
  }
  assert.equal(periodMismatch, 0, 'period theorem: Restores(51,k)<=>8|k and Restores(23,k)<=>11|k over k-range');
  // spot the gap the concrete minimality theorems leave: 12 is > 8 but not a multiple, so
  // the deck is NOT home at 12 (only deck52_period settles this, not deck52_no_fewer).
  assert.equal(leanRestores(51, 12), false, 'deck52_period: 52-card deck is NOT home after 12 shuffles (12 not a multiple of 8)');
  assert.equal(leanRestores(51, 16), true, 'deck52_period: 52-card deck IS home after 16 shuffles (16 = 2*8)');
  console.log('  period: home at exactly the multiples of the order (8 for 52, 11 for 24) — 12 not home, 16 home');

  // ---- §M. THE IN-SHUFFLE, for every deck (Lean §4: in_return_iff) -----------------
  // The page's other control. Until now its return count (52 for a 52-card deck) was
  // INSTANTIATED at one size, exactly as the out-shuffle's was. The Lean file proves the
  // law: in the shifted coordinate p+1 the in-shuffle is again pure doubling, so the deck
  // returns after k in-shuffles iff 2^k = 1 mod (deck size + 1). Confirm the Lean model
  // against the engine's inPosition, and its return count against the real permutation.
  const leanInStep = (m, p) => (2 * p + 1) % (m + 2);
  const leanInRestores = (m, k) => {
    for (let p = 0; p <= m; p += 1) {
      let cur = p;
      for (let s = 0; s < k; s += 1) cur = leanInStep(m, cur);
      if (cur !== p) return false;
    }
    return true;
  };
  {
    let stepMismatch = 0, orderMismatch = 0, restoreMismatch = 0, escaped = 0, decks = 0;
    for (let size = 4; size <= 120; size += 2) {
      const m = size - 1;
      decks += 1;
      for (let p = 0; p < size; p += 1) {
        if (inPosition(p, size) !== leanInStep(m, p)) stepMismatch += 1;
        // the range half of inIter_shift: an in-shuffle never sends a card off the deck
        if (leanInStep(m, p) > m) escaped += 1;
      }
      const permOrder = permutationOrder(permutation(size, inPosition));
      const modOrder = multiplicativeOrder(2, m + 2);
      if (permOrder !== modOrder) orderMismatch += 1;
      if (!leanInRestores(m, modOrder)) restoreMismatch += 1;
      for (let k = 1; k < modOrder; k += 1) if (leanInRestores(m, k)) restoreMismatch += 1;
    }
    assert.equal(stepMismatch, 0, 'Lean inStep == engine inPosition for every position of every deck');
    assert.equal(escaped, 0, 'inIter_shift range half: no in-shuffle sends a card off the deck');
    assert.equal(orderMismatch, 0, 'in-shuffle permutation order == ord_{deck+1}(2) for every even deck 4..120');
    assert.equal(restoreMismatch, 0, 'Lean InRestores(m,k) == (2^k mod m+2 == 1), first return = ord_{m+2}(2)');
    // the concrete numbers the Lean file settles by decide
    assert.equal(leanInRestores(51, 52), true);   // deck52_in_returns_after_52
    assert.equal(leanInRestores(51, 51), false);  // deck52_in_no_fewer (last of 1..51)
    assert.equal(leanInRestores(23, 20), true);   // deck24_in_returns_after_twenty
    assert.equal(multiplicativeOrder(2, 25), 20);
    console.log(`  in-shuffle: ${decks} even decks (4..120), 0 mismatches; return count = ord_{deck+1}(2)`);
    console.log('    concrete: InRestores(51,52)=T, InRestores(51,<52)=F, InRestores(23,20)=T — 52 in-shuffles against 8 out');
  }

  // ---- §S. ELMSLEY STEERING, for every deck (Lean §5: elmsley) ---------------------
  // The page's live audit simulates all 52 targets of ONE 52-card deck. The Lean file
  // proves the rule for every even deck and every legal target, and its proof says
  // something the simulation does not: NO MODULUS EVER BITES. Both shuffles reduce to
  // p -> 2p + digit while the running position stays inside the deck, so the tracked
  // card's position IS the binary number, digit by digit. Measure that directly.
  const leanBitStep = (m, bit, p) => (bit ? leanInStep(m, p) : (p === m ? p : (2 * p) % m));
  {
    let landed = 0, missed = 0, reductions = 0, decks = 0;
    for (let size = 4; size <= 120; size += 2) {
      const m = size - 1;
      decks += 1;
      for (let target = 0; target < size; target += 1) {
        // (i) the model, watching for any modular reduction
        let p = 0;
        for (const ch of target.toString(2)) {
          const bit = ch === '1';
          const raw = 2 * p + (bit ? 1 : 0);
          p = leanBitStep(m, bit, p);
          if (p !== raw) reductions += 1;
        }
        // (ii) independently, the engine shuffling COMPLETE decks, then locating card 0
        if (p === target && steerTopCard(target, size) === target) landed += 1;
        else missed += 1;
      }
    }
    assert.equal(missed, 0, 'Elmsley: every legal target of every even deck 4..120 lands exactly');
    assert.equal(reductions, 0,
      'the shift-register claim: no modular reduction EVER occurs on a legal target — the position is the binary number');
    console.log(`  Elmsley steering: ${landed} (deck, target) pairs across ${decks} even decks (4..120), 0 misses`);
    console.log('    and 0 modular reductions in any of them — the deck is literally a shift register');
  }

  // ---- §S2. THE PARITY HYPOTHESIS IS SHARP (Lean: odd_deck_5_fails) ----------------
  // `elmsley` requires m odd, i.e. an EVEN deck. That is not decoration. On an odd deck
  // the doubling can land exactly ON the modulus, which wraps to 0. Measure where it
  // bites. (The engine refuses odd decks by assertion — deliberately — so this sweep runs
  // the Lean model directly, which is defined for every m.)
  {
    let decks = 0, wrongShape = 0, totalFailures = 0;
    for (let size = 5; size <= 201; size += 2) {
      const m = size - 1;
      decks += 1;
      const failures = [];
      for (let target = 0; target < size; target += 1) {
        let p = 0;
        for (const ch of target.toString(2)) p = leanBitStep(m, ch === '1', p);
        if (p !== target) failures.push(target);
      }
      totalFailures += failures.length;
      if (failures.length !== 1 || failures[0] !== size - 1) wrongShape += 1;
    }
    assert.equal(decks, 99, 'the odd-deck sweep actually ran (99 decks, 5..201)');
    assert.equal(wrongShape, 0,
      'on every odd deck 5..201 the binary rule fails at exactly one target: the last position');
    // positive form of the same fact, so the check bites on the DATA and not only on a shape:
    // one failure per odd deck, no more and no fewer. (On even decks §S measured zero.)
    assert.equal(totalFailures, decks,
      'exactly one failing target per odd deck — the parity hypothesis costs exactly one position');
    // the exact witness the Lean file exhibits: a five-card deck, target 4
    let p = 0;
    for (const ch of (4).toString(2)) p = leanBitStep(4, ch === '1', p);
    assert.equal(p, 0, 'odd_deck_5_fails: on five cards, target 4 lands the card back on top');
    assert.notEqual(p, 4);
    console.log(`  sharpness: across ${decks} ODD decks (5..201) the rule fails at exactly one target each — the last`);
    console.log('    witness: five cards, target 4 = "100", lands at 0 (this is odd_deck_5_fails)');
  }

  // ---- §S3. THE BINARY WORD IS SHORTEST (Lean: no_shorter_word, bits_shortest) -----
  // A k-instruction word can only spell a k-digit binary number, so it cannot reach a
  // target >= 2^k. Two independent measurements of what that buys: (a) breadth-first
  // search over the shuffle graph confirms the true minimum instruction count is the bit
  // length, and counts how many shortest words reach each target; (b) the injectivity
  // boundary — length-k words land on distinct positions exactly while 2^k <= deck size,
  // which is precisely the hypothesis the Lean theorem carries.
  {
    const bfs = (size) => {
      const m = size - 1;
      const dist = Array(size).fill(-1), ways = Array(size).fill(0);
      dist[0] = 0; ways[0] = 1;
      let frontier = [0];
      while (frontier.length) {
        const next = [];
        for (const p of frontier) {
          for (const bit of [false, true]) {
            const q = leanBitStep(m, bit, p);
            if (q >= size) continue;
            if (dist[q] === -1) { dist[q] = dist[p] + 1; next.push(q); }
            if (dist[q] === dist[p] + 1) ways[q] += ways[p];
          }
        }
        frontier = next;
      }
      return { dist, ways };
    };
    let checked = 0, longer = 0, ambiguous = 0, unreachable = 0;
    for (const size of [4, 6, 8, 16, 24, 32, 52, 64, 100, 120]) {
      const { dist, ways } = bfs(size);
      for (let t = 1; t < size; t += 1) {
        checked += 1;
        if (dist[t] === -1) { unreachable += 1; continue; }
        if (dist[t] !== t.toString(2).length) longer += 1;
        if (ways[t] !== 1) ambiguous += 1;
      }
    }
    assert.equal(unreachable, 0, 'every position is reachable from the top');
    assert.equal(longer, 0,
      'BFS: the true minimum instruction count is exactly the target\'s bit length — the binary word is shortest');
    assert.equal(ambiguous, 0, 'BFS: the shortest instruction word is unique for every target measured');
    console.log(`  shortest: BFS over 10 deck sizes, ${checked} targets — minimum word length == bit length in all of them`);
    console.log('    and the shortest word is unique in every one — proved outright since 2026-08-02 (Lean: elmsley_unique); §S4 below is the independent path');

    // the injectivity boundary: distinct length-k words land distinctly iff 2^k <= deck size
    let boundaryMismatch = 0;
    for (const size of [8, 24, 52, 64]) {
      const m = size - 1;
      for (let k = 1; (1 << k) <= 4 * size; k += 1) {
        const landings = new Set();
        for (let w = 0; w < (1 << k); w += 1) {
          let p = 0;
          for (let i = k - 1; i >= 0; i -= 1) p = leanBitStep(m, ((w >> i) & 1) === 1, p);
          landings.add(p);
        }
        const injective = landings.size === (1 << k);
        if (injective !== ((1 << k) <= size)) boundaryMismatch += 1;
      }
    }
    assert.equal(boundaryMismatch, 0,
      'length-k words are injective exactly while 2^k <= deck size — the boundary the no-wrap reading predicts');
    console.log('    injectivity boundary measured at 2^k <= deck size, exactly where the moduli start to bite');
  }

  // ---- §S4. THE SHORTEST WORD IS UNIQUE (Lean: steer_dichotomy, elmsley_unique) ----
  // Until 2026-08-02 the uniqueness of the shortest word was the one claim on this page
  // resting on measurement alone: §S3's BFS over ten deck sizes. It is now a theorem, so
  // this section does what the house rule asks — reach the same statement by a path that
  // shares no code with the kernel: a forward dynamic program that COUNTS words rather
  // than searching for one, swept far wider than the original BFS.
  {
    // routeCounts(m, L)[p] = how many length-L instruction words carry the top card to p.
    // Position m+1 is included so a card leaving the deck would be visible rather than
    // silently folded away.
    const routeCounts = (m, maxLen) => {
      const table = [];
      let cur = new Float64Array(m + 2);
      cur[0] = 1;
      table.push(cur);
      for (let L = 1; L <= maxLen; L += 1) {
        const nxt = new Float64Array(m + 2);
        for (let p = 0; p <= m + 1; p += 1) {
          if (cur[p] === 0) continue;
          nxt[leanBitStep(m, false, p)] += cur[p];
          nxt[leanBitStep(m, true, p)] += cur[p];
        }
        table.push(nxt);
        cur = nxt;
      }
      return table;
    };
    const bitlen = (n) => (n === 0 ? 0 : n.toString(2).length);

    // (a) UNIQUENESS, swept 100x wider than the BFS it replaces.
    let pairs = 0, unreachable = 0, wrongLength = 0, notUnique = 0, escaped = 0;
    for (let size = 2; size <= 2000; size += 2) {
      const m = size - 1;
      const maxLen = bitlen(m) + 4;
      const table = routeCounts(m, maxLen);
      for (let L = 0; L <= maxLen; L += 1) if (table[L][m + 1] !== 0) escaped += 1;
      for (let t = 0; t <= m; t += 1) {
        pairs += 1;
        let minLen = -1;
        for (let L = 0; L <= maxLen; L += 1) if (table[L][t] > 0) { minLen = L; break; }
        if (minLen < 0) { unreachable += 1; continue; }
        if (minLen !== bitlen(t)) wrongLength += 1;
        if (table[minLen][t] !== 1) notUnique += 1;
      }
    }
    assert.equal(escaped, 0, 'no word of any length sends the top card off an even deck');
    assert.equal(unreachable, 0, 'every target reachable on every even deck swept');
    assert.equal(wrongLength, 0,
      'minimum instruction count == bit length of the target, on every even deck 2..2000');
    assert.equal(notUnique, 0,
      'the SHORTEST instruction word is unique — every even deck 2..2000, every target');
    assert.equal(pairs, 1001000, 'uniqueness sweep covered the expected number of pairs');
    console.log(`  unique: ${pairs.toLocaleString()} (deck,target) pairs over 1000 even decks — exactly one shortest word in each`);

    // (b) THE LEMMA THE PROOF RESTS ON, measured directly: a wrap costs a whole deck.
    // For every legal start and every word, the run is either exactly the number the word
    // spells or at least m behind it. Nothing in between — that gap is the whole proof.
    let runs = 0, between = 0, offDeck = 0, tight = 0;
    for (let m = 1; m <= 61; m += 2) {
      for (let p0 = 0; p0 <= m; p0 += 1) {
        for (let L = 0; L <= 10; L += 1) {
          for (let w = 0; w < (1 << L); w += 1) {
            let pos = p0, val = p0;
            for (let i = L - 1; i >= 0; i -= 1) {
              const bit = ((w >> i) & 1) === 1;
              val = 2 * val + (bit ? 1 : 0);
              pos = leanBitStep(m, bit, pos);
            }
            runs += 1;
            if (pos > m) offDeck += 1;
            if (val !== pos && val < pos + m) between += 1;
            if (val === pos + m) tight += 1;
          }
        }
      }
    }
    assert.equal(offDeck, 0, 'no run leaves the deck (the parity hypothesis, seen directly)');
    assert.equal(between, 0,
      'steer_dichotomy: every run is EXACT or a whole deck behind the value it spells — never in between');
    assert.equal(tight > 0, true,
      'the whole-deck gap is attained, so the bound is tight rather than slack');
    console.log(`  dichotomy: ${runs.toLocaleString()} runs (31 decks x every start x every word to length 10) — 0 in between, ${tight.toLocaleString()} exactly a deck behind`);

    // (c) THE LEAN HYPOTHESIS `2^|w| <= t + m` IS SUFFICIENT — and honestly, NOT necessary.
    // Sufficiency is what the theorem claims and must never fail. Necessity is a separate
    // question the theorem does not claim, and the answer is no: a thin band just past the
    // bound stays unique anyway. Both are asserted as totals so a change in either bites.
    let insideNotUnique = 0, outsideStillUnique = 0, inside = 0, outside = 0;
    for (let size = 2; size <= 300; size += 2) {
      const m = size - 1;
      const maxLen = bitlen(m) + 3;
      const table = routeCounts(m, maxLen);
      for (let L = 0; L <= maxLen; L += 1) {
        for (let t = 0; t <= m; t += 1) {
          if (table[L][t] === 0) continue;
          const fits = Math.pow(2, L) <= t + m;
          const unique = table[L][t] === 1;
          if (fits) { inside += 1; if (!unique) insideNotUnique += 1; }
          else { outside += 1; if (unique) outsideStillUnique += 1; }
        }
      }
    }
    assert.equal(insideNotUnique, 0,
      'SUFFICIENT: wherever 2^|w| <= t+m, the word that lands on t is unique — no exception in 45,000 cases');
    assert.equal(inside, 45000, 'the sufficiency sweep covered the expected number of cases');
    assert.equal(outsideStillUnique, 150,
      'NOT NECESSARY: exactly 150 cases past the bound are still unique — the theorem claims sufficiency only');
    console.log(`  hypothesis: sufficient in all ${inside.toLocaleString()} cases inside the bound; of ${outside.toLocaleString()} outside it, ${outsideStillUnique} stay unique anyway (so the bound is not the exact boundary, and the page says so)`);

    // (d) THE SHARPNESS WITNESS the Lean file exhibits, recomputed here from scratch.
    const runWord = (m, word) => {
      let p = 0;
      for (const ch of word) p = leanBitStep(m, ch === '1', p);
      return p;
    };
    const spells = (word) => parseInt(word, 2);
    assert.equal(bitlen(32), 6, 'target 32 takes six instructions');
    assert.equal(runWord(51, '100000'), 32, 'the six-instruction binary word reaches 32');
    assert.equal(runWord(51, '0100000'), 32, 'padded with a leading out-shuffle, seven instructions also reach 32');
    assert.equal(runWord(51, '1010101'), 32, 'and so does a second, genuinely different seven-instruction word');
    assert.equal(spells('1010101'), 85, 'that second word spells 85, not 32 — it wrapped');
    assert.equal(Math.pow(2, 6) <= 32 + 51, true, 'six instructions sit inside the theorem hypothesis');
    assert.equal(Math.pow(2, 7) <= 32 + 51, false, 'seven instructions sit outside it — exactly where uniqueness dies');
    // and the count: how many of the 52 targets gain a second route with one spare instruction
    let gained = 0;
    {
      const table = routeCounts(51, 8);
      for (let t = 0; t <= 51; t += 1) if (table[bitlen(t) + 1][t] > 1) gained += 1;
    }
    assert.equal(gained, 20, 'on a 52-card deck, 20 of the 52 targets gain a second route at one spare instruction');
    console.log('  sharp: 52-card deck, target 32 — one word at 6 instructions, two at 7 (the second spells 85 and wrapped); 20 of 52 targets gain a second route at +1');
  }

  // (b) THE FILE: theorems present, no sorry / native_decide, typecheck + footprint.
  const leanFile = join(HERE, 'lean', 'PerfectShuffle.lean');
  assert.equal(existsSync(leanFile), true, 'Lean proof file present (lean/PerfectShuffle.lean)');
  const src = readFileSync(leanFile, 'utf8');
  for (const t of ['out_return_iff', 'outIter_mobile', 'deck52_returns_after_eight',
    'deck52_no_fewer', 'deck24_not_after_eight', 'deck24_returns_after_eleven',
    'least_restorer_dvd', 'deck52_period', 'deck24_period',
    'restored_add', 'restored_sub', 'restored_mul', 'restored_mod',
    'inStep_shift', 'inIter_shift', 'in_return_iff', 'deck52_in_returns_after_52',
    'deck52_in_no_fewer', 'deck52_in_period', 'deck24_in_returns_after_twenty',
    'valFrom_ge', 'steer_valFrom', 'valFrom_append', 'valFrom_bits', 'elmsley',
    'deck52_steer_all', 'deck52_steer_37', 'odd_deck_5_fails',
    'valFrom_lt', 'valFrom_zero_lt', 'no_shorter_word', 'pow_bitsFuel_le', 'bits_shortest',
    'valFrom_mono_gap', 'valFrom_ge_shift', 'valFrom_inj', 'outStep_dichotomy',
    'inStep_dichotomy', 'steer_dichotomy', 'steer_word_determined', 'elmsley_unique',
    'deck52_unique', 'deck52_two_routes_at_seven']) {
    assert.equal(new RegExp(`theorem ${t}\\b`).test(src), true, `Lean states theorem ${t}`);
  }
  // guard against a real sorry / native_decide: strip all `backtick` code spans (every
  // mention in this file's prose lives inside them) so only actual tactic use can match.
  const code = src.replace(/`[^`]*`/g, '');
  assert.equal(/\bsorry\b/.test(code) || /native_decide/.test(code), false,
    'Lean source has no sorry / native_decide');

  const candidates = ['lean', join(homedir(), '.elan', 'bin', 'lean'), join(homedir(), '.nix-profile', 'bin', 'lean')];
  let leanBin = null;
  for (const c of candidates) {
    try { execSync(`${c} --version`, { stdio: 'ignore' }); leanBin = c; break; } catch { /* keep trying */ }
  }
  if (leanBin) {
    let out = '', typechecked = true;
    try {
      out = execSync(`${leanBin} ${JSON.stringify(leanFile)}`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
    } catch (e) {
      out = (e.stdout || '') + (e.stderr || '');
      typechecked = false;
    }
    assert.equal(typechecked, true, 'Lean typechecks with no errors' + (typechecked ? '' : ' — ' + out.split('\n').slice(0, 3).join(' | ')));
    const axiomLines = out.split('\n').filter((l) => /depends on axioms|does not depend on any axioms/.test(l));
    assert.equal(axiomLines.length >= 42, true, `Lean emitted axiom footprints (${axiomLines.length} lines)`);
    const badAxiom = axiomLines.find((l) => /sorryAx|Classical\.choice|native/.test(l));
    assert.equal(badAxiom, undefined, 'every theorem is [propext, Quot.sound] or tighter (no sorryAx, no Classical.choice)' + (badAxiom ? ' — ' + badAxiom : ''));
    for (const l of axiomLines) console.log('   ', l.trim());
  } else {
    console.log('  ..  lean not on PATH — static check only (run research/eight-perfect-shuffles/lean/install-lean.sh to typecheck)');
  }
}

console.log('All eight-perfect-shuffles checks passed.');
