#!/usr/bin/env python3
"""Independent checker: does certificate.json refute Conjecture 16 of Burstein
(arXiv:2306.08065), i.e. exhibit a traversable Ferrers board F and a permutation
sigma for which NO Destop_F-preserving bijection Av_F(231+sigma) -> Av_F(312+sigma)
exists?  Such a bijection exists iff the two multisets {Destop_F(tau)} coincide,
so we recompute both full distributions by exhaustive enumeration.

Integer arithmetic only.  Usage: python3 checker.py certificate.json
"""
import sys
import json
from itertools import combinations
from collections import Counter

MAX_K = 9  # exhaustive enumeration bound (k! traversals at most)


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


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


def int_list(x, name):
    if not isinstance(x, list) or not all(is_int(v) for v in x):
        fail("%s must be a list of integers" % name)
    return list(x)


def is_perm(p):
    return sorted(p) == list(range(1, len(p) + 1))


def direct_sum(s, t):
    return list(s) + [v + len(s) for v in t]


# ---------- board ----------
def traversals(lam):
    """All permutations tau of [k] with tau(i) <= lam_i (rows bottom-up, 1-based)."""
    k = len(lam)
    out = []
    cur = []
    used = [False] * (k + 2)

    def rec(i):
        if i == k:
            out.append(tuple(cur))
            return
        for c in range(1, lam[i] + 1):
            if not used[c]:
                used[c] = True
                cur.append(c)
                rec(i + 1)
                cur.pop()
                used[c] = False

    rec(0)
    return out


def separator_positions(lam):
    """Set of 1-based positions i such that a separator follows tau(i):
    ends of maximal runs of equal row lengths (always includes k)."""
    k = len(lam)
    return set(i for i in range(1, k + 1) if i == k or lam[i - 1] != lam[i])


def destop(tau, seps):
    k = len(tau)
    return frozenset(tau[i - 1] for i in range(1, k)
                     if i not in seps and tau[i - 1] > tau[i])


def ascbot(tau, seps):
    k = len(tau)
    s = set()
    for i in range(1, k + 1):
        if i in seps:
            s.add(tau[i - 1])
        elif tau[i - 1] < tau[i]:
            s.add(tau[i - 1])
    return frozenset(s)


# ---------- containment, method A: literal definition ----------
def occurrence_ok(lam, tau, rows, pat):
    """rows: increasing 1-based rows. True iff the 1s of tau in these rows form a
    submatrix of F (every chosen row x chosen column cell lies in F) equal to M(pat)."""
    m = len(pat)
    if len(rows) != m:
        return False
    cols = [tau[r - 1] for r in rows]
    for r in rows:
        for c in cols:
            if c > lam[r - 1]:
                return False
    sc = sorted(cols)
    # a-th chosen row (from bottom) must have its 1 in the pat(a)-th chosen column
    for a in range(m):
        if sc.index(cols[a]) + 1 != pat[a]:
            return False
    return True


def contains_A(lam, tau, pat):
    k = len(tau)
    for rows in combinations(range(1, k + 1), len(pat)):
        if occurrence_ok(lam, tau, rows, pat):
            return True
    return False


# ---------- containment, method B: independent (maximal rectangles) ----------
def classical_contains(word, pat):
    m = len(pat)
    n = len(word)
    if m == 0:
        return True
    # backtracking embedding
    def rec(pos, chosen):
        j = len(chosen)
        if j == m:
            return True
        for p in range(pos, n - (m - j) + 1):
            v = word[p]
            ok = True
            for a in range(j):
                if (chosen[a] < v) != (pat[a] < pat[j]):
                    ok = False
                    break
            if ok and rec(p + 1, chosen + [v]):
                return True
        return False
    return rec(0, [])


def contains_B(lam, tau, pat):
    """An occurrence with top row r lies in rows <= r and columns <= lam_r, and that
    whole rectangle is inside F (lam weakly decreasing)."""
    k = len(tau)
    if len(pat) == 0:
        return True
    for r in range(1, k + 1):
        w = [tau[i] for i in range(r) if tau[i] <= lam[r - 1]]
        if classical_contains(w, pat):
            return True
    return False


