"""Certified lower bound for G (Section 3 of the paper) with interval arithmetic.

Everything that is not an exact integer is carried as an enclosure [lo, hi]:
* per-segment quantities (segments [b_k, b_{k+1}] between consecutive primes, b_0 = 1) are computed with
  arb (python-flint, 96-bit ball arithmetic) and stored as float enclosures (mid +- rad, widened);
* the per-y sums use float interval arithmetic in which every IEEE operation (+, -, *, /, all correctly
  rounded) is followed by an outward widening of 4u|value| + 1e-300, u = 2^-53;
* long sums of lower ends / upper ends use math.fsum (correctly rounded), widened by 2u|sum| + n*1e-300.

For y = num/40 and N = floor(U0/y), V = yN, the odd n <= N with U_n = max(y n, F(n)) < V give
  J/y        = sum_n int_{U_n}^{V} g(u) du/u^2,          g(u) = (Sigma(u) + gamma - log u) Pi(u),
  (1/2-eps)/y = sum_n int_{U_n}^{V} Pi(u) du/u^2.
Split each integral into the part of the segment containing U_n and whole segments above it:
  sum_n int_{U_n}^V f = sum_k c_k * seg_k(f) + c_top * top(f) + sum_n part_n(f),
with c_k = #{n : U_n in a segment below k}. On a segment, Sigma and Pi are constant and log u lies
between the logs of the segment ends, which encloses part_n; for U_n < SMALL the part is computed in arb.
Then a_{y,2} = (C/2)(1 - gamma + log(y/2)) + C (J + Q), |Q| <= eps * E(yN), E from Rosser-Schoenfeld.

Usage: python3 cert.py <U0> <amax> <J>      (run with: uv run --no-project --with python-flint --with numpy)
"""
import math
import sys
import time

import flint
import numpy as np

import ay2

flint.ctx.prec = 96
arb = flint.arb
U_ = 2.0 ** -53
TINY = 1e-300
SMALL = 10 ** 4


def widen(lo, hi, k=4):
    return lo - (np.abs(lo) * (k * U_) + TINY), hi + (np.abs(hi) * (k * U_) + TINY)


def iv_mul(alo, ahi, blo, bhi):
    c = [alo * blo, alo * bhi, ahi * blo, ahi * bhi]
    return widen(np.minimum.reduce(c), np.maximum.reduce(c))


def iv_add(alo, ahi, blo, bhi):
    return widen(alo + blo, ahi + bhi)


def iv_sum(lo, hi):
    slo, shi = math.fsum(lo.tolist()), math.fsum(hi.tolist())
    n = len(lo)
    return slo - (abs(slo) * 2 * U_ + n * TINY), shi + (abs(shi) * 2 * U_ + n * TINY)


def encl(x):
    """float enclosure of an arb ball."""
    m, r = float(x.mid()), float(x.rad())
    w = r * (1 + 4 * U_) + abs(m) * 2 * U_ + TINY
    return m - w, m + w


def precompute(primes):
    """arb enclosures for every segment k = [b_k, b_{k+1}] (b_0 = 1, b_k = p_k):
    S_k, Pi_k (constant on the segment), log b_k, segK_k = int g/u^2, segP_k = int Pi/u^2."""
    K = len(primes)
    out = {name: (np.empty(K), np.empty(K)) for name in ("S", "Pi", "logb", "segK", "segP")}
    g = arb.const_euler()
    S, Pi, lb, b = arb(0), arb(1), arb(0), 1
    for k, p in enumerate(primes.tolist()):
        lp = arb(p).log()
        ib, ip = arb(1) / b, arb(1) / p
        inv = ib - ip
        il = (lb + 1) * ib - (lp + 1) * ip
        vals = {"S": S, "Pi": Pi, "logb": lb, "segK": Pi * ((S + g) * inv - il), "segP": Pi * inv}
        for name, v in vals.items():
            lo, hi = encl(v)
            out[name][0][k], out[name][1][k] = lo, hi
        S += lp / (p - 1)
        Pi *= 1 - ip
        lb, b = lp, p
    return out


