#!/usr/bin/env python3
"""usage: python3 verify.py certificate.json
Checks a counterexample to the general clause of Gawron-Miska-Ulas Conjecture 5.2:
two indices in the same block {2^k n + j : 0<=j<2^k} whose coefficients t_{2^k+1}(.)
have different 2-adic valuations. Exact integer arithmetic only."""
import sys, json
from math import comb


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


def nu2(x):
    assert x != 0
    x = abs(x)
    v = 0
    while x % 2 == 0:
        x //= 2
        v += 1
    return v


def coeffs_by_product(m, L):
    """Coefficients 0..L-1 of (prod_{i>=0} (1 - x^(2^i)))^m, from the definition.
    Factors with 2^i >= L are 1 mod x^L."""
    T = [0] * L
    T[0] = 1
    p = 1
    while p < L:
        for a in range(L - 1, p - 1, -1):  # multiply by (1 - x^p)
            T[a] -= T[a - p]
        p *= 2
    P = [0] * L
    P[0] = 1
    for _ in range(m):  # m-fold product, truncated
        P = [sum(P[b] * T[a - b] for b in range(a + 1)) for a in range(L)]
    return P


def coeffs_by_recursion(m, L):
    t = [0] * L
    t[0] = 1
    for n in range(1, L):
        s = 0
        for i in range(n % 2, min(m, n) + 1, 2):
            s += (-1) ** i * comb(m, i) * t[(n - i) // 2]
        t[n] = s
    return t


def main():
    if len(sys.argv) != 2:
        fail("usage: python3 verify.py certificate.json")
    try:
        with open(sys.argv[1]) as f:
            c = json.load(f)
        k, n, j1, j2 = c["k"], c["block_n"], c["j1"], c["j2"]
    except Exception as e:
        fail("cannot read certificate: %r" % (e,))
    for x in (k, n, j1, j2):
        if type(x) is not int:
            fail("k, block_n, j1, j2 must be integers")
    if k < 2:
        fail("need k >= 2")
    if n < 0:
        fail("need block_n >= 0")
    if not (0 <= j1 < j2 < 2 ** k):
        fail("need 0 <= j1 < j2 < 2^k")
    m = 2 ** k + 1
    i1, i2 = 2 ** k * n + j1, 2 ** k * n + j2
    if i2 > 5000 or m > 200:
        fail("instance too large for this verifier")
    L = i2 + 1
    P = coeffs_by_product(m, L)
    R = coeffs_by_recursion(m, L)
    if P != R:
        fail("product expansion and recursion disagree")
    a, b = P[i1], P[i2]
    if a == 0 or b == 0:
        fail("a coefficient is zero")
    va, vb = nu2(a), nu2(b)
    print("k=%d m=%d block n=%d" % (k, m, n))
    print("t_%d(%d) = %d, nu_2 = %d" % (m, i1, a, va))
    print("t_%d(%d) = %d, nu_2 = %d" % (m, i2, b, vb))
    # consistency of the redundant fields, if present
    checks = [("m", m), ("index1", i1), ("index2", i2), ("value1", str(a)),
              ("value2", str(b)), ("nu2_value1", va), ("nu2_value2", vb)]
    for key, val in checks:
        if key in c and c[key] != val:
            fail("certificate field %s = %r, recomputed %r" % (key, c[key], val))
    if va == vb:
        fail("valuations agree; not a counterexample")
    print("Same block, different 2-adic valuations: no A_{%d,nu_2(n+1)} can exist." % k)
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
