#!/usr/bin/env python3
"""Rigorous interval certificate that L(ρ⊗ω, 1/2) ≠ 0 and L(ρ⊗ω̄, 1/2) ≠ 0
for the conductor-163 twists 2.163.8t12.a.a / .a.b (and, if time, the
conductor-26569 twists of the second field).

Method: the K0 theta expansion of the completed L-function for two equal
Γ_R(s+1) factors (Vga = [1,1]), split at t=1 and using the functional
equation. Coefficients a_n are exact in Q(ζ3), from the Frobenius class
(already computed as unit quaternions) and the exact character table.
The root number is the cubic Gauss sum G(ω)/√163, evaluated in Arb by a
finite sum. Integrals and Bessel K_0 are Arb/FLINT interval arithmetic
(python-flint acb.integral, acb.bessel_k).

Nothing here is an RH claim: it is a finite check that two particular
Artin L-values are nonzero, used as a hypothesis in the 3/8 exponent.
"""
from __future__ import annotations
import json, math, time, sys
from pathlib import Path
from flint import acb, arb, ctx

HERE = Path(__file__).resolve().parent
OUT = HERE / "certify-lhalf-results.json"

# --- exact cube root y = ζ3 = -1/2 + i √3/2 ---------------------------------
def zeta3():
    half = arb(1)/2
    s3 = arb(3).sqrt()
    return acb(-half, s3/2)

def parse_entry(s, y):
    """Evaluate a chartable entry (string in Z[y], y^2+y+1=0) in acb."""
    s = s.replace(" ", "")
    if s.lstrip("+-").isdigit():
        return acb(int(s))
    # terms like y, -y, -y-1, y+1, -y, y+1
    # safe: replace y by a marker and use flint? do it by hand.
    # All actual entries are in {0,±1,±2,±3, y, -y, y+1, -y-1, -y, y+1, ...}
    table_ok = True
    expr = s
    # compute as polynomial a*y + b
    # representations appearing: 1, -y-1, y, -1, y+1, -y, 0, 2, -2, 3
    mapping = {
        "1": acb(1),
        "-1": acb(-1),
        "0": acb(0),
        "2": acb(2),
        "-2": acb(-2),
        "3": acb(3),
        "y": y,
        "-y": -y,
        "y+1": y+1,
        "-y-1": -y-1,
        "-y+1": -y+1,
        "y-1": y-1,
    }
    if expr not in mapping:
        raise ValueError(f"unexpected chartable entry {s!r}")
    return mapping[expr]


def divisor_bound(n: int) -> int:
    """d(n) ≤ this; simple exact count."""
    d = 0
    i = 1
    while i*i < n:
        if n % i == 0:
            d += 2
        i += 1
    if i*i == n:
        d += 1
    return d


def load_an_exact(fd, char_index, M, y):
    """Exact a_n in acb, n=1..M, from Frobenius classes + recurrence.
    char_index is 0-based index into fd['chars'] (and chartable columns).
    """
    table = fd["chartable"]
    # det character: the 1-dim column whose values square-match ω^2
    # For the two 163-twists, columns 4 and 5 (0-based) have det in columns 2 and 1.
    dim2_to_det = {4: 2, 5: 1, 3: None}
    det_col = dim2_to_det.get(char_index)
    chi_col = char_index
    # a_p from the first Frobenius of each unramified p
    a_p = {}
    det_p = {}
    ram = set(fd.get("ramified", []))
    for ps, inf in fd["frob"].items():
        p = int(ps)
        if p > M:
            continue
        if p in ram:
            continue
        cls = inf["frobs"][0]["cls"]
        a_p[p] = parse_entry(table[cls][chi_col], y)
        if det_col is not None:
            det_p[p] = parse_entry(table[cls][det_col], y)
        else:
            det_p[p] = acb(1)  # unused fallback
    # ramified Euler factor at 163: filled by caller if needed
    return a_p, det_p


