#!/usr/bin/env python3
"""Independent checker for the claimed counterexample to Conjecture 5 of
Chen-Khare-Sahi (arXiv:2509.19649v2).  Exact rational arithmetic only.

Usage: python3 checker.py certificate.json
Prints VERIFIED as the last line and exits 0 only if every check passes.
"""
import sys
import json
import re
from fractions import Fraction
from itertools import permutations, combinations_with_replacement
from math import factorial

MAX_D = 12   # safety bounds so the brute force stays tiny
MAX_N = 6


def fail(msg):
    print("REJECTED: " + msg)
    sys.exit(1)


# ----------------------------------------------------------------- parsing
RAT = re.compile(r"^-?(0|[1-9][0-9]*)(/[1-9][0-9]*)?$")


def rat(s, name):
    if not isinstance(s, str) or not RAT.match(s):
        fail("%s is not an exact rational string: %r" % (name, s))
    return Fraction(s)


def no_dups(pairs):
    d = {}
    for k, v in pairs:
        if k in d:
            fail("duplicate JSON key %r" % k)
        d[k] = v
    return d


def is_int(x):
    return isinstance(x, int) and not isinstance(x, bool)


def partitions(d, maxparts, maxpart=None):
    """Partitions of d with at most maxparts parts, as weakly decreasing tuples
    (no padding)."""
    if maxpart is None:
        maxpart = d
    if d == 0:
        yield ()
        return
    if maxparts == 0:
        return
    for first in range(min(d, maxpart), 0, -1):
        for rest in partitions(d - first, maxparts - 1, first):
            yield (first,) + rest


def pad(p, n):
    return tuple(p) + (0,) * (n - len(p))


def majorizes(a, b):
    """a majorizes b (paper Sec. 1.2): equal size and all partial sums of a >= those of b."""
    m = max(len(a), len(b))
    a, b = pad(a, m), pad(b, m)
    if sum(a) != sum(b):
        return False
    sa = sb = 0
    for x, y in zip(a, b):
        sa += x
        sb += y
        if sa < sb:
            return False
    return True


# ------------------------------------------------------------- polynomials
# dict: exponent tuple -> Fraction (nonzero)
def padd(p, q, c=1):
    r = dict(p)
    for e, v in q.items():
        w = r.get(e, 0) + c * v
        if w == 0:
            r.pop(e, None)
        else:
            r[e] = w
    return r


def pmul(p, q):
    r = {}
    for e1, v1 in p.items():
        for e2, v2 in q.items():
            e = tuple(a + b for a, b in zip(e1, e2))
            w = r.get(e, 0) + v1 * v2
            if w == 0:
                r.pop(e, None)
            else:
                r[e] = w
    return r


def pscale(p, c):
    return {e: v * c for e, v in p.items()} if c != 0 else {}


def monomial_sym(nu, n):
    """m_nu in n variables: sum over DISTINCT permutations of nu."""
    return {e: Fraction(1) for e in set(permutations(pad(nu, n)))}


def linear(n, coeffs):
    """sum_i coeffs[i] x_i"""
    r = {}
    for i, c in coeffs.items():
        e = [0] * n
        e[i] = 1
        if c != 0:
            r[tuple(e)] = Fraction(c)
    return r


def div_exact_diff(p, a, b):
    """Exact division of p by (x_a - x_b); fails if not divisible."""
    # group by all exponents except position a, and by (e_a + e_b) handled via synthetic division in x_a
    groups = {}
    for e, v in p.items():
        key = e[:a] + (0,) + e[a + 1:]
        groups.setdefault(key, {})[e[a]] = v
    # p = sum_k x_a^k * c_k(others).  Divide by (x_a - x_b): q_{k-1} = c_k + x_b * q_k
    maxk = max((e[a] for e in p), default=0)
    by_deg = [dict() for _ in range(maxk + 1)]
    for e, v in p.items():
        key = e[:a] + (0,) + e[a + 1:]
        by_deg[e[a]][key] = v
    xb = [0] * len(next(iter(p))) if p else []
    if not p:
        return {}
    xb[b] = 1
    xb = {tuple(xb): Fraction(1)}
    res = {}
    carry = {}
    for k in range(maxk, 0, -1):
        cur = padd(by_deg[k], pmul(carry, xb))      # coefficient q_{k-1}
        for e, v in cur.items():
            ee = e[:a] + (k - 1,) + e[a + 1:]
            res[ee] = v
        carry = cur
    rem = padd(by_deg[0], pmul(carry, xb))
    if rem:
        fail("internal: inexact division by x_%d - x_%d" % (a, b))
    return res


