#!/usr/bin/env python3
"""Independent checker: counterexample to the general clause of Conjecture 5.2
of Gawron-Miska-Ulas (arXiv:1703.01955).

Definitions (statement.md, checked against the arXiv TeX source):
  F_t(x) = prod_{n>=0} (1 - x^{2^n})^t = sum f_n(t) x^n,   t_m(n) = f_n(m),
  equivalently the m-fold Cauchy convolution of ((-1)^{s_2(n)})_{n>=0}.
General clause: for each k >= 2 there is a strictly increasing sequence
  (A_{k,n}) of nonnegative integers, A_{k,0}=0, with
  nu_2(t_{2^k+1}(2^k n + j)) = A_{k, nu_2(n+1)} for all n>=0, 0<=j<2^k.

A certificate (k, n, j1, j2) refutes the clause iff k>=2, n>=0,
0<=j1<j2<2^k and nu_2(t_m(2^k n+j1)) != nu_2(t_m(2^k n+j2)) with m=2^k+1,
where nu_2(0) is taken as +infinity (which is not a nonnegative integer, so a
zero coefficient also violates the clause; that case is handled, although the
certificate format requires both values to be nonzero and we enforce that).
Then no single value A_{k,nu_2(n+1)} can equal both valuations.

Only k, block_n, j1, j2 are trusted as the object; all else is recomputed with
exact Python integers by three independent methods.
"""
import json
import sys
from math import comb

MAX_INDEX = 6000   # keeps pure-Python exact arithmetic far below the time limit
MAX_K = 12


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


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


def nu2(v):
    """2-adic valuation of a nonzero integer."""
    v = abs(v)
    assert v != 0
    return (v & -v).bit_length() - 1


# Method A: literal product  prod_{2^i <= N} (1 - x^{2^i})^m  mod x^{N+1}.
# Factors with 2^i > N are 1 mod x^{N+1}.
def coeffs_product(m, N):
    a = [0] * (N + 1)
    a[0] = 1
    p = 1
    while p <= N:
        for _ in range(m):
            for n in range(N, p - 1, -1):   # multiply by (1 - x^p) in place
                a[n] -= a[n - p]
        p *= 2
    return a


# Method B: m-fold Cauchy convolution of the Prouhet-Thue-Morse sequence
# (-1)^{s_2(n)}, done as literal repeated convolution (m-1 multiplications).
def coeffs_convolution(m, N):
    tm = [-1 if bin(n).count("1") % 2 else 1 for n in range(N + 1)]
    pos = [i for i in range(N + 1) if tm[i] == 1]
    neg = [i for i in range(N + 1) if tm[i] == -1]
    a = tm[:]
    for _ in range(m - 1):
        b = [0] * (N + 1)
        for n in range(N + 1):
            s = 0
            for i in pos:
                if i > n:
                    break
                s += a[n - i]
            for i in neg:
                if i > n:
                    break
                s -= a[n - i]
            b[n] = s
        a = b
    return a