def build_an(a_p, det_p, ram_factor, M, y):
    """Multiplicative a_n, n=1..M inclusive. ram_factor is dict p -> list
    of coefficients [1, c1, ...] of the Euler polynomial (exact acb), i.e.
    1 + c1 T + c2 T^2 + ...  so a_{p^k} follows from the recurrence, or
    we expand 1/P(T) up to p^k <= M.
    """
    an = [acb(0)] * (M+1)
    an[1] = acb(1)
    # prime powers first
    def powers_from_chi_det(p, chi, det):
        # a_0=1, a_1=chi, a_k = chi a_{k-1} - det a_{k-2}
        vals = [acb(1), chi]
        pk = p
        k = 1
        out = {1: chi}
        while pk * p <= M:
            k += 1
            pk *= p
            ak = chi*vals[-1] - det*vals[-2]
            vals.append(ak)
            out[k] = ak
        return out

    def powers_from_poly(p, coeffs):
        # 1/P(T) = ∑ a_{p^k} T^k, P=∑ c_j T^j, c0=1
        # a_k = -∑_{j=1}^{min(k,deg)} c_j a_{k-j}
        out = {}
        seq = [acb(1)]
        k, pk = 1, p
        while pk <= M:
            s = acb(0)
            for j in range(1, min(k, len(coeffs)-1)+1):
                s += coeffs[j] * seq[k-j]
            ak = -s
            seq.append(ak)
            out[k] = ak
            k += 1
            pk *= p
        return out

    # sieve of prime powers then multiply
    is_p = [True]*(M+1)
    is_p[0]=is_p[1]=False
    p_pows = {}
    for p in range(2, M+1):
        if not is_p[p]:
            continue
        for j in range(p*p, M+1, p):
            is_p[j] = False
        if p in ram_factor:
            p_pows[p] = powers_from_poly(p, ram_factor[p])
        elif p in a_p:
            p_pows[p] = powers_from_chi_det(p, a_p[p], det_p[p])
        else:
            # prime larger than the Frobenius table: leave unknown (should not happen if M is within table)
            p_pows[p] = None

    # factor each n
    for n in range(2, M+1):
        # factor n
        m = n
        val = acb(1)
        ok = True
        p = 2
        while p*p <= m:
            if m % p == 0:
                k=0
                while m % p == 0:
                    m//=p; k+=1
                rec = p_pows.get(p)
                if rec is None or k not in rec:
                    ok=False; break
                val *= rec[k]
            p += 1 if p==2 else 2
        if not ok:
            an[n] = None
            continue
        if m>1:
            rec = p_pows.get(m)
            if rec is None or 1 not in rec:
                an[n]=None
                continue
            val *= rec[1]
        an[n] = val
    return an


def gauss_sum_eps(mod, primroot, cubic_exp, y):
    """ε = G(ω)/√mod, ω(primroot)=y^{cubic_exp}, G=∑ ω(k) e^{2πi k/mod}."""
    # ω(primroot^k) = y^{cubic_exp * k}
    G = acb(0)
    two_pi = 2*arb.pi()
    # map residue -> power of primroot
    # compute ω[residue] by walking powers of the primitive root
    omega = [None]*(mod)
    pw = 1
    ypow = acb(1)
    ystep = y**cubic_exp
    for k in range(mod-1):
        omega[pw] = ypow
        pw = (pw * primroot) % mod
        ypow *= ystep
    for k in range(1, mod):
        if omega[k] is None:
            raise RuntimeError(f"omega missing at {k}")
        angle = two_pi * k / mod
        G += omega[k] * acb(angle.cos(), angle.sin())
    sN = arb(mod).sqrt()
    return G / sN, G


def k0_safe(z, analytic=False):
    """K_0(z) for z in a complex ball that must stay in the right half-plane
    (we only call this for positive real z). If the ball may hit the branch
    cut (−∞,0], return an indeterminate value when analytic=True.
    """
    # branch cut of K_0 is (−∞,0]
    if z.real < 0 or (z.real.contains(0) and z.imag.contains(0)):
        if analytic:
            r = acb(0)
            r /= acb(0)  # indeterminate
            return r
        # if not required to be analytic, still avoid the cut
        if z.real.contains(0) and z.imag.contains(0):
            r = acb(0)
            r /= acb(0)
            return r
    return z.bessel_k(0)


def make_theta_fn(an, N, kind):
    """Θ(t) for kind '11' (Vga [1,1]) or '00' (Vga [0,0]). an[n] for n=1..M."""
    M = len(an)-1
    sqrtN = arb(N).sqrt()
    two_pi = 2*arb.pi()
    # precompute list of n whose an is not None/zero, skip zeros
    terms = [(n, an[n]) for n in range(1, M+1) if an[n] is not None and not (an[n].real.contains(0) and an[n].imag.contains(0) and an[n].rad()==0)]
    # actually keep zeros too if they have tiny rad; skip exact zeros
    terms = []
    for n in range(1, M+1):
        a = an[n]
        if a is None:
            continue
        if a == 0:
            continue
        terms.append((n, a))

    def Theta(t, analytic=False, conjugate=False):
        s = acb(0)
        for n, a in terms:
            z = two_pi * n * t / sqrtN
            kv = k0_safe(z, analytic=analytic)
            coef = a.conjugate() if conjugate else a
            if kind == "11":
                s += (n * coef) * kv
            else:
                s += coef * kv
        if kind == "11":
            return (4 * t / sqrtN) * s
        return 4 * s
    return Theta, terms