def to_mono_basis(p, n, parts_index):
    """Express symmetric polynomial p in the m-basis; check symmetry."""
    vec = {}
    for e, v in p.items():
        key = tuple(sorted(e, reverse=True))
        if key in vec:
            if vec[key] != v:
                fail("internal: polynomial is not symmetric")
        else:
            vec[key] = v
    # every permutation must be present
    cnt = {}
    for e in p:
        key = tuple(sorted(e, reverse=True))
        cnt[key] = cnt.get(key, 0) + 1
    for key, c in cnt.items():
        if c != len(set(permutations(key))):
            fail("internal: polynomial is not symmetric (missing terms)")
        if key not in parts_index:
            fail("internal: unexpected monomial type")
    return vec


# ------------------------------------------------------ exact linear algebra
def nullspace(M):
    """Nullspace basis of square/rect matrix M (list of rows of Fractions)."""
    rows = [r[:] for r in M]
    ncols = len(rows[0])
    piv = []
    r = 0
    for c in range(ncols):
        p = None
        for i in range(r, len(rows)):
            if rows[i][c] != 0:
                p = i
                break
        if p is None:
            continue
        rows[r], rows[p] = rows[p], rows[r]
        inv = 1 / rows[r][c]
        rows[r] = [x * inv for x in rows[r]]
        for i in range(len(rows)):
            if i != r and rows[i][c] != 0:
                f = rows[i][c]
                rows[i] = [x - f * y for x, y in zip(rows[i], rows[r])]
        piv.append(c)
        r += 1
    free = [c for c in range(ncols) if c not in piv]
    basis = []
    for f in free:
        v = [Fraction(0)] * ncols
        v[f] = Fraction(1)
        for i, c in enumerate(piv):
            v[c] = -rows[i][f]
        basis.append(v)
    return basis


def inverse(M):
    k = len(M)
    A = [list(M[i]) + [Fraction(int(i == j)) for j in range(k)] for i in range(k)]
    for c in range(k):
        p = None
        for i in range(c, k):
            if A[i][c] != 0:
                p = i
                break
        if p is None:
            fail("internal: singular matrix")
        A[c], A[p] = A[p], A[c]
        inv = 1 / A[c][c]
        A[c] = [x * inv for x in A[c]]
        for i in range(k):
            if i != c and A[i][c] != 0:
                f = A[i][c]
                A[i] = [x - f * y for x, y in zip(A[i], A[c])]
    return [row[k:] for row in A]


