"""2kwas: compare the certificate numbers written in the authors' Lean files with our own computation.

The Lean files are read as text only (regular expressions); nothing in them is executed.

usage: python3 -I lean_cmp.py <CubeSpectrum/Certificates.lean> <LowCube.lean> > lean_cmp.out
"""
import re
import sys
from fractions import Fraction as Fr
from math import comb


# ------------------------------------------------- the same integer-polynomial helpers as cube_check.py
def trim(p):
    p = list(p)
    while len(p) > 1 and p[-1] == 0: p.pop()
    return p
def add(p, q):
    n = max(len(p), len(q)); return trim([(p[i] if i < len(p) else 0) + (q[i] if i < len(q) else 0) for i in range(n)])
def mul(p, q):
    r = [0] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        if a:
            for j, b in enumerate(q): r[i + j] += a * b
    return trim(r)
def scal(c, p): return trim([c * a for a in p])
def ev(p, x): return sum(Fr(a) * Fr(x) ** i for i, a in enumerate(p))
def div_exact(p, q):
    p = [Fr(a) for a in p]; out = [Fr(0)] * (len(p) - len(q) + 1)
    for i in range(len(out) - 1, -1, -1):
        c = p[i + len(q) - 1] / q[-1]; out[i] = c
        for j, b in enumerate(q): p[i + j] -= c * b
    assert all(a == 0 for a in p), "not divisible"
    assert all(c.denominator == 1 for c in out)
    return trim([int(c) for c in out])
ONE_MINUS_U = [1, -1]; ONE_PLUS_U = [1, 1]
def pw(p, e):
    r = [1]
    for _ in range(e): r = mul(r, p)
    return r
def D(n, j):
    return add(add(scal(comb(n - j, 2), pw(ONE_MINUS_U, 2)), scal(j * (n - j), mul(ONE_MINUS_U, ONE_PLUS_U))),
               scal(comb(j, 2), pw(ONE_PLUS_U, 2)))
def kraw(n, k, j):
    return sum((-1) ** i * comb(k, i) * comb(n - k, j - i) for i in range(0, j + 1) if i <= k and j - i <= n - k)
def P_lambda(n, k):
    Ds = [D(n, j) for j in range(n + 1)]
    tot = [0]
    for j in range(n + 1):
        c = kraw(n, k, j)
        if c == 0: continue
        prod = [1]
        for i in range(n + 1):
            if i != j: prod = mul(prod, Ds[i])
        tot = add(tot, scal(c, prod))
    return tot
def strip(p):
    a = 0
    while p[0] == 0: p = p[1:]; a += 1
    b = 0
    while ev(p, 1) == 0: p = div_exact(p, ONE_MINUS_U); b += 1
    return a, b, p
def bernstein(q):
    d = len(q) - 1
    tot = [0]
    for i, a in enumerate(q):
        tot = add(tot, scal(a, mul([0] * i + [1], pw(ONE_PLUS_U, d - i))))
    return d, tot + [0] * (d + 1 - len(tot))


def lin_coeffs(rhs, n):
    """'(1) * f 0 + (-8) * f 1 ...' or '(1:ℝ)*f 0 + ...' -> list of n+1 integers"""
    out = [0] * (n + 1)
    for c, j in re.findall(r"\((-?\d+)(?::ℝ)?\)\s*\*\s*f\s+(\d+)", rhs):
        out[int(j)] += int(c)
    return out


cert_path, low_path = sys.argv[1], sys.argv[2]
ok_all = True

# ------------------------------------------------- iis:2611.00267, CubeSpectrum/Certificates.lean
src = open(cert_path, encoding="utf-8").read()
print("=== iis:2611.00267  CubeSpectrum/Certificates.lean")
# denominators
den = re.search(r"def denom \(u : ℝ\) : ℕ → ℝ\n(.*?)\n\n", src, re.S).group(1)
ok_den = True
for line in den.splitlines():
    m = re.match(r"\s*\|\s*(\d+|_)\s*=>\s*(.*)", line)
    j = 8 if m.group(1) == "_" else int(m.group(1))
    a = re.search(r"(\d+) \* \(1-u\)\^2", m.group(2)); b = re.search(r"(\d+) \* \(\(1-u\)\*\(1\+u\)\)", m.group(2))
    c = re.search(r"(\d+) \* \(1\+u\)\^2", m.group(2))
    got = (int(a.group(1)) if a else 0, int(b.group(1)) if b else 0, int(c.group(1)) if c else 0)
    ok_den &= got == (comb(8 - j, 2), j * (8 - j), comb(j, 2))