def tail_bound_theta(t_lo, N, M, kind):
    """Bound |remainder of Θ(t) after n>M| uniformly for t ≥ t_lo (real, ≥1).
    |a_n| ≤ d(n) ≤ 2√n, K_0(x) < exp(-x) * √(π/(2x)) * 2 for x≥1
    (we use the looser K_0(x) < exp(-x) * 2/√x for x≥1, which holds
    because the standard bound is √(π/(2x)) e^{-x} (1+O(1/x)) and
    √(π/2)≈1.25 < 2, and for x≥1 the remainder of the expansion is
    absorbed; we actually use a fully elementary bound:
        0 < K_0(x) < e^{-x} √(π/(2x)) * (1 + 1/(8x-1))   (x>1/8)
    which is classical (see e.g. Abramowitz–Stegun 9.7.2 with remainder).
    To stay elementary and unimpeachable we use the cruder
        K_0(x) < e^{-x}   once x ≥ 1,   AFTER checking K_0(1)<1 is false.
    Instead: K_0(x) < e^{-x} * √(2/x) for x≥1, since √(π/2)*(1+1/7)<1.25*1.15<1.44 < √2≈1.41? careful.
    We just evaluate Arb K_0 at the first omitted argument and use
    monotonicity + a geometric majorant.
    """
    # For t ≥ t_lo, argument of K_0 for n>M is ≥ α = 2π (M+1) t_lo / √N
    alpha0 = 2*arb.pi() * (M+1) * arb(t_lo) / arb(N).sqrt()
    # Use K_0(x) < √(π/(2x)) e^{-x} (1 + 1/(8x))  for x>0.  This is the
    # first two terms of the asymptotic series with a remainder of the
    # same sign as the next (negative) term when truncated after a
    # positive term? Safer: compute K0(alpha0) in Arb and bound the
    # tail by ∑_{n≥M+1} n d(n) K_0(α n) with α=2π t_lo/√N, and
    # K_0(α n) ≤ K_0(alpha0) * exp(-α(n-(M+1))) because
    # K_0 is decreasing and K_0(x+d)/K_0(x) ≤ exp(-d) for x>0
    # (true because K_0'(x)/K_0(x) = -K_1(x)/K_0(x) ≤ -1 for x>0?
    # K_1/K_0 ≥ 1 is true for all x>0? K_1(x) > K_0(x) yes for x>0.
    # Yes, K_1(x) > K_0(x) for x>0, so -K_0'/K_0 = K_1/K_0 > 1, so
    # K_0(x+d) < K_0(x) e^{-d}.
    # We'll record this standard inequality.
    khead = arb(alpha0).bessel_k(0)
    alpha = 2*arb.pi() * arb(t_lo) / arb(N).sqrt()
    # ∑_{n≥M+1} n d(n) e^{-α(n-(M+1))} ≤ (M+1)*d_max * khead * ∑_{j≥0} (1+j/(M+1)) e^{-α j}
    # d(n)< 2√n ≤ 2√(n) ; use d(n) ≤ n for a trivial bound, or 2√n
    # ∑_{n=M+1}^∞ n * 2√n * K_0(α n) ≤ 2 khead ∑_{j=0}^∞ (M+1+j)^{3/2} e^{-α j}
    # Bound (M+1+j)^{3/2} ≤ (M+1)^{3/2} * (1+j/(M+1))^{3/2} ≤ (M+1)^{3/2} e^{ (3/2) j/(M+1) }
    # so the sum is geometric with ratio r = exp(-α + 3/(2(M+1))).
    M1 = arb(M+1)
    ratio_exp = -alpha + arb(3)/(2*M1)
    # require ratio < 1
    r = ratio_exp.exp()
    head = 2 * khead * M1**(arb(3)/2)
    # ∑ j=0..∞ r^j = 1/(1-r) if r<1
    if not (r < 1):
        return arb("inf")
    geom = 1/(1-r)
    # For kind 11, Θ has an extra factor (4 t /√N) * n already in the n^{3/2}?
    # |Θ| tail: kind 11: (4 t /√N) ∑ n |a_n| K_0 ≤ (4 t /√N) * 2 khead ∑ n^{3/2} e^{-...}
    # kind 00: 4 ∑ |a_n| K_0 ≤ 4 * 2 khead ∑ n^{1/2} e^{-...}  (weaker power)
    tlo = arb(t_lo)
    if kind == "11":
        return (4 * tlo / arb(N).sqrt()) * head * geom
    # kind 00: ∑ |a_n| K ≤ 2 khead ∑ √n exp = 2 khead (M+1)^{1/2} ∑ e^{j/(2(M+1))-α j}
    r0 = (-alpha + arb(1)/(2*M1)).exp()
    if not (r0 < 1):
        return arb("inf")
    return 4 * (2 * khead * M1.sqrt() / (1-r0))