def distributions(lam, pats):
    """For each pattern: (Counter of Destop_F over avoiders, Counter of Ascbot_F, #avoiders)."""
    seps = separator_positions(lam)
    T = traversals(lam)
    res = []
    for pat in pats:
        d = Counter()
        a = Counter()
        n = 0
        for tau in T:
            cA = contains_A(lam, tau, pat)
            cB = contains_B(lam, tau, pat)
            if cA != cB:
                fail("internal: containment methods disagree on %r, pattern %r" % (tau, pat))
            if not cA:
                n += 1
                d[destop(tau, seps)] += 1
                a[ascbot(tau, seps)] += 1
        res.append((d, a, n))
    return T, res


def conjugate(lam):
    return [sum(1 for x in lam if x >= j) for j in range(1, lam[0] + 1)]


def inverse(p):
    q = [0] * len(p)
    for i, v in enumerate(p):
        q[v - 1] = i + 1
    return q


# ---------- self tests against the paper ----------
def self_test():
    # Example 15 of the paper: F = (6,6,5,5,3,3), tau = 465231, separation 46|52|31|
    lam = [6, 6, 5, 5, 3, 3]
    tau = (4, 6, 5, 2, 3, 1)
    seps = separator_positions(lam)
    if seps != {2, 4, 6}:
        fail("self-test: separators of Example 15")
    if destop(tau, seps) != frozenset({3, 5}):
        fail("self-test: Destop_F of Example 15")
    if ascbot(tau, seps) != frozenset({1, 2, 4, 6}):
        fail("self-test: Ascbot_F of Example 15")
    if direct_sum([2, 3, 1], [1]) != [2, 3, 1, 4] or direct_sum([3, 1, 2], [1]) != [3, 1, 2, 4]:
        fail("self-test: direct sum")
    # square board = classical avoidance: |Av_5(231)| = |Av_5(312)| = 42 (Catalan)
    sq = [5] * 5
    T, res = distributions(sq, [[2, 3, 1], [3, 1, 2]])
    if len(T) != 120 or res[0][2] != 42 or res[1][2] != 42:
        fail("self-test: Catalan count on square board")
    # staircase board has exactly one traversal
    if len(traversals([4, 3, 2, 1])) != 1:
        fail("self-test: staircase")


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, parse_float=lambda s: fail("float in certificate"),
                             parse_constant=lambda s: fail("non-finite constant in certificate"))
    except SystemExit:
        raise
    except Exception as e:
        fail("cannot read certificate: %r" % (e,))
    if not isinstance(cert, dict):
        fail("certificate is not a JSON object")
    keys = ["sigma", "board_row_lengths_bottom_to_top", "fibre_destop_set",
            "claimed_fibre_size_avoiding_231_plus_sigma",
            "claimed_fibre_size_avoiding_312_plus_sigma",
            "witness_traversal_containing_231_plus_sigma",
            "witness_occurrence_rows"]
    for key in keys:
        if key not in cert:
            fail("missing key %s" % key)

    self_test()

    sigma = int_list(cert["sigma"], "sigma")
    lam = int_list(cert["board_row_lengths_bottom_to_top"], "board")
    S_list = int_list(cert["fibre_destop_set"], "fibre_destop_set")
    c231 = cert["claimed_fibre_size_avoiding_231_plus_sigma"]
    c312 = cert["claimed_fibre_size_avoiding_312_plus_sigma"]
    wit = int_list(cert["witness_traversal_containing_231_plus_sigma"], "witness traversal")
    wrows = int_list(cert["witness_occurrence_rows"], "witness rows")
    if not (is_int(c231) and is_int(c312)):
        fail("claimed fibre sizes must be integers")

    # sigma
    if not is_perm(sigma):
        fail("sigma is not a permutation in one-line notation")
    p231 = direct_sum([2, 3, 1], sigma)
    p312 = direct_sum([3, 1, 2], sigma)
    print("patterns: %s and %s" % ("".join(map(str, p231)), "".join(map(str, p312))))

    # board: partition, traversable
    k = len(lam)
    if k == 0:
        fail("empty board")
    if k > MAX_K:
        fail("board too large for exhaustive check (k=%d > %d)" % (k, MAX_K))
    if any(x <= 0 for x in lam):
        fail("row lengths must be positive")
    if any(lam[i] < lam[i + 1] for i in range(k - 1)):
        fail("row lengths are not weakly decreasing (not a partition)")
    if lam[0] != k:
        fail("not traversable: lambda_1 != k")
    for i in range(1, k + 1):
        if lam[i - 1] < k + 1 - i:
            fail("not traversable: lambda_%d < k+1-%d" % (i, i))
    seps = separator_positions(lam)
    print("board lambda = %r, separators after positions %r" % (lam, sorted(seps)))

    # full enumeration
    T, res = distributions(lam, [p231, p312])
    if len(T) == 0:
        fail("board has no traversals")
    # exact count of traversals: prod over rows from the top of (lam_i - (k - i))
    prod = 1
    for i in range(1, k + 1):
        prod *= lam[i - 1] - (k - i)
    if prod != len(T):
        fail("traversal count mismatch: enumerated %d, formula %d" % (len(T), prod))
    (d1, a1, n1), (d2, a2, n2) = res
    print("traversals: %d; |Av_F(231+s)| = %d, |Av_F(312+s)| = %d" % (len(T), n1, n2))

    # the decisive fact: Destop_F distributions differ <=> no Destop_F-preserving bijection
    if d1 == d2:
        fail("Destop_F distributions over the two avoider sets coincide; no refutation")
    diff = sorted((sorted(s), d1.get(s, 0), d2.get(s, 0))
                  for s in set(d1) | set(d2) if d1.get(s, 0) != d2.get(s, 0))
    print("Destop_F fibres that differ (set, #231+s avoiders, #312+s avoiders):")
    for row in diff:
        print("   ", row)
    print("Ascbot_F distributions differ: %s" % (a1 != a2))

    # certificate's specific claims
    if len(set(S_list)) != len(S_list):
        fail("fibre_destop_set has repeated entries")
    if any(v < 1 or v > k for v in S_list):
        fail("fibre_destop_set has entries outside [k]")
    S = frozenset(S_list)
    f1 = d1.get(S, 0)
    f2 = d2.get(S, 0)
    if f1 != c231:
        fail("fibre size for 231+sigma is %d, certificate claims %d" % (f1, c231))
    if f2 != c312:
        fail("fibre size for 312+sigma is %d, certificate claims %d" % (f2, c312))
    if f1 == f2:
        fail("the named fibre has equal sizes (%d); it does not witness a difference" % f1)
    print("named fibre Destop_F = %r: %d vs %d (matches certificate)" % (sorted(S), f1, f2))

    # witness
    if len(wit) != k or not is_perm(wit):
        fail("witness is not a permutation of [k]")
    if any(wit[i] > lam[i] for i in range(k)):
        fail("witness is not a traversal of F")
    wt = tuple(wit)
    if destop(wt, seps) != S:
        fail("witness has Destop_F = %r, not the named set" % sorted(destop(wt, seps)))
    if any(r < 1 or r > k for r in wrows) or any(wrows[i] >= wrows[i + 1] for i in range(len(wrows) - 1)):
        fail("witness_occurrence_rows must be strictly increasing rows in [1,k]")
    if not occurrence_ok(lam, wt, wrows, p231):
        fail("witness rows do not form an occurrence of 231+sigma inside F")
    if contains_A(lam, wt, p312) or contains_B(lam, wt, p312):
        fail("witness contains 312+sigma (certificate says it avoids it)")
    print("witness %r: occurrence of 231+sigma at rows %r, avoids 312+sigma" % (wit, wrows))

    # robustness to the row/column reading (informational unless it breaks the claim):
    # reading the traversal by columns amounts to conjugating F and inverting the patterns.
    lamc = conjugate(lam)
    _, resc = distributions(lamc, [inverse(p231), inverse(p312)])
    col_differs = resc[0][0] != resc[1][0]
    print("column-reading convention (conjugate board %r): Destop distributions differ: %s"
          % (lamc, col_differs))
    if not col_differs:
        fail("under the column-reading convention the distributions coincide; "
             "the refutation depends on an ambiguous convention")

    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
