"""Certify a lower bound for C(1) from a single-shift witness (Carneiro et al., arXiv:2404.08380).

Generalizes verify_single_shift_36_arb.py from github.com/novalis78/least-nonresidue-two-shift
to any a, c > 0 and any coefficient list r (2..64 exact rationals). Reads JSON on stdin:
  {"a": "3/10", "c": "4/5", "r": ["1", "4.815715", ...]}
and prints JSON: {"ok": bool, "c1_inv2_upper": str, "c1_lower": str, "log": str}.

Same certificate as the published verifier: exact root isolation of P on [0, m] (SymPy, rational
intervals), Arb balls for the numerator, and a trapezoid sum with a one-sided interpolation
correction for the denominator. The bound is accepted only if every ball comparison is strict.
"""
import json, sys
from fractions import Fraction
from math import comb, factorial
from flint import acb, arb, ctx, fmpq
from sympy import Poly, Rational, Symbol

def ball(v):
    v = Fraction(v); return arb(fmpq(v.numerator, v.denominator))
def to_sympy(v): return Rational(v.numerator, v.denominator)
def from_sympy(v): return Fraction(int(v.p), int(v.q))
def peval(cs, x):
    out = cs[-1]
    for c in reversed(cs[:-1]): out = out * x + c
    return out