def gamma_factor(s, N, kind):
    """N^{s/2} γ(s). kind '11': γ=π^{-(s+1)} Γ((s+1)/2)^2
       kind '00': γ=π^{-s} Γ(s/2)^2
    """
    pi = arb.pi()
    Ns2 = acb(N)**(s/2)
    if kind == "11":
        gam = (s+1)/2
        g = (pi**(-(s+1))) * (gam.gamma())**2
    else:
        gam = s/2
        g = (pi**(-s)) * (gam.gamma())**2
    return Ns2 * g


def certify_one(fd, char_index, label, kind, N, M=800, T=40, dps=40):
    t0 = time.time()
    ctx.dps = dps
    y = zeta3()
    a_p, det_p = load_an_exact(fd, char_index, M, y)
    # ramified p=163: Euler factor from known Artin local factor of conductor 163.
    # For a primitive 2-dim representation of prime conductor q, the Euler factor
    # at q is 1 (the inertia has no invariants, so the local polynomial is 1).
    # We confirm against the coefficient a_163 from PARI later; set ram factor 1
    # (all a_{163^k}=0).
    ram_factor = {163: [acb(1), acb(1)]}  # 1+T, so a_{163}=-1, a_{163^k}=(-1)^k
    an = build_an(a_p, det_p, ram_factor, M, y)
    n_ok = sum(1 for n in range(1,M+1) if an[n] is not None)
    # Root number ε = G(χ_det)/√163, where χ_det is the unique primitive
    # cubic Dirichlet character mod 163 that agrees with det(ρ⊗ω) at the
    # primitive root 2 (znprimroot(163)=2). For an even primitive Dirichlet
    # character this is the classical formula; we use the same Gauss sum
    # here because det(ρ⊗ω) is that cubic character (conductor 163).
    primroot = 2
    d2 = det_p[2]
    if abs(d2 - y).upper() < arb("1e-20"):
        the_exp = 1
    elif abs(d2 - y*y).upper() < arb("1e-20"):
        the_exp = 2
    else:
        raise RuntimeError(f"det(Frob_2) is neither ζ3 nor ζ3^2: {d2}")
    eps, G = gauss_sum_eps(163, primroot, the_exp, y)
    eps_cands = {the_exp: (eps, G)}

    Theta, terms = make_theta_fn(an, N, kind)

    def integrand_factory(eps, Tmax):
        def f(t, analytic):
            # t should stay in the right half-plane, off the cut of sqrt and K0
            if analytic and (t.real < 0 or t.real.contains(0)):
                r = acb(0); r /= acb(0); return r
            Th = Theta(t, analytic=analytic, conjugate=False)
            Ths = Theta(t, analytic=analytic, conjugate=True)
            return (t.sqrt(analytic=analytic)**(-1)) * (Th + eps*Ths)
        return f

    # Try both ε candidates: integrate 1..T, compare
    results = {}
    for exp, (eps, G) in eps_cands.items():
        f = integrand_factory(eps, T)
        I = acb.integral(f, acb(1), acb(T), abs_tol=arb(10)**(-(dps-5)))
        # tail of the integral t=T..∞: |f(t)| ≤ t^{-1/2} (|Θ|+|Θ*|) ≤ 2 t^{-1/2} (|Θ_partial|+tail_Θ)
        # For large T, Θ(t) itself is O( t e^{-c t} ) or O(e^{-c t}).
        # Bound |Θ(t)| for t≥T by evaluating the first-term size * geometric.
        # Use: |∫_T^∞ t^{-1/2} (Θ+εΘ*) dt| ≤ 2 ∫_T^∞ t^{-1/2} ( |Θ_{≤M}(t)| + tail_Θ ) dt
        # A crude majorant: |Θ(t)| ≤ C t^e exp(-2π t /√N) with C from the n=1 term
        # times 1/(1-e^{-2π/√N}).
        alpha = 2*arb.pi()/arb(N).sqrt()  # min increment
        # |Θ(t)| ≤ (4 t /√N) ∑ n |a_n| K_0(α n t) ≤ (4 t /√N) * 2 * ∑ n^{3/2} √(π/(2 α n t)) e^{-α n t}
        # ≤ C t * t^{-1/2} e^{-α t} / (1 - e^{-α t}) roughly.
        # Evaluate a majorant at T and integrate e^{-α(t-T)} .
        # Simpler: increase T so the Arb integral's missing tail is < 10^{-dps/2}
        # by a geometric bound:
        # |∫_T^∞ t^{-1/2} 2 C t exp(-α t) dt|  for kind 11, C=(4/√N)*∑...
        # Bound t^{1/2} e^{-α t} ≤ T^{1/2} e^{-α T} e^{-α(t-T) + (t-T)/(2T)}
        # (since (T+u)^{1/2} ≤ T^{1/2} e^{u/(2T)}).
        # We compute a numeric majorant of |Θ(T)| using the same Theta function
        # (a ball) plus the series tail, then integrate the exponential majorant.
        TT = acb(T)
        ThT = Theta(TT, conjugate=False)
        ThsT = Theta(TT, conjugate=True)
        magT = (abs(ThT) + abs(ThsT)) + tail_bound_theta(T, N, M, kind)*2
        # |f(t)| ≤ t^{-1/2} mag(t), mag(t) ≤ magT * exp(-(α-δ)(t-T)) with δ from
        # the t-power in Θ (at most t^1 / T^1 = e^{log t - log T} ≤ e^{(t-T)/T}).
        # For kind 11, Θ has a factor t, so |Θ(t)/Θ(T)| ~ (t/T) e^{-α(t-T)}.
        # |f(t)| ≤ (t^{-1/2}) (t/T) (T^{1/2} * (magT / T^0?)) wait:
        # |f(T)| ≤ T^{-1/2} magT, and |f(t)| ≤ |f(T)| * (t/T)^{1/2} e^{-α(t-T)}
        # because of the extra t in Θ and t^{-1/2}.
        # (t/T)^{1/2} e^{-α(t-T)} = e^{ (1/2)log(t/T) - α(t-T) } ≤ e^{ (t-T)/(2T) - α(t-T) }
        rate = alpha - arb(1)/(2*arb(T))
        fT = arb(T)**(arb(-1)/2) * magT  # |f(T)| bound (arb)
        if rate > 0:
            tailI = fT / rate   # ∫_0^∞ e^{-rate u} du
        else:
            tailI = arb("inf")
        Lam = I + acb(arb(0, tailI), arb(0, tailI))
        pre = gamma_factor(acb("1/2"), N, kind)
        Lval = Lam / pre
        results[exp] = dict(eps=eps, G=G, I=I, tail=tailI, Lam=Lam, pre=pre, L=Lval,
                            contains0= (Lval.real.contains(0) and Lval.imag.contains(0)),
                            abs_lo = abs(Lval).lower(),
                            I_only=I)
    # pick the candidate whose |L| is bounded away from 0 and matches the
    # expected size (~1.8 for the 163 twists). Both conjugates are needed;
    # they correspond to the two characters (a.a and a.b). For a *single*
    # character (this char_index), exactly one of the two ε is correct.
    # We identify it by requiring the two-split test: compute I_{1..T/2} and
    # I_{1..T} and see consistency... actually both will 'work' only for the
    # true ε because a wrong ε gives a wrong Λ. We just pick the one with
    # larger abs_lo if one contains 0; if both are nonzero that's fine to
    # report both? No: only one ε is correct, the other gives a meaningless L.
    # Use a cheap consistency check: Λ should satisfy Λ = ε conj(Λ)
    # (because Λ(1/2)=ε Λ^*(1/2) and Λ^* (1/2)=conj Λ(1/2) on the real line).
    chosen = None
    for exp, r in results.items():
        # Use the une-inflated integral I to distinguish ε: the true ε
        # satisfies I ≈ ε conj(I) up to the (tiny) omitted tail, so the
        # midpoint residual is orders of magnitude smaller than for a wrong ε.
        I0, eps = r["I"], r["eps"]
        conjI = acb(I0.real, -I0.imag)
        resid_I = I0 - eps * conjI
        r["fe_residual_I"] = resid_I
        midv = acb(resid_I.real.mid(), resid_I.imag.mid())
        r["fe_I_mid"] = abs(midv)
        r["fe_I_mid_float"] = float(abs(midv).mid())
        Lam, eps = r["Lam"], r["eps"]
        conjLam = acb(Lam.real, -Lam.imag)
        resid = Lam - eps * conjLam
        r["fe_residual"] = resid
        r["fe_abs_upper"] = abs(resid).upper()
        r["fe_ok"] = r["fe_I_mid"] < arb("1e-8")
    for exp,r in results.items():
        print("  cand exp", exp, "fe_I_mid_float", r["fe_I_mid_float"], "abs_lo", r["abs_lo"], flush=True)
    chosen = min(results, key=lambda e: results[e]["fe_I_mid_float"])

    def acb_to_s(z):
        try:
            return {"re": str(z.real), "im": str(z.imag), "rad": str(z.rad())}
        except Exception:
            return str(z)

    r = results[chosen]
    out = {
        "label": label,
        "char_index": char_index,
        "conductor": N,
        "kind": kind,
        "M": M,
        "T": T,
        "dps": dps,
        "n_coeffs_ok": n_ok,
        "cubic_exp_for_eps": chosen,
        "eps": acb_to_s(r["eps"]),
        "Gauss_sum": acb_to_s(r["G"]),
        "Lambda": acb_to_s(r["Lam"]),
        "integral_1_to_T": acb_to_s(r["I"]),
        "tail_bound": str(r["tail"]),
        "prefactor": acb_to_s(r["pre"]),
        "L_half": acb_to_s(r["L"]),
        "abs_L_lower": str(r["abs_lo"]),
        "contains_zero": bool(r["contains0"]),
        "FE_residual": acb_to_s(r["fe_residual"]),
        "FE_residual_abs_upper": str(r["fe_abs_upper"]),
        "certified_nonzero": (not r["contains0"]) and (r["abs_lo"] is not None) and (arb(r["abs_lo"]) > 0),
        "seconds": time.time()-t0,
        "other_candidate_abs_lo": {str(e): str(results[e]["abs_lo"]) for e in results},
    }
    return out, r["L"]


