#!/usr/bin/env python3
"""Exact-integer verifier for the counterexample to magnification-meta-nonadaptive-mkp-r2.

Zero floating-point arithmetic is used anywhere in this script.
Verifies:
  1. Exhaustive independent-set & zero-conflict decoding of the hypercube-derangement
     induced-matching construction across ALL N! permutations for small instances
     (C, n, m) = (2, 2, 1), (2, 2, 2), (3, 2, 1), plus capped k_max=1 on (2, 2, 2).
  2. Exact polynomial-coefficient check of the generating-function identity for I_N / N!
     (Lemma 5) for N = 2..60, and exact rational check of e < 87/32 (Lemma 6).
  3. Complete exact-integer verification of the explicit counterexample
     (C = 16, n = 10, mu = 16, k_max = 57, D = 8192) proving
         2^N * alpha(G_phi)^2 > I_N^2 * (T + 1)^N.

Prints PASS on full success, FAIL otherwise.
"""

import itertools
import math
import sys
from collections import defaultdict
from fractions import Fraction


def verify_small_exhaustive(C: int, n: int, m: int, k_max: int) -> None:
    """Exhaustively verify Lemmas 1-4 on all N! permutations for small (C, n, m, k_max)."""
    V = list(itertools.product(range(C), repeat=n))
    K = len(V)
    assert K == C**n
    # Canonical base-C bijection matching COUNTEREXAMPLE.md Section 2
    id_map = {a: sum(a[r] * (C**r) for r in range(n)) for a in V}
    assert set(id_map.values()) == set(range(K))
    N = K * m
    assert N >= 2

    # Miss-graph H = {(a, b) : a_r != b_r for all r}
    H = set()
    for a in V:
        ia = id_map[a]
        for b in V:
            if all(a[r] != b[r] for r in range(n)):
                H.add((ia, id_map[b]))
    assert len(H) == (C**n) * ((C - 1) ** n)

    # Selector phi(y) = union_{b : (a, b) not in H} A_b for y in A_a
    phi = {}
    for a in V:
        ia = id_map[a]
        Q = []
        for b in V:
            ib = id_map[b]
            if (ia, ib) not in H:
                Q.extend(range(ib * m, (ib + 1) * m))
        Q_tuple = tuple(sorted(Q))
        for y in range(ia * m, (ia + 1) * m):
            phi[y] = Q_tuple

    # Lemma 1 check
    T = m * (C**n - (C - 1) ** n)
    assert 1 <= T <= N - 1
    assert all(len(phi[y]) == T for y in range(N))

    # Lemma 2 check: exact partition into R = comb(C, 2)^n induced matchings of size 2^n
    pairs = list(itertools.combinations(range(C), 2))
    matchings = []
    for P in itertools.product(pairs, repeat=n):
        M = []
        for bits in itertools.product((0, 1), repeat=n):
            a = tuple(P[r][bits[r]] for r in range(n))
            b = tuple(P[r][1 - bits[r]] for r in range(n))
            M.append((id_map[a], id_map[b]))
        assert len(M) == 2**n
        assert len(set(M)) == 2**n
        for p1 in range(len(M)):
            assert M[p1] in H
            for p2 in range(len(M)):
                if p1 != p2:
                    assert (M[p1][0], M[p2][1]) not in H
                    # Verify A_{b'} subset phi(y) for all y in A_a
                    ia, ibp = M[p1][0], M[p2][1]
                    for y in range(ia * m, (ia + 1) * m):
                        for x in range(ibp * m, (ibp + 1) * m):
                            assert x in phi[y]
        matchings.append(M)

    R = math.comb(C, 2) ** n
    assert len(matchings) == R
    flat_edges = [e for M in matchings for e in M]
    assert len(flat_edges) == len(H) and set(flat_edges) == H

    # Enumerate all partial bijections D subset [m] x [m] of size <= k_max
    partial_bijs = []
    for j in range(k_max + 1):
        for dom in itertools.combinations(range(m), j):
            for img in itertools.permutations(range(m), j):
                partial_bijs.append(frozenset(zip(dom, img)))
    U = sum((math.comb(m, j) ** 2) * math.factorial(j) for j in range(k_max + 1))
    assert len(partial_bijs) == U
    enc = {pb: idx for idx, pb in enumerate(partial_bijs)}

    # Partition balanced permutations S into fibers B_v
    buckets = defaultdict(list)
    good_count = 0
    for pi in itertools.permutations(range(N)):
        # Compute D_{ia, ib}(pi) for all (ia, ib) in H
        D_map = {}
        balanced = True
        for ia, ib in H:
            pairs_ab = []
            lo_y = ia * m
            hi_y = lo_y + m
            base_x = ib * m
            for u in range(m):
                val = pi[base_x + u]
                if lo_y <= val < hi_y:
                    pairs_ab.append((u, val - lo_y))
            if len(pairs_ab) > k_max:
                balanced = False
                break
            D_map[(ia, ib)] = frozenset(pairs_ab)
        if not balanced:
            continue
        good_count += 1
        adv = tuple(sum(enc[D_map[e]] for e in M) % U for M in matchings)
        buckets[adv].append(pi)

    # Lemma 4 check (exact union bound on |S|)
    N_fact = math.factorial(N)
    if k_max < m:
        r = k_max + 1
        bad_ub = len(H) * (math.comb(m, r) ** 2) * math.factorial(r) * math.factorial(N - r)
        assert good_count >= N_fact - bad_ub
    else:
        assert good_count == N_fact

    # Lemma 3 check: EVERY fiber B_v has ZERO conflict edges in G_phi
    for B in buckets.values():
        for y in range(N):
            Q = phi[y]
            decoder = {}
            for pi in B:
                key = tuple(pi[x] for x in Q)
                inv_y = pi.index(y)
                if key in decoder:
                    assert decoder[key] == inv_y, f"Conflict found for C={C},n={n},m={m},y={y}"
                else:
                    decoder[key] = inv_y

    # Pigeonhole lower bound check
    max_bucket = max(len(B) for B in buckets.values())
    assert max_bucket * (U**R) >= good_count
    print(
        f"[OK] Exhaustive check (C={C}, n={n}, m={m}, k_max={k_max}): "
        f"N={N}, T={T}, R={R}, U={U}, |S|={good_count}/{N_fact}, "
        f"max_fiber={max_bucket}, conflicts=0"
    )