def h_enclosure(num, U0, F, b40, b, pre, primes):
    """Enclosure of h(y) = a_{y,2}/y for y = num/40, N = floor(U0/y)."""
    y = arb(num) / 40
    N = (U0 * 40) // num
    V40 = num * N                          # 40 V, exact
    n = np.arange(1, N + 1, 2, dtype=np.int64)
    U40 = np.maximum(num * n, 40 * F[n])   # 40 U_n, exact integers
    keep = U40 < V40
    n, U40 = n[keep], U40[keep]
    seg = np.searchsorted(b40, U40, side="right") - 1    # U_n in [b_seg, b_seg+1)
    iV = int(np.searchsorted(b40, np.int64(V40), side="right") - 1)
    M = len(n)
    # c_k for k <= iV: number of n with seg < k
    cnt = np.bincount(seg, minlength=iV + 1)[: iV + 1]
    c = np.concatenate(([0], np.cumsum(cnt)[:-1])).astype(np.float64)   # exact (< 2^53)
    out = {}
    g = arb.const_euler()
    V = arb(V40) / 40
    logV = V.log()
    for f in ("K", "P"):
        slo, shi = pre["seg" + f]
        # whole segments 0..iV-1
        lo, hi = iv_mul(c[:iV], c[:iV], slo[:iV], shi[:iV])
        tot = iv_sum(lo, hi)
        # top segment [b_iV, V]
        k = iV
        Sl, Pl = pre["S"], pre["Pi"]
        S_top = arb(Sl[0][k]) .union(arb(Sl[1][k]))
        P_top = arb(Pl[0][k]).union(arb(Pl[1][k]))
        bk = arb(int(b[k]))
        lbk = bk.log()
        if f == "K":
            top = P_top * ((S_top + g) * (1 / bk - 1 / V) - ((lbk + 1) / bk - (logV + 1) / V))
        else:
            top = P_top * (1 / bk - 1 / V)
        tlo, thi = encl(top * int(c[k]) if k < len(c) else top * 0)
        tot = widen(tot[0] + tlo, tot[1] + thi)
        # partial segments, one per n
        e40 = np.where(seg < iV, b40[np.minimum(seg + 1, len(b40) - 1)], V40).astype(np.float64)
        Uf = U40.astype(np.float64)                    # exact (< 2^53)
        # w = 1/U - 1/e = 40 (e40 - U40) / (U40 e40)
        dlo, dhi = widen(e40 - Uf, e40 - Uf)          # exact difference of integers < 2^53, widened anyway
        plo, phi = iv_mul(Uf, Uf, e40, e40)
        wlo, whi = widen(40 * dlo / phi, 40 * dhi / plo)
        Pilo, Pihi = pre["Pi"][0][seg], pre["Pi"][1][seg]
        if f == "P":
            qlo, qhi = iv_mul(Pilo, Pihi, wlo, whi)
        else:
            # S + gamma - log u in [S + gamma - log(end), S + gamma - log b_seg]
            glo, ghi = float(encl(g)[0]), float(encl(g)[1])
            ltop = np.where(seg < iV, pre["logb"][1][np.minimum(seg + 1, len(b) - 1)], encl(logV)[1])
            lbot = pre["logb"][0][seg]
            dglo, dghi = widen(glo - ltop, ghi - lbot)
            alo, ahi = iv_add(pre["S"][0][seg], pre["S"][1][seg], dglo, dghi)
            mlo, mhi = iv_mul(Pilo, Pihi, wlo, whi)
            qlo, qhi = iv_mul(mlo, mhi, alo, ahi)
        small = Uf < 40 * SMALL
        # exact arb for small U_n
        for idx in np.nonzero(small)[0].tolist():
            Ua = arb(int(U40[idx])) / 40
            s = int(seg[idx])
            ea = V if s == iV else arb(int(b[s + 1]))
            Sa = arb(pre["S"][0][s]).union(arb(pre["S"][1][s]))
            Pa = arb(pre["Pi"][0][s]).union(arb(pre["Pi"][1][s]))
            if f == "K":
                val = Pa * ((Sa + g) * (1 / Ua - 1 / ea) - ((Ua.log() + 1) / Ua - (ea.log() + 1) / ea))
            else:
                val = Pa * (1 / Ua - 1 / ea)
            qlo[idx], qhi[idx] = encl(val)
        part = iv_sum(qlo, qhi)
        out[f] = widen(tot[0] + part[0], tot[1] + part[1])
    # J = y * K-sum, eps = 1/2 - y * P-sum   (to arb)
    Ksum = arb(out["K"][0]).union(arb(out["K"][1]))
    Psum = arb(out["P"][0]).union(arb(out["P"][1]))
    J = y * Ksum
    eps = arb(1) / 2 - y * Psum
    C = 1 / (1 - (-g).exp())
    yN = y * N
    L = yN.log()
    Ebound = 1 / (2 * L) + 2 * (L + 1) / (yN - 1)     # Rosser-Schoenfeld, valid for yN >= 319
    assert float(yN.lower()) >= 319
    a = C / 2 * (1 - g + (y / 2).log()) + C * J
    a = a + (C * eps.upper() * Ebound).upper() * arb(0, 1)   # |Q| <= eps E(yN)
    return a / y, a, J, eps, M


