#!/usr/bin/env python3
"""usage: python3 verify.py certificate.json
Checks, by exhaustive enumeration with integer arithmetic only, that on the given
traversable Ferrers board F the distributions of Destop_F (and of Ascbot_F) over
Av_F(231+sigma) and Av_F(312+sigma) differ, so no statistic-preserving bijection exists."""
import sys, json
from itertools import permutations, combinations
from collections import Counter

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

def main():
    if len(sys.argv) != 2: fail("usage")
    try:
        C = json.load(open(sys.argv[1]))
        sigma = C["sigma"]; lam = C["board_row_lengths_bottom_to_top"]
        fib = C["fibre_destop_set"]
        c231 = C["claimed_fibre_size_avoiding_231_plus_sigma"]
        c312 = C["claimed_fibre_size_avoiding_312_plus_sigma"]
        wit = C["witness_traversal_containing_231_plus_sigma"]
        wrows = C["witness_occurrence_rows"]
    except Exception as e:
        fail("bad certificate: %r" % (e,))
    isint = lambda x: isinstance(x, int) and not isinstance(x, bool)
    for L in (sigma, lam, fib, wit, wrows):
        if not isinstance(L, list) or not all(isint(x) for x in L): fail("lists of ints required")
    if not (isint(c231) and isint(c312)): fail("counts must be ints")
    m = len(sigma)
    if sorted(sigma) != list(range(1, m + 1)): fail("sigma is not a permutation")
    k = len(lam)
    if k == 0 or k > 9: fail("board size out of supported range (1..9)")
    # partition, traversable
    if any(lam[i] < lam[i + 1] for i in range(k - 1)) or lam[-1] <= 0: fail("not a partition")
    if lam[0] != k or any(lam[i] < k - i for i in range(k)): fail("board not traversable")
    # patterns: direct sums
    p231 = [2, 3, 1] + [x + 3 for x in sigma]
    p312 = [3, 1, 2] + [x + 3 for x in sigma]
    # separators: after row i (1-based) iff i is the last row of a run of equal parts
    sep = [i == k - 1 or lam[i] != lam[i + 1] for i in range(k)]  # 0-based row i

    def in_board(row, col):  # 1-based
        return 1 <= row <= k and 1 <= col <= lam[row - 1]

    def destop(t):
        return frozenset(t[i] for i in range(k - 1) if not sep[i] and t[i] > t[i + 1])

    def ascbot(t):
        return frozenset(t[i] for i in range(k) if sep[i] or t[i] < t[i + 1])

    def occurrence(t, rows, pat):
        """rows: increasing 1-based rows. The 1s (r, t[r]) form a submatrix of F (all chosen
        rows x chosen columns inside F) that equals M(pat) (1s at (i, pat(i)))."""
        cols = sorted(t[r - 1] for r in rows)
        if not all(in_board(r, c) for r in rows for c in cols): return False
        return all(cols.index(t[r - 1]) + 1 == pat[j] for j, r in enumerate(rows))

    def contains(t, pat):
        return any(occurrence(t, rows, pat) for rows in combinations(range(1, k + 1), len(pat)))

    travs = [t for t in permutations(range(1, k + 1)) if all(t[i] <= lam[i] for i in range(k))]
    # sanity: each is a genuine traversal (one 1 per row and per column, all cells in F)
    for t in travs:
        if not all(in_board(i + 1, t[i]) for i in range(k)): fail("internal")
    D = {}; A = {}
    for name, pat in (("231", p231), ("312", p312)):
        av = [t for t in travs if not contains(t, pat)]
        D[name] = Counter(destop(t) for t in av)
        A[name] = Counter(ascbot(t) for t in av)
        print("pattern", pat, "traversals", len(travs), "avoiders", len(av))
    # a statistic-preserving bijection exists iff the two distributions coincide
    if D["231"] == D["312"]: fail("Destop_F distributions coincide on this board")
    if len(sigma) >= 1 and A["231"] == A["312"]:
        print("note: Ascbot_F distributions coincide (Conjecture 17 not refuted by this board)")
    elif len(sigma) >= 1:
        print("Ascbot_F distributions also differ (Conjecture 17 refuted too)")
    # check the specific claims in the certificate
    f = frozenset(fib)
    if D["231"][f] != c231 or D["312"][f] != c312: fail("fibre sizes differ from certificate: %d, %d" % (D["231"][f], D["312"][f]))
    if c231 == c312: fail("named fibre has equal sizes")
    wt = tuple(wit)
    if wt not in travs: fail("witness is not a traversal of F")
    if destop(wt) != f: fail("witness not in the named fibre")
    if len(wrows) != len(p231) or sorted(set(wrows)) != wrows or not all(1 <= r <= k for r in wrows):
        fail("bad occurrence rows")
    if not occurrence(wt, wrows, p231): fail("witness occurrence invalid")
    if contains(wt, p312): fail("witness contains 312+sigma")
    print("fibre Destop_F = %s: %d avoiders of %s vs %d avoiders of %s" % (sorted(f), c231, p231, c312, p312))
    print("VERIFIED")

main()
