#!/usr/bin/env python3
"""Stage 2b: certified continued fraction of e + pi, statistics, and the rational-denominator bound.

Input: data/enclosure_lower.txt, data/enclosure_upper.txt written by compute_digits.py.
Each holds an exact dyadic number m * 2^k with  L <= e + pi <= U  (MPFR directed rounding).

1. Compute the longest common prefix [a0; a1, ..., aK] of the continued fractions of L and U
   (divide and conquer: truncating both endpoints outward keeps the interval containing [L, U],
   and the continued-fraction cylinders are intervals, so any prefix common to the widened
   interval is common to [L, U]).
2. Independent verification: form M = prod [[a_i, 1], [1, 0]] = [[P_K, P_{K-1}], [Q_K, Q_{K-1}]]
   exactly, and check that for both endpoints the tail y with x = (P_K y + P_{K-1})/(Q_K y + Q_{K-1})
   satisfies y > 1. That alone proves every x in [L, U] has CF beginning a0, ..., aK.
3. Bound: if e + pi = p/q in lowest terms, then either p/q = P_K/Q_K (excluded by an exact check
   that P_K/Q_K is outside [L, U]) or p/q = (P_K p' + P_{K-1} q')/(Q_K p' + Q_{K-1} q') with
   y = p'/q' > 1 in lowest terms; the matrix is unimodular so q = Q_K p' + Q_{K-1} q' >= 2 Q_K + Q_{K-1}.
4. Statistics: largest partial quotients, Khinchin geometric mean, Levy constant, Gauss-Kuzmin.
"""
import sys, os, json, time, math
import gmpy2
from gmpy2 import mpz

sys.setrecursionlimit(10000)
HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "..", "data")
BASE_BITS = 4096

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 (num, den) with den > 0
    return (m << k, mpz(1)) if k >= 0 else (m, mpz(1) << (-k))

def naive_common(L, U, out):
    """Simultaneous Euclid on L = a/b < U = c/d (positive dens). Appends common terms; returns tails."""
    (a, b), (c, d) = L, U
    while b != 0 and d != 0:
        qa = a // b; qc = c // d
        if qa != qc:
            break
        # both have the same floor; is the tail defined for both (non-integers)?
        ra = a - qa * b; rc = c - qc * d
        if ra == 0 or rc == 0:
            break
        out.append(int(qa))
        # x -> 1/(x - q) reverses order
        a, b, c, d = d, rc, b, ra
    return out

def mat_prod(terms, lo, hi):
    """Product of [[a,1],[1,0]] for terms[lo:hi] as (p, pp, q, qq) = [[p, pp], [q, qq]]."""
    if hi - lo == 1:
        a = mpz(terms[lo]); return (a, mpz(1), mpz(1), mpz(0))
    if hi - lo <= 0:
        return (mpz(1), mpz(0), mpz(0), mpz(1))
    mid = (lo + hi) // 2
    A = mat_prod(terms, lo, mid); B = mat_prod(terms, mid, hi)
    return (A[0]*B[0] + A[1]*B[2], A[0]*B[1] + A[1]*B[3], A[2]*B[0] + A[3]*B[2], A[2]*B[1] + A[3]*B[3])

def tail(M, x):
    """y with x = (P y + Pp)/(Q y + Qp):  y = (Pp*den - Qp*num)/(Q*num - P*den), normalised den > 0."""
    P, Pp, Q, Qp = M; num, den = x
    yn = Pp * den - Qp * num; yd = Q * num - P * den
    if yd < 0:
        yn, yd = -yn, -yd
    return (yn, yd)

def cf_common(L, U):
    """Common CF prefix of all x in [L, U] (L < U, positive rationals as (num, den))."""
    terms = []
    while True:
        n = max(L[0].bit_length(), L[1].bit_length(), U[0].bit_length(), U[1].bit_length())
        if n <= BASE_BITS:
            naive_common(L, U, terms)
            return terms
        s = n // 2
        lo = (L[0] >> s, (L[1] >> s) + 1)      # <= L
        hi = ((U[0] >> s) + 1, U[1] >> s)      # >= U
        if lo[1] == 0 or hi[1] == 0 or lo[0] == 0:
            naive_common(L, U, terms)
            return terms
        t = cf_common(lo, hi)
        if not t:
            # widened interval too wide for even one term: take one exact step on [L, U]
            a, b = L; c, d = U
            qa = a // b; qc = c // d
            if qa != qc or a - qa*b == 0 or c - qc*d == 0:
                return terms
            t = [int(qa)]
        M = mat_prod(t, 0, len(t))
        yL = tail(M, L); yU = tail(M, U)
        # order may flip
        if yL[0] * yU[1] > yU[0] * yL[1]:
            yL, yU = yU, yL
        terms += t
        L, U = yL, yU
        if L[0] <= L[1]:      # tail not > 1 cannot happen for a valid prefix
            raise RuntimeError("invalid prefix")