# ------------------------------------------ Macdonald polynomials, method A
def macdonald_operator(n, d, q, t):
    """P_nu (nu partition of d, <= n parts) in n variables as eigenfunctions of
    Macdonald's operator D_n^1 = sum_i prod_{j!=i} (t x_i - x_j)/(x_i - x_j) T_{q,x_i}
    (Macdonald VI.3-4), unitriangular in the monomial basis w.r.t. dominance.
    Returns dict nu(padded) -> dict(kappa(padded) -> coeff of m_kappa)."""
    parts = [pad(p, n) for p in partitions(d, n)]
    idx = {p: i for i, p in enumerate(parts)}
    k = len(parts)
    pairs = [(a, b) for a in range(n) for b in range(a + 1, n)]
    D = [[Fraction(0)] * k for _ in range(k)]   # D[row][col]: coefficient of m_row in D m_col
    for col, nu in enumerate(parts):
        m = monomial_sym(nu, n)
        num = {}
        for i in range(n):
            Tm = {e: v * q ** e[i] for e, v in m.items()}
            term = Tm
            for j in range(n):
                if j != i:
                    term = pmul(term, linear(n, {i: t, j: -1}))
            # multiply by prod_{a<b} (x_a-x_b) / prod_{j!=i}(x_i-x_j)
            sign = 1
            for (a, b) in pairs:
                if a == i:
                    continue            # factor (x_i - x_b) cancels
                if b == i:
                    sign = -sign        # (x_a - x_i) = -(x_i - x_a) cancels with sign
                    continue
                term = pmul(term, linear(n, {a: 1, b: -1}))
            num = padd(num, term, sign)
        for (a, b) in pairs:
            num = div_exact_diff(num, a, b)
        vec = to_mono_basis(num, n, idx)
        for kappa, v in vec.items():
            D[idx[kappa]][col] = v
    eig = {nu: sum(q ** nu[i] * t ** (n - 1 - i) for i in range(n)) for nu in parts}
    if len(set(eig.values())) != k:
        fail("eigenvalues of D_n^1 are not distinct at this (q,t); operator characterization unusable")
    P = {}
    for nu in parts:
        A = [[D[r][c] - (eig[nu] if r == c else 0) for c in range(k)] for r in range(k)]
        ns = nullspace(A)
        if len(ns) != 1:
            fail("eigenspace of D_n^1 for %s is not one-dimensional" % (nu,))
        v = ns[0]
        lead = v[idx[nu]]
        if lead == 0:
            fail("eigenvector for %s has zero coefficient at m_nu" % (nu,))
        v = [x / lead for x in v]
        coeffs = {}
        for kappa in parts:
            c = v[idx[kappa]]
            if c != 0:
                if not majorizes(nu, kappa):
                    fail("eigenvector for %s is not dominance-triangular" % (nu,))
                coeffs[kappa] = c
        P[nu] = coeffs
    return P


# ------------------------------------------ Macdonald polynomials, method B
def macdonald_hall(d, q, t):
    """Monic Macdonald P_nu for ALL partitions nu of d (as symmetric functions,
    realised in d variables) from the definition: unitriangular in monomials
    w.r.t. dominance, pairwise orthogonal for
    <p_r,p_s> = delta_rs z_r prod_i (1-q^{r_i})/(1-t^{r_i}).
    Returns dict nu -> dict(kappa -> coeff), partitions unpadded tuples."""
    N = d
    parts = list(partitions(d, d))
    idx = {p: i for i, p in enumerate(parts)}
    k = len(parts)
    # power sums expanded in monomials: only the coefficient of x^kappa (kappa a partition) is needed,
    # but compute the full polynomial to stay close to the definition.
    def psum(r):
        out = {}
        for i in range(N):
            e = [0] * N
            e[i] = r
            out[tuple(e)] = Fraction(1)
        return out
    cache = {}
    def ppoly(rho):
        if rho in cache:
            return cache[rho]
        if not rho:
            res = {(0,) * N: Fraction(1)}
        else:
            res = pmul(ppoly(rho[1:]), psum(rho[0]))
        cache[rho] = res
        return res
    # p_rho = sum_kappa T[rho][kappa] m_kappa
    T = []
    for rho in parts:
        pp = ppoly(rho)
        T.append([pp.get(pad(kappa, N), Fraction(0)) for kappa in parts])
    Tinv = inverse(T)        # m_kappa = sum_rho Tinv[kappa][rho] p_rho
    def z(rho):
        out = 1
        for i in set(rho):
            mlt = rho.count(i)
            out *= i ** mlt * factorial(mlt)
        return out
    w = []
    for rho in parts:
        val = Fraction(z(rho))
        for r in rho:
            val *= (1 - q ** r) / (1 - t ** r)
        w.append(val)
    G = [[sum(Tinv[a][r] * Tinv[b][r] * w[r] for r in range(k)) for b in range(k)] for a in range(k)]
    P = {}
    for nu in parts:
        below = [kap for kap in parts if kap != nu and majorizes(nu, kap)]
        # unknown c_kap (kap in below): <m_nu + sum c m_kap, m_j> = 0 for all j in below
        if below:
            A = [[G[idx[kap]][idx[j]] for kap in below] for j in below]
            rhs = [-G[idx[nu]][idx[j]] for j in below]
            Ainv = inverse(A)
            c = [sum(Ainv[i][j] * rhs[j] for j in range(len(below))) for i in range(len(below))]
        else:
            c = []
        coeffs = {nu: Fraction(1)}
        for kap, cv in zip(below, c):
            if cv != 0:
                coeffs[kap] = cv
        P[nu] = coeffs
    # pairwise orthogonality of the whole family (this is what the definition demands)
    for a in parts:
        for b in parts:
            if a < b:
                ip = sum(ca * cb * G[idx[x]][idx[y]] for x, ca in P[a].items() for y, cb in P[b].items())
                if ip != 0:
                    fail("Hall-pairing construction: P_%s and P_%s are not orthogonal" % (a, b))
    return P