# ---------------------------------------------------------------------------
# Conductor-26569 twists (Vga [0,0]): termwise incomplete-K0 AFE
# A(X) = 4 Σ a_n (α n)^{-1/2} F(α n X),  F(z)=∫_z^∞ u^{-1/2} K_0(u) du
# α = 2π/√N,  Λ(1/2)=A(1)+ε A^*(1),  ε from two-X: (A(1)-A(2))/(A^*(1/2)-A^*(1))
# ---------------------------------------------------------------------------

def _complete_F0():
    """∫_0^∞ u^{-1/2} K_0(u) du = 2^{-3/2} Γ(1/4)^2."""
    return (arb(2)**(arb(-3)/2)) * (arb(1)/4).gamma()**2


def _near0_F_integral(eps):
    """Enclosure of ∫_0^eps u^{-1/2} K_0(u) du for 0 < eps ≤ 1e-16.

    Main term uses K_0(u) = -log(u/2)-γ plus a remainder bound
    |R(u)| ≤ u^2 (|log u| + 3) on this range, which is a large
    over-estimate of the classical power-series remainder
    (the first correction is O(u^2 |log u|), with coefficient 1/4).
    """
    eps = arb(eps)
    se = eps.sqrt()
    main = -(2 * se * eps.log() - 4 * se) + 2 * se * (arb(2).log() - arb.const_euler())
    a = arb(5) / 2
    int_u32_log = (eps**a) / a * eps.log() - (eps**a) / a**2
    int_u32 = (eps**a) / a
    int_abs_log = -int_u32_log  # log u < 0
    # |∫ u^{-1/2} R(u) du| ≤ ∫_0^eps u^{3/2} (|log u| + 3) du
    Rint = (-int_u32_log) + 3 * int_u32
    return acb(main) + acb(arb(0, Rint))


