#!/usr/bin/env python3
"""Stage 2c: rigorous "no small integer polynomial vanishes at e + pi" bounds via LLL.

Claim proved for each (d, H) reported:
    there is no nonzero c = (c_0, ..., c_d) in Z^{d+1} with ||c||_2 <= H and sum c_i (e+pi)^i = 0.

Proof certificate (all integer / exact rational arithmetic):
  * alpha = e + pi lies in [L, U] (MPFR directed rounding, compute_digits.py). We widen to dyadic
    L' <= L, U' >= U with t bits, so alpha^i in [L'^i, U'^i] (alpha > 0).
  * a_i = floor(L'^i * 2^s) and delta_i = ceil((U'^i - L'^i) 2^s) + 1  >=  |a_i - alpha^i 2^s|.
  * Lattice rows b_i = (e_i, a_i), i = 0..d. For c as above, v = sum c_i b_i = (c, sum c_i a_i), and
    |sum c_i a_i| = |sum c_i (a_i - alpha^i 2^s)| <= ||c|| ||delta||, so ||v||^2 <= H^2 (1 + ||delta||^2).
  * For ANY basis (b'_i) of the lattice, every nonzero lattice vector has norm >= min_i ||b'_i*||
    (Gram-Schmidt). We take b' = LLL(b) from FLINT, verify b' = T b with T integral and |det T| = 1,
    and compute ||b'_i*||^2 = det(G_{i+1}) / det(G_i) exactly from leading minors of the Gram matrix.
  * Hence if H^2 (1 + ||delta||^2) < min_i ||b'_i*||^2, no such c exists. We report the largest
    H for which this holds:  H_max^2 = min ||b'*||^2 / (1 + ||delta||^2)  (strict inequality).

Usage: python algebraic_bound.py D d s [d s ...]     (D selects data/enclosure_*_D.txt)
"""
import sys, os, json, time, math
import gmpy2
from gmpy2 import mpz
import flint

HERE = os.path.dirname(os.path.abspath(__file__)); DATA = os.path.join(HERE, "..", "data")

def read_dyadic(path):
    with open(path) as f:
        line = f.readline().strip(); k = int(f.readline())
        m = mpz(line[4:], 16) if line.startswith("hex:") else mpz(line)
    return m, k   # value m * 2^k

def run(D, d, s):
    mL, kL = read_dyadic(os.path.join(DATA, f"enclosure_lower_{D}.txt"))
    mU, kU = read_dyadic(os.path.join(DATA, f"enclosure_upper_{D}.txt"))
    t = s + 4 * d + 64                       # working fraction bits
    # L' = floor(L 2^t)/2^t, U' = ceil(U 2^t)/2^t
    def scaled_floor(m, k):  # floor(m 2^k 2^t)
        e = k + t
        return m << e if e >= 0 else m >> (-e)
    Ln = scaled_floor(mL, kL)
    Un = scaled_floor(mU, kU) + 1
    assert Ln < Un
    a = []; delta = []
    for i in range(d + 1):
        lo = Ln ** i; hi = Un ** i            # L'^i = lo / 2^{t i}
        sh = t * i - s
        width = hi - lo                       # (U'^i - L'^i) 2^{t i}
        if sh >= 0:
            ai = lo >> sh                     # floor(L'^i 2^s)
            di = (width >> sh) + 2            # >= ceil(width 2^s / 2^{ti}) + 1
        else:                                 # only i = 0: exact
            ai = lo << (-sh); di = (width << (-sh)) + 2
        a.append(ai); delta.append(di)
    Delta2 = sum(x * x for x in delta)
    n = d + 1
    rows = [[1 if j == i else 0 for j in range(n)] + [int(a[i])] for i in range(n)]
    B = flint.fmpz_mat(rows)
    t0 = time.time()
    Bp, T = B.lll(transform=True)
    t1 = time.time()
    assert T * B == Bp, "transform check failed"
    assert abs(T.det()) == 1, "transform not unimodular"
    G = Bp * Bp.transpose()
    # leading principal minors
    dets = [flint.fmpz(1)]
    for k in range(1, n + 1):
        sub = flint.fmpz_mat([[G[i, j] for j in range(k)] for i in range(k)])
        dets.append(sub.det())
    gs2 = [flint.fmpq(dets[k + 1], dets[k]) for k in range(n)]
    m2 = min(gs2)
    Hmax2 = m2 / flint.fmpq(int(1 + Delta2))        # need H^2 < Hmax2
    log10H = 0.5 * (math.log10(int(Hmax2.p)) - math.log10(int(Hmax2.q)))
    # exact floor of sqrt for a clean statement: largest integer H with H^2 < Hmax2
    Hint = gmpy2.isqrt(mpz(int(Hmax2.p)) // mpz(int(Hmax2.q)))
    while Hint * Hint * int(Hmax2.q) >= int(Hmax2.p):
        Hint -= 1
    # first LLL vector: the "best candidate" relation (not a relation, just the shortest found)
    first = [int(Bp[0, j]) for j in range(n)]
    return {"D_enclosure_digits": D, "degree": d, "scale_bits_s": s, "lll_seconds": round(t1 - t0, 2),
            "log10_Hmax": round(log10H, 3), "H_proved_euclidean_norm_at_least_excluded": str(Hint) if Hint.num_digits() < 60 else f"~10^{log10H:.2f}",
            "log2_Delta": round(math.log2(int(Delta2)) / 2, 3),
            "shortest_lll_vector_log10_norm": round(0.5 * math.log10(sum(x*x for x in first)), 3),
            "residual_bits_of_shortest": int(abs(first[-1])).bit_length()}

if __name__ == "__main__":
    D = int(sys.argv[1]); args = list(map(int, sys.argv[2:]))
    out = []
    for d, s in zip(args[0::2], args[1::2]):
        r = run(D, d, s); out.append(r); print(json.dumps(r), flush=True)
    fn = os.path.join(DATA, "algebraic_bounds.jsonl")
    with open(fn, "a") as f:
        for r in out: f.write(json.dumps(r) + "\n")
