#!/usr/bin/env python3
"""Interval (Arb / python-flint) certificate: L'(rho, 1/2) != 0 for the two icosahedral (2I = SL(2,5))
Artin L-functions with root number -1 of icosa-oddW-20261114.md, and for their Galois conjugates rho'
(sqrt5 -> -sqrt5; also W = -1 by the same local computation).

  2.3806401.120.a  N = 1951^2,  Gamma_R(s)^2    (mu = 0)
  2.4583881.120.a  N = 2141^2,  Gamma_R(s+1)^2  (mu = 1)

HYPOTHESIS: Lambda(s) = N^{s/2} Gamma_R(s+mu)^2 L(rho, s) is entire and Lambda(s) = W Lambda(1-s)
(Artin's conjecture for these icosahedral reps; open [known: Booker, Experiment. Math. 15 (2006)]; the FE
itself is unconditional by Brauer, and W = +-1 since rho is symplectic).

Method (as octa1113/certify_octa.py and icosa-exp1113/certify_icosa.py):
  phi_mu(x) = 4 x^mu K0(2 pi x) has Mellin transform Gamma_R(s+mu)^2 (checked below), so
  Lambda(s) = int_0^oo theta(t) t^{s-1} dt, theta(t) = sum a_n phi_mu(n t / sqrt N), theta(1/t) = W t theta(t);
  for W = -1:  Lambda'(1/2) = 2 sum a_n int_1^oo phi_mu(n t/sqrt N) t^{-1/2} log t dt
             = P_mu sum a_n z^{-1/2} [H(z) - log z F(z)],  z = c n, c = 2 pi / sqrt N,
  P_0 = 8, P_1 = 4/pi,  F(z) = int_z^oo K0(x) x^{mu-1/2} dx,  H(z) = int_z^oo K0(x) x^{mu-1/2} log x dx,
  F, H by chained rigorous acb.integral over [c n, c(n+1)] downward from c(M+1), explicit tails.
  L'(1/2) = Lambda'(1/2) / (N^{1/4} Gamma_R(1/2+mu)^2).
Root number certified (under the hypothesis) from the interval ratio theta(1/2) / (2 theta(2)).
Coefficients exact in Z[phi], phi = (1+sqrt5)/2, from cert1113/ap-oriented-*.json (oriented-discriminant
Frobenius classes); ramified p has Euler factor 1 (inertia C10 resp. C5 has no fixed vector).
No RH claim: the zero at 1/2 is forced by the sign of the functional equation."""
import json, math, sys, time
from pathlib import Path
from flint import arb, acb, ctx
HERE = Path(__file__).resolve().parent
LABEL = sys.argv[1]
CN = float(sys.argv[2]) if len(sys.argv) > 2 else 120.0
ctx.prec = int(sys.argv[3]) if len(sys.argv) > 3 else 160
INFO = {'2.3806401.120.a': (1951, 0, 14.640419841590850183), '2.4583881.120.a': (2141, 1, 8.3882157)}
P, MU, PARI_LP = INFO[LABEL]
N = P*P
d = json.loads((HERE.parent/'cert1113'/f'ap-oriented-{LABEL}.json').read_text())
assert d['N'] == N
apf = {int(k): v for k, v in d['ap'].items()}
NMAX = 119999
PHIf = (1 + 5**0.5)/2
VALS = {(2, 0): 2., (-2, 0): -2., (1, 0): 1., (-1, 0): -1., (0, 0): 0., (0, 1): PHIf, (-1, 1): PHIf-1, (1, -1): 1-PHIf, (0, -1): -PHIf}
def recog(x):
    for t, v in VALS.items():
        if abs(x - v) < 1e-9: return t
    raise ValueError(x)
def gconj(t): return (t[0] + t[1], -t[1])
def mulp(a, b): return (a[0]*b[0] + a[1]*b[1], a[0]*b[1] + a[1]*b[0] + a[1]*b[1])   # phi^2 = phi + 1
def primes_upto(n):
    s = bytearray(b'\x01')*(n+1); s[0] = s[1] = 0
    for i in range(2, int(n**.5)+1):
        if s[i]: s[i*i::i] = b'\x00'*len(s[i*i::i])
    return [i for i in range(n+1) if s[i]]
PR = primes_upto(NMAX)
assert all(p in apf for p in PR) and apf[P] is None and all(apf[p] is not None for p in PR if p != P)

def build(conj):
    a = [None]*(NMAX+1); a[1] = (1, 0); pp = {}
    for p in PR:
        if p == P: pp[p] = None; continue
        ap = recog(apf[p])
        if conj: ap = gconj(ap)
        seq = [(1, 0), ap]; q = p
        while q*p <= NMAX:
            x1 = mulp(ap, seq[-1]); z = seq[-2]
            seq.append((x1[0]-z[0], x1[1]-z[1])); q *= p
        pp[p] = seq
    spf = list(range(NMAX+1))
    for p in PR:
        for m in range(p*p, NMAX+1, p):
            if spf[m] == m: spf[m] = p
    for n in range(2, NMAX+1):
        p = spf[n]; m = n; k = 0
        while m % p == 0: m //= p; k += 1
        loc = (0, 0) if p == P else pp[p][k]
        a[n] = mulp(loc, a[m])
    return a