def _k0_uinvsqrt(u, analytic=False):
    if analytic and (u.real < 0 or u.real.contains(0)):
        r = acb(0)
        r /= acb(0)
        return r
    return (u.sqrt(analytic=analytic) ** (-1)) * u.bessel_k(0)


def F_table(alpha, X, nmax, z_cut=35, abs_tol=None):
    """F(α n X) as a real acb for n=1..nmax, by a cumulative integral.

    For z = α n X ≤ z_cut: F(z) = F(0) - ∫_0^z, chained from a tiny
    eps through the successive z_n (spacing α X).
    For z > z_cut: the elementary bound 0 < F(z) < z^{-1/2} K_0(z),
    recorded as a ball [0, bound].
    """
    if abs_tol is None:
        abs_tol = arb(10) ** (-(ctx.dps - 8))
    complete = _complete_F0()
    eps = arb("1e-16")
    I0 = _near0_F_integral(eps)
    cum = I0
    z_prev = acb(eps)
    out = {}
    alphaX = arb(alpha) * arb(X)
    for n in range(1, nmax + 1):
        z = acb(alphaX * n)
        zlo = z.real.lower()
        if zlo > z_cut:
            # 0 < F(z) < z^{-1/2} K_0(z), using K_1>K_0 so the integral
            # of e^{-(t-z)} z^{-1/2} K_0(z) dt is at most the bound.
            bound = abs((z.sqrt() ** (-1)) * z.bessel_k(0))
            out[n] = acb(arb(bound / 2, bound / 2))
            continue
        piece = acb.integral(_k0_uinvsqrt, z_prev, z, abs_tol=abs_tol)
        cum = cum + piece
        out[n] = acb(complete) - cum
        z_prev = z
    return out


def A_from_F(an, alpha, X, Ftab, M):
    """A(X) = 4 Σ_{n=1}^M a_n (α n)^{-1/2} F(α n X), plus a series tail."""
    s = acb(0)
    for n in range(1, M + 1):
        a = an[n]
        if a is None or a == 0:
            continue
        coef = (acb(alpha) * n) ** (arb(-1) / 2)
        s += a * coef * Ftab[n]
    s = 4 * s
    # Tail n>M: |a_n|≤d(n)≤2√n, F(z)<z^{-1/2} K_0(z),
    # K_0(z+d)<K_0(z) e^{-d}.  z_n = α n X.
    # |term_n| ≤ 4 * 2√n * (α n)^{-1/2} * (α n X)^{-1/2} K_0(α n X)
    #          = 8 (α)^{-1} X^{-1/2} K_0(α n X)
    # Σ_{n≥M+1} K_0(α n X) < K_0(α(M+1)X) / (1 - exp(-α X))
    aX = arb(alpha) * arb(X)
    zhead = aX * (M + 1)
    khead = arb(zhead).bessel_k(0)
    den = 1 - (-aX).exp()
    tail = 8 * (1 / arb(alpha)) * arb(X) ** (arb(-1) / 2) * khead / den
    return s + acb(arb(0, tail))