def main():
    U0, amax, Jg = int(float(sys.argv[1])), int(sys.argv[2]), int(sys.argv[3])
    t0 = time.time()
    primes = ay2.primes_upto(U0 + 2000)     # a prime above every V = yN <= U0
    b = np.concatenate(([1], primes)).astype(np.int64)
    b40 = 40 * b
    pre = precompute(primes)
    # pad segment 0 = [1, 2]: precompute's index k is the segment starting at b_k (k = 0 is [1, 2])
    print(f"precompute {len(primes)} primes: {time.time() - t0:.0f}s", flush=True)
    lo = int(sys.argv[4]) if len(sys.argv) > 4 else 3
    hi = lo + 1
    F = ay2.F_table(int(U0 / (lo if amax == 0 else 4)) + 1, primes)
    if amax == -1:         # even family D'': y = 2^b (180 + j)/40, b = 2..bmax; usage: cert.py U0 -1 20 <bmax>
        return main_even(U0, pre, F, b40, b, primes, int(sys.argv[4]))
    if amax == 0:          # (2,3)-merge grid only: y = lo + j/20, j = 0..20; usage: cert.py U0 0 20 <lo>
        return main23(U0, pre, F, b40, b, primes, lo, hi)
    nums = sorted({2 ** a * (40 + j * 20 // Jg) for a in range(2, amax + 1) for j in range(Jg + 1)})
    H = {}
    for num in nums:
        hy, a, J, eps, M = h_enclosure(num, U0, F, b40, b, pre, primes)
        H[num] = hy
        print(f"y={num / 40:g}: a_y2 in {a.str(10, radius=True)}  h width {float(hy.rad()):.2e}  M={M}", flush=True)
    G = arb(0)
    for a in range(2, amax + 1):
        th = [arb(40 + j * 20 // Jg) / 40 for j in range(Jg + 1)]
        ys = [2 ** a * (40 + j * 20 // Jg) for j in range(Jg + 1)]
        lower = th[0] * H[ys[0]].lower() + sum((th[j] - th[j - 1]) * H[ys[j]].lower() for j in range(1, Jg)) \
            - th[Jg - 1] * H[ys[Jg]].upper()
        Ga = lower.lower()
        print(f"a={a}: certified lower bound {Ga.str(8)}", flush=True)
        G += Ga
    print(f"G >= {G.lower().str(8)}  (sum of certified lower bounds, a = 2..{amax}; arb endpoint, not rounded)")
    print(f"total time {time.time() - t0:.0f}s")


def main23(U0, pre, F, b40, b, primes, lo=3, hi=4):
    """G23 = (1/6) sum_j y_j (h(y_j) - h(y_{j+1})), y_j = 3 + j/20 (Section 19 / Lemma 5 of the paper).
    Linear in h with coefficients y_0/6 > 0, (y_j - y_{j-1})/6 > 0 and -y_{J-1}/6 for the last value."""
    nums = [40 * lo + (40 * (hi - lo)) * j // 20 for j in range(21)]
    H = {}
    for num in nums:
        hy, a, J, eps, M = h_enclosure(num, U0, F, b40, b, pre, primes)
        H[num] = hy
        print(f"y={num / 40:g}: a_y2 in {a.str(10, radius=True)}  h width {float(hy.rad()):.2e}  M={M}", flush=True)
    ys = [arb(n) / 40 for n in nums]
    lower = ys[0] * H[nums[0]].lower() + sum((ys[j] - ys[j - 1]) * H[nums[j]].lower() for j in range(1, 20)) \
        - ys[19] * H[nums[20]].upper()
    G23 = (lower / 6).lower()
    print(f"G23[{lo},{hi}] >= {G23.str(8)}  (arb endpoint, not rounded)")


def main_even(U0, pre, F, b40, b, primes, bmax):
    """G'' = (1/6) sum_{b=2}^{bmax} sum_j t_j (h(2^b t_j) - h(2^b t_{j+1})), t_j = (180 + j)/40 (Section 21b).
    For each b the sum is linear in h with coefficients t_0, t_j - t_{j-1} > 0 and -t_{J-1}."""
    total = arb(0)
    for bb in range(2, bmax + 1):
        nums = [2 ** bb * (180 + j) for j in range(21)]
        H = {}
        for num in nums:
            hy, a, J, eps, M = h_enclosure(num, U0, F, b40, b, pre, primes)
            H[num] = hy
        ts = [arb(180 + j) / 40 for j in range(21)]
        lower = ts[0] * H[nums[0]].lower() + sum((ts[j] - ts[j - 1]) * H[nums[j]].lower() for j in range(1, 20)) \
            - ts[19] * H[nums[20]].upper()
        g = (lower / 6).lower()
        print(f"b={bb}: certified lower bound {g.str(8)}", flush=True)
        total += g
    print(f"Geven >= {total.lower().str(8)}  (arb endpoint, not rounded)")


if __name__ == "__main__":
    main()