t0 = time.time()
out = dict(label=LABEL, conductor=N, mu=MU, gamma_factor=f'Gamma_R(s+{MU})^2', arb_prec_bits=ctx.prec, cn_cutoff=CN, NMAX=NMAX,
           hypothesis='Lambda entire with Lambda(s) = W Lambda(1-s) (Artin conjecture for this icosahedral rep and its conjugate)')
A_r = build(False); A_c = build(True)
# --- audit 1: exact vs the float recursion of cert1113/lw_2I.py (the vector PARI lfuncheckfeq accepted at 2^-55/-54)
spf = list(range(NMAX+1))
for p in PR:
    for m in range(p*p, NMAX+1, p):
        if spf[m] == m: spf[m] = p
anf = [0.0]*(NMAX+1); anf[1] = 1.0
def apk(p, k):
    a = apf[p]
    if a is None: return 0.0
    x0, x1 = 1.0, a
    for _ in range(k-1): x0, x1 = x1, a*x1 - x0
    return x1
for n in range(2, NMAX+1):
    p = spf[n]; m = n; k = 0
    while m % p == 0: m //= p; k += 1
    anf[n] = apk(p, k)*anf[m]
worst = max(abs(A_r[n][0] + A_r[n][1]*PHIf - anf[n]) for n in range(1, NMAX+1))
# --- audit 2: |a_n| <= d(n) (used in the tail bound) and a_{mn} = a_m a_n spot checks
def dfun(n):
    r = 1; m = n
    while m > 1:
        p = spf[m]; k = 0
        while m % p == 0: m //= p; k += 1
        r *= k+1
    return r
bad_d = sum(1 for A in (A_r, A_c) for n in range(1, NMAX+1) if abs(A[n][0] + A[n][1]*PHIf) > dfun(n) + 1e-9)
out['audit'] = dict(exact_vs_float_recursion_max_abs_diff=worst, divisor_bound_violations=bad_d,
                    first_coeffs_rho={n: VALS.get(A_r[n], A_r[n][0] + A_r[n][1]*PHIf) for n in range(1, 31)})
print('audit', worst, bad_d, flush=True)
assert worst < 1e-9 and bad_d == 0

PHI = (1 + arb(5).sqrt())/2
def A(t): return arb(t[0]) + arb(t[1])*PHI
c = 2*arb.pi()/arb(N).sqrt(); cf = float(c.mid())
M = int(math.ceil(CN/cf)); assert 2*M + 10 <= NMAX, (M, NMAX)
out['M'] = M; out['c'] = c.str(20)
TWOPI = 2*arb.pi()

def geo_tail(m, x0, step, power):
    """rigorous bound for sum_{n>=m} n^power e^{-(x0 + step (n-m))} with x0 = step*m: ratio test"""
    q = (arb(m+1)/m)**power*(-step).exp()
    assert q < 1
    return arb(m)**power*(-x0).exp()/(1 - q)

# ---- Mellin normalisation check: int_0^oo phi_mu(x) x^{s-1} dx = Gamma_R(s+mu)^2 at s = 2 (float, mpmath)
import mpmath as mp
mp.mp.dps = 30
mel = mp.quad(lambda x: 4*x**MU*mp.besselk(0, 2*mp.pi*x)*x**(2-1), [0, 1, mp.inf])
gr = (mp.pi**(-(2+MU)/2.)*mp.gamma((2+MU)/2.))**2
out['mellin_check_s2'] = dict(integral=str(mel), gamma_R_sq=str(gr))
assert abs(mel/gr - 1) < 1e-20

# ---- theta and root number --------------------------------------------------------------------------------
def theta(a, y, nmax):
    y = arb(y); s = arb(0)
    for n in range(1, nmax+1):
        if a[n] == (0, 0): continue
        x = c*n*y
        s += A(a[n])*x.bessel_k(0)*(x/TWOPI if MU else 1)
    # tail: |a_n| <= d(n) <= n; K0(x) <= sqrt(pi/(2x)) e^-x; x^mu K0(x)/(2pi)^mu <= sqrt(pi/2) (cy)^(mu-1/2) n^(mu-1/2) e^-x
    m = nmax+1; step = c*y
    pw = MU + arb(1)/2
    tl = (arb.pi()/2).sqrt()*step**(MU - arb(1)/2)/TWOPI**MU*geo_tail(m, step*m, step, pw)
    return 4*(s + arb(0, tl.upper()))

rootno = {}
for nm, a in (('rho', A_r), ('rho_conj', A_c)):
    th_half = theta(a, arb(1)/2, NMAX); th2 = theta(a, 2, M)
    Wb = th_half/(2*th2)
    W = 1 if (Wb - 1).contains(0) and not (Wb + 1).contains(0) else (-1 if (Wb + 1).contains(0) and not (Wb - 1).contains(0) else None)
    rootno[nm] = dict(theta_half=th_half.str(20, radius=True), two_theta_2=(2*th2).str(20, radius=True), ratio=Wb.str(20, radius=True),
                      ratio_rad=float(Wb.rad()), W=W)
    print(nm, rootno[nm], f'{time.time()-t0:.0f}s', flush=True)
    assert W == -1
