#!/usr/bin/env python3
"""Stage 2a: compute e + pi to D decimal digits by two independent methods and compare.

Method A (rigorous enclosure): GNU MPFR via gmpy2. e = exp(1) and pi = const_pi are computed
with directed rounding (round-down for a lower bound, round-up for an upper bound), and the sum
is rounded the same way. MPFR guarantees correct rounding, so  L <= e + pi <= U  exactly.
L and U are written to data/ as exact dyadic rationals (numerator, exponent) for later stages.

Method B (independent library and algorithms): mpmath (mpmath.e + mpmath.pi; mpmath computes
pi with the Chudnovsky series, MPFR with its own const_pi algorithm; e via separate code paths).

The script checks that the first D digits after the point agree across A-lower, A-upper and B.

Usage: python compute_digits.py [D]      (default D = 10_000_000)
"""
import sys, time, hashlib, math, json, os
import gmpy2
from gmpy2 import mpfr
import mpmath

D = int(sys.argv[1]) if len(sys.argv) > 1 else 10_000_000
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data")
os.makedirs(OUT, exist_ok=True)
GUARD_BITS = 256
prec = int(math.ceil(D * math.log2(10))) + GUARD_BITS
log = {"D": D, "prec_bits": prec, "versions": {"gmpy2": gmpy2.version(), "mpfr": gmpy2.mpfr_version(), "mpmath": mpmath.__version__, "mpmath_backend": mpmath.libmp.BACKEND}}

def digits_after_point(int_part_and_frac_str):
    s = int_part_and_frac_str
    assert s.startswith("5"), s[:10]
    return s[1:]

# ---------------- Method A: MPFR with directed rounding ----------------
t0 = time.time()
bounds = {}
for name, rnd in (("lower", gmpy2.RoundDown), ("upper", gmpy2.RoundUp)):
    with gmpy2.context(precision=prec, round=rnd):
        e = gmpy2.exp(mpfr(1))
        pi = gmpy2.const_pi()
        s = e + pi          # rounded in the same direction -> valid one-sided bound
    bounds[name] = s
tA = time.time() - t0
L, U = bounds["lower"], bounds["upper"]
assert L <= U
# exact dyadic form: value = m * 2^k
for name in ("lower", "upper"):
    m, k = bounds[name].as_mantissa_exp()
    with open(os.path.join(OUT, f"enclosure_{name}_{D}.txt"), "w") as f:
        f.write(f"hex:{gmpy2.mpz(m).digits(16)}\n{int(k)}\n")
# decimal digits: floor(10^D * L) and floor(10^D * U) computed exactly from the dyadics
def floor_scaled(x):
    m, k = x.as_mantissa_exp()
    m, k = gmpy2.mpz(m), int(k)
    num = m * gmpy2.mpz(10)**D
    return num << k if k >= 0 else num >> (-k)   # floor for positive values
t1 = time.time()
aL = floor_scaled(L); aU = floor_scaled(U)
sL = aL.digits(10); sU = aU.digits(10)
tconv = time.time() - t1
log["methodA_seconds"] = round(tA, 2); log["methodA_to_decimal_seconds"] = round(tconv, 2)
log["width_of_enclosure_ulps_at_1e-D"] = int(aU - aL)  # 0 or 1 means D digits pinned down (up to carry)

# ---------------- Method B: mpmath ----------------
t2 = time.time()
mpmath.mp.dps = D + 30
xB = mpmath.e + mpmath.pi
sB = mpmath.nstr(mpmath.floor(xB * mpmath.mpf(10) ** D), D + 5, strip_zeros=False).split(".")[0]
tB = time.time() - t2
log["methodB_seconds"] = round(tB, 2)

# ---------------- comparison ----------------
def first_diff(a, b):
    n = min(len(a), len(b))
    for i in range(n):
        if a[i] != b[i]:
            return i
    return None if len(a) == len(b) else n
dLU = first_diff(sL, sU); dLB = first_diff(sL, sB)
log["len_digits"] = len(sL)
log["first_diff_lower_vs_upper"] = dLU
log["first_diff_methodA_vs_methodB"] = dLB
# Certified digits: those common to floor(10^D L) and floor(10^D U)
cert = len(sL) if dLU is None else dLU
log["certified_significant_digits"] = cert
digits = sL[:cert]
with open(os.path.join(OUT, f"e_plus_pi_{D}.txt"), "w") as f:
    f.write(digits[0] + "." + digits[1:] + "\n")
log["sha256_digit_file"] = hashlib.sha256((digits[0] + "." + digits[1:] + "\n").encode()).hexdigest()
log["head"] = digits[0] + "." + digits[1:61]
log["tail_last_50_certified"] = digits[-50:]
with open(os.path.join(OUT, f"compute_digits_{D}.json"), "w") as f:
    json.dump(log, f, indent=1)
print(json.dumps(log, indent=1))
ok = (dLB is None or dLB >= cert) and cert >= D
print("RESULT:", "AGREE" if ok else "MISMATCH")