# Method C: recursion from F_m(x) = (1-x)^m F_m(x^2):
#   t_m(N) = sum_{i = N mod 2, i <= min(m,N)} (-1)^i C(m,i) t_m((N-i)/2).
def coeff_recursive(m, N, memo):
    if N == 0:
        return 1
    if N in memo:
        return memo[N]
    s = 0
    for i in range(N & 1, min(m, N) + 1, 2):
        s += (-1) ** i * comb(m, i) * coeff_recursive(m, (N - i) // 2, memo)
    memo[N] = s
    return s


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


def main():
    if len(sys.argv) != 2:
        fail("usage: python3 checker.py certificate.json")
    try:
        with open(sys.argv[1], "r", encoding="utf-8") as f:
            cert = json.load(f, object_pairs_hook=reject_dup,
                             parse_float=lambda s: fail("float in certificate: " + s),
                             parse_constant=lambda s: fail("non-finite constant: " + s))
    except SystemExit:
        raise
    except Exception as e:
        fail("cannot read/parse certificate: %r" % (e,))
    if not isinstance(cert, dict):
        fail("certificate is not a JSON object")

    for key in ("k", "m", "block_n", "j1", "j2", "index1", "index2",
                "nu2_value1", "nu2_value2"):
        if key not in cert:
            fail("missing field %r" % key)
        if not is_int(cert[key]):
            fail("field %r is not an integer" % key)
    for key in ("value1", "value2"):
        if key not in cert:
            fail("missing field %r" % key)
        if not isinstance(cert[key], str):
            fail("field %r is not a decimal string" % key)

    k, n, j1, j2 = cert["k"], cert["block_n"], cert["j1"], cert["j2"]

    # --- the object: hypotheses of the clause ---
    if k < 2:
        fail("k = %d is not >= 2" % k)
    if k > MAX_K:
        fail("k = %d too large for this checker (max %d)" % (k, MAX_K))
    if n < 0:
        fail("block_n = %d is negative" % n)
    if not (0 <= j1 < j2 < 2 ** k):
        fail("need 0 <= j1 < j2 < 2^k, got j1=%d j2=%d k=%d" % (j1, j2, k))
    m = 2 ** k + 1
    N1 = 2 ** k * n + j1
    N2 = 2 ** k * n + j2
    if N2 > MAX_INDEX:
        fail("index %d too large for this checker (max %d)" % (N2, MAX_INDEX))
    print("object: k=%d m=%d block n=%d j1=%d j2=%d -> indices %d, %d"
          % (k, m, n, j1, j2, N1, N2))
    # both indices are in the same block, hence share the same nu_2(n+1)
    assert N1 // 2 ** k == n == N2 // 2 ** k and N1 != N2

    # --- definitional sanity checks of the three implementations ---
    S = 300
    ptm = [(-1) ** bin(i).count("1") for i in range(S + 1)]
    if coeffs_product(1, S) != ptm:
        fail("internal: product for m=1 is not the Prouhet-Thue-Morse sequence")
    for mm in (1, 2, 3, 5, 9):
        A = coeffs_product(mm, S)
        if A != coeffs_convolution(mm, S):
            fail("internal: product vs convolution mismatch at m=%d" % mm)
        memo = {}
        if any(coeff_recursive(mm, i, memo) != A[i] for i in range(S + 1)):
            fail("internal: product vs recursion mismatch at m=%d" % mm)
    # Reading check: the explicit formulas (i),(ii) of Conjecture 5.2 (not
    # challenged) must hold under our reading of t_m and of the block layout.
    for kk, c1, c2 in ((2, 4, 1), (3, 5, 2)):
        L = 1500
        A = coeffs_product(2 ** kk + 1, L)
        for idx in range(L + 1):
            v = nu2(idx // 2 ** kk + 1)
            want = c1 * ((v + 1) // 2) - c2 * (v % 2)
            if A[idx] == 0 or nu2(A[idx]) != want:
                fail("reading check failed: formula for t_%d at index %d"
                     % (2 ** kk + 1, idx))
    print("sanity: 3 methods agree for small m; formulas (i),(ii) hold up to index 1500")

    # --- recompute the two coefficients three ways ---
    A = coeffs_product(m, N2)
    B = coeffs_convolution(m, N2)
    memo = {}
    vals = []
    for N in (N1, N2):
        a, b, c = A[N], B[N], coeff_recursive(m, N, memo)
        if not (a == b == c):
            fail("methods disagree at index %d: %d / %d / %d" % (N, a, b, c))
        vals.append(a)
    v1, v2 = vals
    print("t_%d(%d) = %d" % (m, N1, v1))
    print("t_%d(%d) = %d" % (m, N2, v2))

    # --- the refutation itself ---
    if v1 == 0 or v2 == 0:
        fail("a coefficient is zero; certificate format requires both nonzero")
    e1, e2 = nu2(v1), nu2(v2)
    assert v1 % 2 ** e1 == 0 and v1 % 2 ** (e1 + 1) != 0
    assert v2 % 2 ** e2 == 0 and v2 % 2 ** (e2 + 1) != 0
    print("nu_2 = %d and %d" % (e1, e2))
    if e1 == e2:
        fail("valuations coincide (%d); no contradiction with the clause" % e1)

    # --- remaining certificate fields must match the recomputation ---
    if cert["m"] != m:
        fail("m = %d but 2^k+1 = %d" % (cert["m"], m))
    if cert["index1"] != N1 or cert["index2"] != N2:
        fail("index fields %d,%d differ from 2^k n + j = %d,%d"
             % (cert["index1"], cert["index2"], N1, N2))
    for name, s, v in (("value1", cert["value1"], v1), ("value2", cert["value2"], v2)):
        if s != str(v):
            fail("%s = %r but recomputed %d" % (name, s, v))
    if cert["nu2_value1"] != e1 or cert["nu2_value2"] != e2:
        fail("nu2 fields %d,%d differ from recomputed %d,%d"
             % (cert["nu2_value1"], cert["nu2_value2"], e1, e2))

    print("Indices %d and %d lie in the same block (k=%d, n=%d) but the valuations "
          "%d != %d, so no A_{%d,%d} exists: the 'for each k>=2' clause fails at k=%d."
          % (N1, N2, k, n, e1, e2, k, nu2(n + 1), k))
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    main()