out['root_numbers'] = rootno

# ---- F and H tables ---------------------------------------------------------------------------------------
HALF = arb(1)/2
def f_FH(x, analytic):
    if analytic and (x.real < 0 or x.real.contains(0)):
        z = acb(0); return z/z
    w = x.rsqrt(analytic=analytic)
    if MU: w = w*x
    return x.bessel_k(0)*w*(1 + acb(0, 1)*x.log(analytic=analytic))
t1 = time.time()
X0 = c*(M+1)
# tails beyond X0 with K0(x) <= sqrt(pi/(2x)) e^-x:
#  mu=0: F <= sqrt(pi/2) e^-X0/X0, |H| <= sqrt(pi/2) e^-X0 (log X0 + 1)/X0  (int_X^oo log x e^-x = e^-X log X + E1(X), E1 <= e^-X/X)
#  mu=1: F <= sqrt(pi/2) e^-X0,     |H| <= sqrt(pi/2) e^-X0 (log X0 + 1)
sp = (arb.pi()/2).sqrt()
bF = sp*(-X0).exp()/(X0 if MU == 0 else 1); bH = sp*(-X0).exp()*(X0.log() + 1)/(X0 if MU == 0 else 1)
Fv = [None]*(M+2); Hv = [None]*(M+2)
Fv[M+1] = arb(bF/2, bF/2); Hv[M+1] = arb(0, bH)
tol = arb(2)**(-ctx.prec + 20)
for n in range(M, 0, -1):
    piece = acb.integral(f_FH, acb(c*n), acb(c*(n+1)), rel_tol=tol, abs_tol=tol, eval_limit=10**6, deg_limit=200)
    Fv[n] = Fv[n+1] + piece.real; Hv[n] = Hv[n+1] + piece.imag
    if n % 5000 == 0: print('  F/H n =', n, f'{time.time()-t1:.0f}s', Fv[n].rad(), flush=True)
out['FH_table_seconds'] = time.time() - t1
# sanity: F(0+) = int_0^oo K0 x^{mu-1/2} = 2^{mu-3/2} Gamma((mu+1/2)/2)^2
F0 = arb(2)**(MU - arb(3)/2)*((MU + HALF)/2).gamma()**2
out['sanity'] = dict(F_c=Fv[1].str(25, radius=True), F_0plus=F0.str(25), F_rad=float(Fv[1].rad()), H_rad=float(Hv[1].rad()))
print('sanity', out['sanity'], flush=True)

PREF = arb(8) if MU == 0 else 4/arb.pi()
completion = arb(N)**(arb(1)/4)*(arb.pi()**(-(HALF + MU)/2)*((HALF + MU)/2).gamma())**2
def total(a):
    s = arb(0)
    for n in range(1, M+1):
        if a[n] == (0, 0): continue
        z = c*n
        s += A(a[n])*z.rsqrt()*(Hv[n] - z.log()*Fv[n])
    # n > M: |a_n| <= n, |z^{-1/2}(H - log z F)| = z^{-1/2} int_z^oo K0(x) x^{mu-1/2} log(x/z) dx
    #   <= z^{-1/2} sqrt(pi/2) int_z^oo x^{mu-1} e^-x (x-z)/z dx <= sqrt(pi/2) z^{mu-5/2} e^-z  (mu=0: x^{-1}<=1/z; mu=1: 1)
    # so term <= sqrt(pi/2) c^{mu-5/2} n^{mu-3/2} e^{-cn}; bound n^{mu-3/2} <= n^{1/2} crude
    tl = sp*c**(MU - arb(5)/2)*geo_tail(M+1, c*(M+1), c, HALF)
    return PREF*(s + arb(0, tl.upper())), tl
res = {}
for nm, a in (('rho', A_r), ('rho_conj', A_c)):
    Lam, tl = total(a)
    Lp = Lam/completion
    res[nm] = dict(W=-1, Lambda_prime_half=Lam.str(30, radius=True), L_prime_half=Lp.str(30, radius=True),
                   lower=float(Lp.lower()), upper=float(Lp.upper()), radius=float(Lp.rad()), n_tail_bound=tl.str(5),
                   excludes_zero=bool(Lp > 0 or Lp < 0))
    print(nm, res[nm], flush=True)
res['rho']['pari_float'] = PARI_LP
out.update(res)
out['completion'] = completion.str(25)
out['seconds'] = time.time() - t0
tag = f'{LABEL}-cn{int(CN)}-p{ctx.prec}'
(HERE/f'certify-oddW-results-{tag}.json').write_text(json.dumps(out, indent=2) + '\n')
print('PASS' if res['rho']['excludes_zero'] and res['rho_conj']['excludes_zero'] else 'FAIL', out['seconds'])