def build_Ftabs_26569(M=1500, dps=40):
    """F-tables depend only on N, α, X, M — shared by both conjugates."""
    ctx.dps = dps
    N = 26569
    alpha = 2 * arb.pi() / arb(N).sqrt()
    Xs = (("1/2", arb("1/2")), ("1", arb(1)), ("2", arb(2)))
    print(f"  building F-tables M={M} dps={dps}...", flush=True)
    Ftabs = {}
    for key, X in Xs:
        t1 = time.time()
        Ftabs[key] = F_table(alpha, X, M)
        n_tight = sum(1 for n, v in Ftabs[key].items() if v.rad() < arb("1e-10"))
        print(f"    F-table X={key} in {time.time()-t1:.1f}s, tight={n_tight}/{M}", flush=True)
    return Ftabs, alpha


def certify_26569(fd, char_index, label, M=1500, dps=40, Ftabs=None, alpha=None):
    """Interval-certify L(1/2)≠0 for a conductor-26569 Vga[0,0] twist."""
    t0 = time.time()
    ctx.dps = dps
    N = 26569
    kind = "00"
    y = zeta3()
    a_p, det_p = load_an_exact(fd, char_index, M, y)
    # Ramified p=163: lfuneuler = 1, so a_{163^k}=0 for all k.
    ram_factor = {163: [acb(1)]}
    an = build_an(a_p, det_p, ram_factor, M, y)
    n_ok = sum(1 for n in range(1, M + 1) if an[n] is not None)
    an_star = [None] * (M + 1)
    for n in range(1, M + 1):
        if an[n] is not None:
            an_star[n] = an[n].conjugate()

    if Ftabs is None or alpha is None:
        Ftabs, alpha = build_Ftabs_26569(M=M, dps=dps)

    def AA(an_list, key, X):
        return A_from_F(an_list, alpha, X, Ftabs[key], M)

    A1 = AA(an, "1", arb(1))
    A2 = AA(an, "2", arb(2))
    Ahalf = AA(an, "1/2", arb("1/2"))
    B1 = AA(an_star, "1", arb(1))        # A^*(1)
    B2 = AA(an_star, "1/2", arb("1/2"))  # A^*(1/2)
    # ε = (A(1)-A(2)) / (A^*(1/2)-A^*(1))
    num = A1 - A2
    den = B2 - B1
    if den.contains(0):
        raise RuntimeError(f"two-X denominator contains 0: {den}")
    eps = num / den
    Lam = A1 + eps * B1
    pre = gamma_factor(acb("1/2"), N, kind)
    Lval = Lam / pre
    # Functional equation check: Λ should equal ε conj(Λ) (s=1/2, real line)
    conjLam = acb(Lam.real, -Lam.imag)
    resid = Lam - eps * conjLam
    contains0 = Lval.real.contains(0) and Lval.imag.contains(0)
    abs_lo = abs(Lval).lower()
    certified = (not contains0) and (abs_lo is not None) and (arb(abs_lo) > 0)

    def acb_to_s(z):
        try:
            return {"re": str(z.real), "im": str(z.imag), "rad": str(z.rad())}
        except Exception:
            return str(z)

    out = {
        "label": label,
        "char_index": char_index,
        "conductor": N,
        "kind": kind,
        "M": M,
        "dps": dps,
        "n_coeffs_ok": n_ok,
        "field": "2.26569.24t7.a.a",
        "root_number_method": "two-X interval: eps=(A(1)-A(2))/(A^*(1/2)-A^*(1))",
        "eps": acb_to_s(eps),
        "A1": acb_to_s(A1),
        "A2": acb_to_s(A2),
        "Ahalf": acb_to_s(Ahalf),
        "B1": acb_to_s(B1),
        "den": acb_to_s(den),
        "Lambda": acb_to_s(Lam),
        "prefactor": acb_to_s(pre),
        "L_half": acb_to_s(Lval),
        "abs_L_lower": str(abs_lo),
        "contains_zero": bool(contains0),
        "FE_residual": acb_to_s(resid),
        "FE_residual_abs_upper": str(abs(resid).upper()),
        "certified_nonzero": bool(certified),
        "seconds": time.time() - t0,
    }
    return out, Lval


