"""Check the width-eleven Padé / Bézout identities by integer multiplication.

No third-party modules are used in check mode. In generate mode FLINT first
produces the auxiliary coefficients. Check mode also compares 17 terms with
an independent permanent dynamic program on subsets of [n].
"""
import argparse
import hashlib
import pathlib


P = 65521
D = 353740
ROOT = pathlib.Path(__file__).resolve().parent


def read(name):
    return list(map(int, (ROOT/name).read_text(encoding="ascii").split()))


def pack(coefficients):
    if not all(0 <= a < P for a in coefficients):
        raise ValueError("coefficient outside field representation")
    return int.from_bytes(b"".join(x.to_bytes(7,"little") for x in coefficients),"little")


def unpack_integer_product(integer, count):
    data = integer.to_bytes(7*count,"little")
    return [int.from_bytes(data[i:i+7],"little") % P for i in range(0,len(data),7)]


def literal_permanent(n):
    dp = [1] + [0]*((1 << n)-1)
    for used in range((1 << n)-1):
        row = bin(used).count("1")
        for col in range(max(0,row-11), min(n,row+12)):
            bit = 1 << col
            if col != row and not (used & bit):
                dp[used | bit] += dp[used]
    return dp[-1]


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("--generate",action="store_true")
    args = cli.parse_args()
    terms = read("terms-65521.txt")
    q = read("denominator-65521.txt")
    assert len(terms)==2*D and len(q)==D+1 and q[0]==q[-1]==1
    for n in range(17):
        assert literal_permanent(n)%P==terms[n]
    if args.generate:
        from flint import nmod_poly
        Q = nmod_poly(q,P)
        numerator = (Q*nmod_poly(terms,P)).truncate(2*D)
        one, U, V = numerator.xgcd(Q)
        assert one==1
        for name,poly in [("bezout-u.txt",U),("bezout-v.txt",V)]:
            (ROOT/name).write_bytes(b"".join((str(int(a))+"\n").encode("ascii") for a in poly))
    u,v = read("bezout-u.txt"), read("bezout-v.txt")
    assert len(u)<=D and len(v)<=D
    assert 2*(D+1)*(P-1)**2 < 2**56
    Q, S = pack(q), pack(terms)
    mask = (1 << (56*2*D))-1
    numerator = unpack_integer_product((Q*S)&mask, 2*D)
    assert all(a==0 for a in numerator[D-21:])
    assert numerator[D-22] != 0
    while numerator[-1]==0:
        numerator.pop()
    assert len(numerator)-1==353718
    bezout = unpack_integer_product(pack(u)*pack(numerator)+pack(v)*Q,2*D+1)
    assert bezout[0]==1 and not any(bezout[1:])
    for label,data in [("sequence",terms),("P",numerator),("Q",q),("U",u),("V",v)]:
        norm = b"".join((str(a)+"\n").encode("ascii") for a in data)
        print(label,len(data),hashlib.sha256(norm).hexdigest(),flush=True)
    print("Passed for 17 exact subset permanents, all 707480 coefficients and the full Bezout identity.")


if __name__ == "__main__":
    main()