print("denom u j = C(8-j,2)(1-u)^2 + j(8-j)(1-u)(1+u) + C(j,2)(1+u)^2 for j = 0..8:", ok_den)
ok_all &= ok_den
for m in range(9):
    lay = re.search(r"private lemma layer%d \(f : ℕ → ℝ\) : layer %d %d f 0 = (.*?) := by" % (m, 8 - m, m), src)
    ok_lay = lin_coeffs(lay.group(1), 8) == [kraw(8, m, j) for j in range(9)]
    cl = re.search(r"lemma cleared%d .*?:\n\s*common u \* layer %d %d \(kernel u\) 0 = (.*?) := by" % (m, 8 - m, m), src, re.S).group(1)
    pl = P_lambda(8, m)
    if m < 8:
        hd = re.match(r"u\^(\d+) \* \(1-u\^2\) \* \((.*)\)$", cl)
        terms = re.findall(r"(\d+) \* \(u\^2\)\^(\d+) \* \(1-u\^2\)\^(\d+)", hd.group(2))
        d = int(terms[0][2])
        lean_c = [int(c) for c, i, e in terms]
        ok_shape = int(hd.group(1)) == m and all(int(i) == t and int(e) == d - t for t, (c, i, e) in enumerate(terms))
        rest = div_exact(pl[m:], mul(ONE_MINUS_U, ONE_PLUS_U))
        dz, ours = bernstein(rest[0::2])
        ok = ok_lay and ok_shape and dz == d and ours == lean_c and all(x > 0 for x in lean_c)
        print("m=%d  layer coefficients = Krawtchouk: %s;  cleared%d: u^%s (1-u^2) * sum of %d Bernstein terms in z = u^2, "
              "coefficients equal ours and positive: %s" % (m, ok_lay, m, hd.group(1), len(terms), ok))
    else:
        ok = ok_lay and cl.strip() == "505774080 * u^8 * (1-u^2) * cubic (u^2)"
        print("m=8  layer coefficients = Krawtchouk: %s;  cleared8 is '505774080 * u^8 * (1-u^2) * cubic (u^2)': %s" % (ok_lay, ok))
    ok_all &= ok
print("cubic z = 4z^3-190z^2+791z-245 in the file:", "def cubic (z : ℝ) := 4*z^3-190*z^2+791*z-245" in src)

# ------------------------------------------------- iis:2611.00275, LowCube.lean
src = open(low_path, encoding="utf-8").read()
print()
print("=== iis:2611.00275  LowCube.lean")
dm = re.search(r"def D \(n j : ℕ\) \(u : ℝ\) : ℝ :=\n(.*?)\n\n", src, re.S).group(1)
print("D n j u as printed:", " ".join(dm.split()))
count = 0
for n in range(2, 8):
    blk = re.search(r"namespace Dim%d\n(.*?)\nend Dim%d" % (n, n), src, re.S).group(1)
    for k in range(n + 1):
        lay = re.search(r"private lemma lin%d \(f : ℕ → ℝ\) : layer %d %d f 0 = (.*?) := by" % (k, n - k, k), blk)
        ok_lay = lin_coeffs(lay.group(1), n) == [kraw(n, k, j) for j in range(n + 1)]
        ce = re.search(r"private lemma pos%d .*?have cert : P u \* layer %d %d \(K %d u\) 0 = u\^(\d+)\*\(1-u\)\^(\d+)\*\((.*?)\) := by"
                       % (k, n - k, k, n), blk, re.S)
        a, b = int(ce.group(1)), int(ce.group(2))
        terms = re.findall(r"(\d+)\*u\^(\d+)\*\(1-u\)\^(\d+)", ce.group(3))
        d = int(terms[0][2])
        lean_c = [int(c) for c, i, e in terms]
        ok_shape = all(int(i) == t and int(e) == d - t for t, (c, i, e) in enumerate(terms))
        a0, b0, q = strip(P_lambda(n, k))
        d0, ours = bernstein(q)
        ok = ok_lay and ok_shape and (a, b, d) == (a0, b0, d0) and lean_c == ours and all(x > 0 for x in lean_c)
        count += 1
        ok_all &= ok
        if not ok:
            print("MISMATCH n=%d k=%d: lean a=%d b=%d d=%d %s; ours a=%d b=%d d=%d %s" % (n, k, a, b, d, lean_c, a0, b0, d0, ours))
    print("n=%d: all %d layers: Krawtchouk coefficients and certificate (a, b, d, Bernstein coefficients) equal ours: %s"
          % (n, n + 1, ok_all))
print("certificates compared:", count)
print("ALL EQUAL:", ok_all)