def main():
    t_all = time.time()
    data = json.loads((HERE / "pari-data.json").read_text())
    reports = []

    # Keep the already-certified conductor-163 cases if present.
    prev = {}
    if OUT.exists():
        try:
            prev = json.loads(OUT.read_text())
        except Exception:
            prev = {}
    old_163 = []
    if prev.get("cases"):
        old_163 = [c for c in prev["cases"] if c.get("conductor") == 163 and c.get("certified_nonzero")]
    if len(old_163) == 2:
        print("reusing existing certified conductor-163 cases", flush=True)
        reports.extend(old_163)
    else:
        fd163 = data["2.26569.24t7.b.a"]
        for idx, lab in ((4, "2.163.8t12.a.a"), (5, "2.163.8t12.a.b")):
            ch = fd163["chars"][idx]
            assert ch["conductor"] == 163 and ch["Vga"] == [1, 1]
            print(f"==== certifying {lab} (char index {idx}) ====", flush=True)
            rec, L = certify_one(fd163, idx, lab, kind="11", N=163, M=400, T=30, dps=40)
            reports.append(rec)
            print(json.dumps({k: rec[k] for k in ("label", "L_half", "abs_L_lower", "contains_zero", "certified_nonzero", "FE_residual_abs_upper", "seconds")}, indent=2), flush=True)

    fd = data["2.26569.24t7.a.a"]
    for idx, lab in ((4, "2.26569.8t12.a.a"), (5, "2.26569.8t12.a.b")):
        ch = fd["chars"][idx]
        assert ch["conductor"] == 26569 and ch["Vga"] == [0, 0], (ch["conductor"], ch["Vga"])
        print(f"==== certifying {lab} (char index {idx}, second 2T field) ====", flush=True)
        if idx == 4:
            Ftabs, alpha = build_Ftabs_26569(M=1500, dps=40)
        rec, L = certify_26569(fd, idx, lab, M=1500, dps=40, Ftabs=Ftabs, alpha=alpha)
        reports.append(rec)
        keys = ("label", "L_half", "abs_L_lower", "contains_zero", "certified_nonzero", "FE_residual_abs_upper", "eps", "seconds")
        print(json.dumps({k: rec[k] for k in keys}, indent=2), flush=True)

    out = {
        "method": "Arb/FLINT interval AFE. Conductor 163: K0 theta (Vga [1,1]), exact a_n in Q(ζ3) from Frobenius classes, root number = cubic Gauss sum / √163. Conductor 26569: termwise incomplete-K0 (Vga [0,0]), A(X)=4 Σ a_n (α n)^{-1/2} F(α n X) with F(z)=∫_z^∞ u^{-1/2} K_0(u) du, root number from two-X identity ε=(A(1)-A(2))/(A^*(1/2)-A^*(1)).",
        "hypotheses": [
            "K_1(x)>K_0(x) for x>0 (used for K_0(x+d)<K_0(x) e^{-d} and for 0<F(z)<z^{-1/2} K_0(z)); standard.",
            "∫_0^∞ u^{-1/2} K_0(u) du = 2^{-3/2} Γ(1/4)^2 (Mellin of K_0, classical).",
            "K_0(u) = -log(u/2)-γ + R(u) with |R(u)| ≤ u^2(|log u|+3) for 0<u≤1e-16 (large over-estimate of the power-series remainder; the near-0 integral is ~8e-7 and its remainder ball is <1e-38).",
            "|a_n| ≤ d(n) ≤ 2√n (used only in the n>M series tail, already <10^{-8} at M=1500).",
            "For conductor 163: ε=G(ω)/√163 for the primitive even cubic character ω mod 163 (classical Gauss-sum formula for the determinant character).",
            "For conductor 26569: the functional equation Λ(s)=ε Λ^*(1-s) implies the two-X identity for ε; the identity is checked a posteriori by the residual Λ-ε conj(Λ) at s=1/2.",
        ],
        "not_claimed": "No RH statement. Only non-vanishing of these Artin L-values at s=1/2.",
        "lmfdb": {
            "163": ["2.163.8t12.a.a", "2.163.8t12.a.b"],
            "26569": ["2.26569.8t12.a.a", "2.26569.8t12.a.b"],
            "orbit_26569": "2.26569.8t12.a",
            "parent_fields": {"163": "2.26569.24t7.b.a", "26569": "2.26569.24t7.a.a"},
        },
        "cases": reports,
        "seconds": time.time() - t_all,
    }
    OUT.write_text(json.dumps(out, indent=2, default=str))
    print("wrote", OUT)
    all_ok = all(r["certified_nonzero"] for r in reports)
    print("ALL CERTIFIED NONZERO" if all_ok else "NOT ALL CERTIFIED")
    return 0 if all_ok else 1


if __name__ == "__main__":
    sys.exit(main())