def main():
    t0 = time.time()
    D = int(sys.argv[1]) if len(sys.argv) > 1 else 10_000_000
    L = read_dyadic(os.path.join(DATA, f"enclosure_lower_{D}.txt"))
    U = read_dyadic(os.path.join(DATA, f"enclosure_upper_{D}.txt"))
    assert L[0] * U[1] < U[0] * L[1], "need L < U"
    terms = cf_common(L, U)
    t1 = time.time()
    K = len(terms) - 1
    # ---- independent verification of the whole prefix in one exact step ----
    M = mat_prod(terms, 0, len(terms))
    P, Pp, Q, Qp = M
    det = P * Qp - Pp * Q
    assert abs(det) == 1
    yL = tail(M, L); yU = tail(M, U)
    ok_tails = (yL[0] > yL[1] > 0) and (yU[0] > yU[1] > 0)
    # is the last convergent P/Q itself inside [L, U]?
    conv_inside = (L[0] * Q <= P * L[1]) and (P * U[1] <= U[0] * Q)
    t2 = time.time()
    # ---- statistics ----
    a = terms
    big = sorted(((v, i) for i, v in enumerate(a) if i >= 1), reverse=True)[:15]
    logs = [math.log(v) for v in a[1:]]
    khinchin_gm = math.exp(sum(logs) / len(logs))
    qdig = Q.num_digits(10)          # may overestimate by 1
    log10Q = float(gmpy2.log10(gmpy2.mpfr(Q, 64)))
    levy_obs = log10Q * math.log(10) / K
    counts = {}
    for v in a[1:]:
        if v <= 10:
            counts[v] = counts.get(v, 0) + 1
    n = len(a) - 1
    gk = {k: {"observed": counts.get(k, 0) / n, "gauss_kuzmin": -math.log2(1 - 1 / (k + 1) ** 2)} for k in range(1, 11)}
    # 2-sigma style check: expected std of frequency
    gk_z = {k: (gk[k]["observed"] - gk[k]["gauss_kuzmin"]) / math.sqrt(gk[k]["gauss_kuzmin"] * (1 - gk[k]["gauss_kuzmin"]) / n) for k in gk}
    N_bound_lower = 2 * Q + Qp     # q >= this
    res = {
        "num_terms_certified": len(a), "K_index_of_last_term": K,
        "first_40_terms": a[:40],
        "largest_15_terms_(value,index)": big,
        "khinchin_geometric_mean": khinchin_gm, "khinchin_constant": 2.6854520010653064,
        "levy_observed_(log Q_K)/K": levy_obs, "levy_constant_pi2_over_12ln2": math.pi ** 2 / (12 * math.log(2)),
        "gauss_kuzmin_freq": gk, "gauss_kuzmin_z_scores": gk_z,
        "verification_tails_gt_1": ok_tails, "det": int(det), "last_convergent_inside_enclosure": conv_inside,
        "log10_Q_K": log10Q, "digits_of_bound_2Q_K_plus_Q_Km1": N_bound_lower.num_digits(10),
        "log10_bound": float(gmpy2.log10(gmpy2.mpfr(N_bound_lower, 64))),
        "seconds_cf": round(t1 - t0, 1), "seconds_verify": round(t2 - t1, 1),
    }
    with open(os.path.join(DATA, f"cf_terms_{D}.txt"), "w") as f:
        f.write("\n".join(map(str, a)) + "\n")
    with open(os.path.join(DATA, f"cf_result_{D}.json"), "w") as f:
        json.dump(res, f, indent=1, default=str)
    print(json.dumps(res, indent=1, default=str))
    if not ok_tails or conv_inside:
        print("VERIFICATION FAILED"); sys.exit(1)
    print(f"PROVED (given MPFR enclosure): if e+pi = p/q with q>0, gcd(p,q)=1, then q >= 2Q_K+Q_(K-1) ~ 10^{res['log10_bound']:.3f}")

if __name__ == "__main__":
    main()