def qpoch(a, q, k):
    out = Fraction(1)
    for i in range(k):
        out *= (1 - a * q ** i)
    return out


# -------------------------------------------------------------------- main
def main():
    if len(sys.argv) != 2:
        fail("usage: python3 checker.py certificate.json")
    try:
        with open(sys.argv[1], "r") as f:
            cert = json.load(f, object_pairs_hook=no_dups)
    except SystemExit:
        raise
    except Exception as ex:
        fail("cannot read/parse certificate: %s" % ex)
    if not isinstance(cert, dict) or set(cert.keys()) != {"n", "lambda", "mu", "q", "t", "L"}:
        fail("certificate must be an object with exactly the keys n, lambda, mu, q, t, L")
    n = cert["n"]
    if not is_int(n) or not (1 <= n <= MAX_N):
        fail("n must be an integer in 1..%d" % MAX_N)

    def get_partition(name):
        p = cert[name]
        if not isinstance(p, list) or len(p) != n or not all(is_int(x) and x >= 0 for x in p):
            fail("%s must be a list of n nonnegative integers" % name)
        if any(p[i] < p[i + 1] for i in range(n - 1)):
            fail("%s is not weakly decreasing" % name)
        return tuple(p)
    lam = get_partition("lambda")
    mu = get_partition("mu")
    q = rat(cert["q"], "q")
    t = rat(cert["t"], "t")
    d = sum(lam)
    if not (1 <= d <= MAX_D):
        fail("degree out of supported range")

    # ---- item 1: clause (5) holds, parameters in range
    if sum(mu) != d:
        fail("|lambda| != |mu|")
    if lam == mu:
        fail("lambda == mu")
    if not majorizes(lam, mu):
        fail("lambda does not majorize mu")
    if not (0 < q < 1 and 0 < t < 1):
        fail("q, t must lie in the open interval (0,1)")
    print("ok: n=%d lambda=%s mu=%s, lambda majorizes mu, q=%s t=%s in (0,1)" % (n, lam, mu, q, t))

    # ---- the functional L
    parts_d = [pad(p, n) for p in partitions(d, n)]
    Lraw = cert["L"]
    if not isinstance(Lraw, dict):
        fail("L must be an object")
    expected = {",".join(map(str, p)): p for p in parts_d}
    if set(Lraw.keys()) != set(expected.keys()):
        fail("keys of L are not exactly the partitions of %d with at most %d parts" % (d, n))
    Lval = {expected[k]: rat(v, "L[%s]" % k) for k, v in Lraw.items()}

    def L(poly):
        tot = Fraction(0)
        for e, v in poly.items():
            if sum(e) != d:
                fail("internal: L applied to a polynomial of wrong degree")
            tot += v * Lval[tuple(sorted(e, reverse=True))]
        return tot

    # ---- Macdonald polynomials (two independent constructions)
    PA = macdonald_operator(n, d, q, t)
    PB_full = macdonald_hall(d, q, t)
    for nu in parts_d:
        nu_s = tuple(x for x in nu if x > 0)
        restr = {pad(kap, n): c for kap, c in PB_full[nu_s].items() if len(kap) <= n}
        if restr != PA[nu]:
            fail("Hall-pairing and operator constructions disagree for P_%s" % (nu,))
    print("ok: monic Macdonald P_nu (all %d partitions nu of %d, %d variables): Hall-pairing "
          "definition (pairwise orthogonality checked on all %d partitions) agrees with D_n^1 "
          "eigenfunction characterization" % (len(parts_d), d, n, len(PB_full)))
    # convention sanity check against the paper's formula (5.3): P_(k,0) in two variables
    for k in range(1, d + 1):
        P2 = macdonald_operator(2, k, q, t)[(k, 0)]
        for i in range(k + 1):
            want = (qpoch(q, q, k) / (qpoch(q, q, i) * qpoch(q, q, k - i))
                    * qpoch(t, q, i) * qpoch(t, q, k - i) / qpoch(t, q, k))
            got = P2.get(tuple(sorted((i, k - i), reverse=True)), Fraction(0))
            if want != got:
                fail("convention mismatch with paper formula (5.3) for P_(%d,0)" % k)
    print("ok: convention matches paper formula (5.3) for P_(k,0), k=1..%d, in two variables" % d)

    def as_poly(coeffs):
        out = {}
        for kap, c in coeffs.items():
            out = padd(out, monomial_sym(kap, n), c)
        return out

    def at_one(poly):
        return sum(poly.values(), Fraction(0))

    Plam = as_poly(PA[lam])
    Pmu = as_poly(PA[mu])
    a1, b1 = at_one(Plam), at_one(Pmu)
    if a1 == 0 or b1 == 0:
        fail("P(1,...,1) vanishes; normalization undefined")
    F = padd(pscale(Plam, 1 / a1), pscale(Pmu, 1 / b1), -1)
    if at_one(F) != 0:
        fail("internal: normalized difference does not vanish at 1")
    LF = L(F)
    print("L(P_lambda/P_lambda(1) - P_mu/P_mu(1)) = %s" % LF)
    if not LF < 0:
        fail("L is not negative on the normalized Macdonald difference")

    # ---- item 2: L >= 0 on every degree-d product of Muirhead generators
    gens = {}     # degree -> list of polynomials
    ngen = 0
    for k in range(1, d + 1):
        ps = [pad(p, n) for p in partitions(k, n)]
        g = []
        M = {}
        for p in ps:
            m = monomial_sym(p, n)
            M[p] = pscale(m, Fraction(1, len(m)))      # m_p(1) = number of monomials
            g.append(M[p])
        for a in ps:
            for b in ps:
                if a != b and majorizes(a, b):
                    g.append(padd(M[a], M[b], -1))
        gens[k] = g
        ngen += len(g)
    one = {(0,) * n: Fraction(1)}
    nprod = 0
    worst = None
    for degs in partitions(d, d):       # multiset of generator degrees
        distinct = sorted(set(degs), reverse=True)
        # for each distinct degree choose a multiset of generators of that degree
        def rec(i, acc):
            nonlocal nprod, worst
            if i == len(distinct):
                val = L(acc)
                nprod += 1
                if worst is None or val < worst:
                    worst = val
                if val < 0:
                    fail("L is negative (%s) on a product of Muirhead generators (degrees %s)" % (val, degs))
                return
            k = distinct[i]
            mult = degs.count(k)
            for combo in combinations_with_replacement(range(len(gens[k])), mult):
                cur = acc
                for gi in combo:
                    cur = pmul(cur, gens[k][gi])
                rec(i + 1, cur)
        rec(0, one)
    print("ok: L >= 0 on all %d products (multisets of the %d generators of degree 1..%d) of total "
          "degree %d; minimum value %s" % (nprod, ngen, d, d, worst))

    print("Conclusion: lambda majorizes mu (clause 5) but the specialized normalized Macdonald "
          "difference is not in M_S(R>=0) at (q,t)=(%s,%s), so clause (2') and hence clause (1) fail." % (q, t))
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