def certify(a, c, r, panels=32768):
    log = []
    if not (a > 0 and c > 0): raise ValueError("need a > 0 and c > 0")
    if not (2 <= len(r) <= 64): raise ValueError("need 2..64 coefficients")
    ctx.prec = 200
    h, m = 1 + a, c / a
    n = len(r)
    d = [Fraction(0)] + [sum(r[j] * comb(j, k) * 2**k * (-1)**(j - k) for j in range(k, n)) for k in range(n)]
    u = Symbol("u")
    P = Poly(sum(to_sympy(d[k]) * u**k / factorial(k) for k in range(1, n + 1)), u)
    if P.is_zero: raise ValueError("P vanishes identically")
    if P.eval(to_sympy(m)) == 0: raise ValueError("P(m) = 0; perturb the witness")
    roots = P.intervals(inf=0, sup=to_sympy(m), eps=Rational(1, 10**30))
    points = [ball(0)]
    for (lo, hi), mult in roots:
        if lo == hi == 0: continue
        if mult != 1: raise ValueError("multiple root of P in (0, m); perturb the witness")
        if not (0 < lo <= hi < to_sympy(m)): raise ValueError("root interval not inside (0, m)")
        points.append(ball(from_sympy(lo)).union(ball(from_sympy(hi))))
    points.append(ball(m))
    log.append(f"interior roots of P on (0, m): {len(points) - 2}")
    tc = [ball(sum(d[k] / h**(k - j + 1) for k in range(j, n + 1)) / factorial(j)) for j in range(n + 1)]
    tails = [(-ball(h) * p).exp() * peval(tc, p) for p in points]
    penalty = sum(abs(x - y) for x, y in zip(tails, tails[1:]))
    num = 2 * arb.pi() * ball(a) * ball(c).exp() * (tails[-1] - penalty)
    if not num > 0: raise ValueError("numerator not certified positive")
    L = arb.pi() / 2; step = L / panels
    co = [ball(v) for v in r]
    mod = lambda z: abs(peval(co, z))
    trap = (mod(acb(1)) + mod(acb(-1))) / 2
    for j in range(1, panels):
        trap += mod(acb(0, -2 * j * step).exp())
    trap *= step
    K = ball(sum(4 * j * j * abs(v) for j, v in enumerate(r)))
    corr = L * K * step**2 / 12
    den = trap + corr
    if not den > 0: raise ValueError("denominator not certified positive")
    U = (den / num) ** 2
    lower = 1 / U.sqrt()
    log += [f"scaled numerator: {num}", f"trapezoid sum: {trap}", f"one-sided correction: {corr}", f"upper bound for C(1)^-2: {U}", f"so C(1) > {lower}"]
    # report decimal values that are certified: round U up, round the C(1) bound down
    # directed rounding with exact rationals: U rounded up, the C(1) bound rounded down (10 decimals)
    man, exp = U.upper().man_exp()
    u_up = Fraction(int(man)) * (Fraction(2) ** int(exp))
    D = 10**10
    us = -((-u_up * D).numerator // (-u_up * D).denominator)  # ceil
    X = Fraction(D * D) / u_up
    from math import isqrt
    q = isqrt(X.numerator // X.denominator)
    return f"{us / D:.10f}", f"{q // D}.{q % D:010d}", "\n".join(log)


# ---------------------------------------------------------------------------------------------
# Family "two-shift" (optionally with Gaussian corrections). Adapted from the five-Gaussian verifier
# written by an agent working with L. Lopin (verify_five_gaussian_bound.py), itself built on the
# archived two-shift certificate (check_arb.py, https://doi.org/10.5281/zenodo.24408857).
# Every tail bound below holds for any parameters in the family; the integration ranges only
# affect how tight the enclosures are, never their validity. Wide enclosures make a bound fail.
def _poly(z, cs):
    v = cs[-1]
    for b in reversed(cs[:-1]):
        v = v * z + b
    return v


def certify_two_shift(scale_s, shifts_s, rows_s, gaussians_s):
    from flint import acb, arb, ctx, fmpq
    ctx.prec = 128
    log = []
    tol = arb("1e-14")
    scale = arb(scale_s)
    c, c0 = arb(shifts_s[0]), arb(shifts_s[1])
    if not (scale > 0 and c > 0 and c0 == 0):
        raise ValueError("need scale > 0 and shifts [c, 0] with c > 0")
    if Fraction(shifts_s[0]) > 3:
        raise ValueError("need c <= 3")
    left, right = [[arb(b) for b in row] for row in rows_s]
    eps2 = arb(fmpq(1, 10**24))
    # ---- base numerator N
    coeff = [b / factorial(2 * n - 1) for n, b in enumerate(left, 1)]

    def correction(u, analytic):
        y = u * _poly(u * u, coeff)
        return (-(1 + scale) * u).exp() * (y + (y * y + eps2).sqrt(analytic=analytic))

    full = arb(0)
    for shift, row in [(c, left), (c0, right)]:
        full += 2 * scale * shift.exp() * sum(b / (1 + scale) ** (2 * n) for n, b in enumerate(row, 1))
    integral = acb.integral(correction, 0, c / scale, abs_tol=tol, rel_tol=tol)
    base_n = (full - 2 * scale * c.exp() * integral.real).lower()
    # ---- base norm D
    i = acb(0, 1)

    def H(z):
        v = 1 / (1 + i * z) ** 2
        return v * (_poly(v, left) + (-i * c * z / scale).exp() * _poly(v, right))

    def magnitude(z, analytic):
        return (H(z) * H(-z) + eps2).sqrt(analytic=analytic)

    stops = [0, 1, 2, 4, 8, 16, 32, 64]
    finite = arb(0)
    for lo, hi in zip(stops, stops[1:]):
        panels = max(32, 4 * (hi - lo))
        step = arb(hi - lo) / panels
        for j in range(panels):
            finite += acb.integral(magnitude, lo + j * step, lo + (j + 1) * step, abs_tol=tol, rel_tol=tol).real
    end = arb(stops[-1])
    tail = sum(abs(b) / ((2 * n - 1) * end ** (2 * n - 1)) for row in (left, right) for n, b in enumerate(row, 1))
    base_d = ((finite + tail) / arb.pi()).upper()
    log.append(f"base two-shift witness: N >= {base_n}, D <= {base_d}")
    if not gaussians_s:
        n_lower, d_upper = base_n, base_d
    else:
        terms = [tuple(map(arb, g)) for g in gaussians_s]
        if any(not (v > 0) for _, _, v in terms):
            raise ValueError("every Gaussian width v must be positive")
        eps = arb("1e-12")
        pi = arb.pi()

        def integrate_real(cb, a0, b0, panels):
            a0, b0 = arb(a0), arb(b0)
            st = (b0 - a0) / panels
            t16 = arb("1e-16")
            tot = arb(0)
            for j in range(panels):
                tot += acb.integral(cb, a0 + j * st, a0 + (j + 1) * st, abs_tol=t16, rel_tol=t16).real
            return tot

        def base_value(t):
            v = (1 + 2 * i * scale * t) ** -2
            return scale / pi * v * sum((2 * i * sh * t).exp() * _poly(v, row) for sh, row in ((c, left), (c0, right)))

        def perturbation(t):
            return sum(d * (i * f * t - (t / v) ** 2 / 2).exp() for d, f, v in terms)

        def norm_change(t, analytic):
            b, br = base_value(t), base_value(-t)
            a, ar = perturbation(t), perturbation(-t)
            return ((b + a) * (br + ar) + eps ** 2).sqrt(analytic=analytic) - (b * br + eps ** 2).sqrt(analytic=analytic)

        limit = 40
        dcorr = 2 * integrate_real(norm_change, 0, limit, 200) + 2 * limit * eps
        dcorr += sum(2 * abs(d) * v * v / limit * (-(limit / v) ** 2 / 2).exp() for d, f, v in terms)
        d_upper = (base_d + dcorr).upper()
        split = 2 * c
        pos = [b / factorial(2 * k - 1) for k, b in enumerate(left, 1)]

        def penalty_change(first):
            def integrand(s, analytic):
                w = acb(0)
                if first:
                    u = (split - s) / (2 * scale)
                    w = u * (-u).exp() * _poly(u * u, pos)
                add = sum(d * v * (2 * pi).sqrt() * (-(v * (s - f)) ** 2 / 2).exp() for d, f, v in terms)
                return (s / 2).exp() * (add + ((w + add) ** 2 + eps ** 2).sqrt(analytic=analytic) - (w * w + eps ** 2).sqrt(analytic=analytic))
            return integrand

        top = arb(8)
        penalty = integrate_real(penalty_change(True), 0, split, 64)
        penalty += integrate_real(penalty_change(False), split, top, 64)
        penalty += 2 * eps * ((top / 2).exp() - 1)
        signed = arb(0)
        for d, f, v in terms:
            mass = 2 * pi * (f / 2 + 1 / (8 * v * v)).exp()
            signed += d * mass
            penalty += abs(d) * mass * ((top - f - 1 / (2 * v * v)) * v / arb(2).sqrt()).erfc()
        n_lower = (base_n + signed - penalty).lower()
        log.append(f"with {len(terms)} Gaussian corrections: N >= {n_lower}, D <= {d_upper}")
    if not (n_lower > 0 and d_upper > 0):
        raise ValueError("could not certify a positive numerator and norm")
    U = ((d_upper / n_lower) ** 2).upper()
    log.append(f"upper bound for C(1)^-2: {U}")
    return _report(U, log)


def _report(U, log):
    """Directed rounding from an upper ball endpoint U for C(1)^-2: U rounded up (12 decimals), C(1) bound rounded down (10)."""
    from math import isqrt
    man, exp = U.man_exp()
    u_up = Fraction(int(man)) * (Fraction(2) ** int(exp))
    D = 10**12
    us = -((-u_up * D).numerator // (-u_up * D).denominator)
    X = Fraction(10**20) / u_up
    q = isqrt(X.numerator // X.denominator)
    log.append(f"so C(1) > {q // 10**10}.{q % 10**10:010d}")
    return f"{us // D}.{us % D:012d}", f"{q // 10**10}.{q % 10**10:010d}", "\n".join(log)


DEC = __import__("re").compile(r"^-?\d{1,6}(\.\d{1,30})?$")


def parse_two_shift(w):
    def dec(x):
        x = str(x).strip()
        if not DEC.match(x):
            raise ValueError(f"not a decimal number: {x[:40]}")
        return x
    rows = w.get("coefficients")
    if not (isinstance(rows, list) and len(rows) == 2 and all(isinstance(r, list) and 1 <= len(r) <= 32 for r in rows) and len(rows[0]) == len(rows[1])):
        raise ValueError("coefficients: two rows of equal length, 1..32 numbers each")
    sh = w.get("shifts")
    if not (isinstance(sh, list) and len(sh) == 2):
        raise ValueError("shifts: [c, 0]")
    g = w.get("gaussians") or []
    if not (isinstance(g, list) and len(g) <= 12 and all(isinstance(t, list) and len(t) == 3 for t in g)):
        raise ValueError("gaussians: up to 12 triples [d, f, v]")
    return dec(w.get("scale")), [dec(x) for x in sh], [[dec(x) for x in r] for r in rows], [[dec(x) for x in t] for t in g]

def parse(s):
    s = str(s).strip()
    if len(s) > 60: raise ValueError("number too long")
    return Fraction(s)

if __name__ == "__main__":
    if not __debug__: raise SystemExit("run without -O")
    try:
        w = json.load(sys.stdin)
        if w.get("family") == "two-shift":
            us, cs, log = certify_two_shift(*parse_two_shift(w))
        else:
            us, cs, log = certify(parse(w["a"]), parse(w["c"]), [parse(x) for x in w["r"]], int(w.get("panels", 32768)))
        print(json.dumps({"ok": True, "family": w.get("family", "single-shift"), "c1_inv2_upper": us, "c1_lower": cs, "log": log}))
    except Exception as e:
        print(json.dumps({"ok": False, "error": f"{type(e).__name__}: {e}"}))