def verify_analytic_lemmas() -> None:
    """Verify exact generating-function identity (Lemma 5) and rational bound e < 87/32 (Lemma 6)."""
    # Lemma 5: Verify I_N (recurrence) == explicit sum == N! * [x^N](sum x^a/a! * sum x^{2j}/(2^j j!))
    I_seq = [1, 1]
    for N in range(2, 61):
        I_rec = I_seq[N - 1] + (N - 1) * I_seq[N - 2]
        I_seq.append(I_rec)
        I_sum = sum(
            math.factorial(N) // (math.factorial(N - 2 * j) * (2**j) * math.factorial(j))
            for j in range(N // 2 + 1)
        )
        assert I_rec == I_sum
        coeff = Fraction(0)
        for j in range(N // 2 + 1):
            a = N - 2 * j
            coeff += Fraction(1, math.factorial(a)) * Fraction(1, (2**j) * math.factorial(j))
        assert coeff == Fraction(I_rec, math.factorial(N))

    # Lemma 6: Exact rational series bound 1 + 1 + 1/2 + 1/6 + (1/24)*(5/4) == 87/32
    e_hi = Fraction(1) + Fraction(1) + Fraction(1, 2) + Fraction(1, 6) + Fraction(1, 24) * Fraction(5, 4)
    assert e_hi == Fraction(87, 32)
    # Termwise dominance check: (4+j)! >= 24 * 5^j (strict for j >= 2)
    for j in range(25):
        lhs = math.factorial(4 + j)
        rhs = 24 * (5**j)
        if j < 2:
            assert lhs == rhs
        else:
            assert lhs > rhs

    print("[OK] Lemma 5 (I_N/N! GF identity for N=2..60) & Lemma 6 (e < 87/32 exact rational bound)")


def verify_main_counterexample() -> None:
    """Exact-integer verification of the main counterexample (C=16, n=10, mu=16, k_max=57)."""
    C = 16
    n = 10
    mu = 16
    k_max = 57

    K = C**n
    H_size = K * ((C - 1) ** n)
    m = mu * ((C - 1) ** n)
    N = K * m
    T = m * (C**n - (C - 1) ** n)
    R = math.comb(C, 2) ** n
    D = mu * (2 ** (n - 1))

    # Exact structural identities and conjecture domain hypotheses
    assert C >= 2 and n >= 1 and m >= 1 and 0 <= k_max < m
    assert N == (16**11) * (15**10)
    assert N >= 2
    assert 1 <= T <= N - 1
    assert 2 * T < N  # Even strictly below N/2
    assert R * (2**n) == H_size
    assert N == 2 * R * D
    assert D == 8192

    # Exact Check 1: 2 * |H| * comb(m, k_max + 1)^2 <= comb(N, k_max + 1) => |S| >= N!/2
    r = k_max + 1
    c1_lhs = 2 * H_size * (math.comb(m, r) ** 2)
    c1_rhs = math.comb(N, r)
    assert c1_lhs <= c1_rhs, "Check 1 (union bound) failed!"

    # Exact Check 2: R >= 2 and N <= (R - 1)^2 => 4 * e^(2*sqrt(N)) < e^(2*R)
    assert R >= 2 and N <= (R - 1) ** 2, "Check 2 (subexponential absorption) failed!"

    # Exact computation of U = sum_{j=0}^{k_max} comb(m, j)^2 * j! (two independent methods)
    U_direct = sum((math.comb(m, j) ** 2) * math.factorial(j) for j in range(k_max + 1))
    U_rec = 1
    term = 1
    for j in range(1, k_max + 1):
        num = term * (m - j + 1) * (m - j + 1)
        assert num % j == 0
        term = num // j
        U_rec += term
    assert U_direct == U_rec
    U = U_direct

    # Exact Check 3: 32 * (64 * N)^D > 87 * U * (87 * (T + 1))^D
    # Equivalent to (64*N / (87*(T+1)))^D > (87/32) * U, which with e < 87/32 implies
    # ((2*N / (e*(T+1)))^D / (e*U))^(2R) > 1 => 2^N * alpha(G_phi)^2 > I_N^2 * (T+1)^N.
    c3_lhs = 32 * pow(64 * N, D)
    c3_rhs = 87 * U * pow(87 * (T + 1), D)
    assert c3_lhs > c3_rhs, "Check 3 (final refutation inequality) failed!"

    print(f"[OK] Main counterexample parameters: C={C}, n={n}, mu={mu}, k_max={k_max}, D={D}")
    print(f"     N = {N}")
    print(f"     T = {T}")
    print(f"     R = {R}")
    print(f"     Check 1 (tail <= 1/2): bit_len(lhs)={c1_lhs.bit_length()} <= bit_len(rhs)={c1_rhs.bit_length()}")
    print(f"     Check 2 (N <= (R-1)^2): bit_len(N)={N.bit_length()} <= bit_len((R-1)^2)={((R - 1) ** 2).bit_length()}")
    print(f"     Exact U: bit_len(U)={U.bit_length()}")
    print(
        f"     Check 3 (32*(64N)^D > 87*U*(87(T+1))^D): "
        f"bit_len(lhs)={c3_lhs.bit_length()} > bit_len(rhs)={c3_rhs.bit_length()} "
        f"(margin = {c3_lhs.bit_length() - c3_rhs.bit_length()} bits)"
    )


def main() -> int:
    try:
        verify_small_exhaustive(2, 2, 1, 1)
        verify_small_exhaustive(2, 2, 2, 2)
        verify_small_exhaustive(2, 2, 2, 1)  # Nontrivial cap k_max < m
        verify_small_exhaustive(3, 2, 1, 1)
        verify_analytic_lemmas()
        verify_main_counterexample()
    except Exception as exc:
        print(f"FAIL: {exc}")
        return 1
    print("PASS")
    return 0


if __name__ == "__main__":
    sys.exit(main())
