#!/usr/bin/env python3
"""Interval (Arb/FLINT) certificate for the binary-octahedral (2O = GAP [48,28]) field
of polyhedral-fields-20261112.md (PARI galpol degree-48 real field, conductor 924800 = 2^7 5^2 17^2):

  (i)  rho      (PARI char col 5, root number -1): L'(rho, 1/2) != 0, so the forced central zero is simple;
  (ii) rho(x)eps (PARI char col 4, root number +1): L(rho(x)eps, 1/2) != 0.

Method (differs from tetra1112/certify_lprime.py, whose Riemann-sum hulls are far too wide at this
conductor): exact termwise Mellin integrals.  For Vga = [0,0],
    Lambda(s) = N^{s/2} Gamma_R(s)^2 L(s) = int_0^oo theta(y) y^{s-1} dy,  theta(y) = 4 sum a_n K0(c n y),  c = 2 pi / sqrt(N),
and (entire Lambda, Lambda(s) = W Lambda(1-s), W = +-1)
    W = -1:  Lambda'(1/2) = 4 sum a_n G1(c n),  G1(z) = 2 int_1^oo K0(z y) y^{-1/2} log y dy = 2 z^{-1/2} [H(z) - log z F(z)],
    W = +1:  Lambda(1/2)  = 4 sum a_n G0(c n),  G0(z) = 2 z^{-1/2} F(z),
with F(z) = int_z^oo K0(x) x^{-1/2} dx and H(z) = int_z^oo K0(x) x^{-1/2} log x dx, computed by chaining
acb.integral (rigorous Gauss-Legendre with error bounds) over [c n, c (n+1)] downward from a top point,
plus explicit tails.  Coefficients: exact in Z[sqrt2] from PARI lfunartin a_p, built multiplicatively
(det = 1; ramified 2,5,17 have Euler factor 1), audited against (a) PARI's own a_n for every n <= NMAX,
(b) residue degrees from idealprimedec (= order of Frobenius), (c) eps(p) = (p/5).
The root numbers are certified (not assumed) from the theta relation theta(1/y) = W y theta(y) at y = 2.
No RH claim: this is a finite check of two Artin L-values at s = 1/2.
"""
import json, math, sys, time
from pathlib import Path
from flint import arb, acb, ctx
HERE = Path(__file__).resolve().parent
ctx.prec = int(sys.argv[2]) if len(sys.argv) > 2 else 160
CN = float(sys.argv[1]) if len(sys.argv) > 1 else 120.0   # truncate where c*n > CN
D = json.loads((HERE/'pari-data.json').read_text())
NMAX = D['NMAX']; N = 924800; RAM = (2, 5, 17)
S2f = math.sqrt(2)

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]]

def recog(x):
    for (u, v) in ((2,0),(-2,0),(1,0),(-1,0),(0,0),(0,1),(0,-1)):
        if abs(x - (u + v*S2f)) < 1e-8: return (u, v)
    raise ValueError(x)

def legendre5(p):
    r = p % 5
    return 0 if r == 0 else (1 if r in (1, 4) else -1)

def build(an_float, twist):
    """exact a_n = (u,v) meaning u + v sqrt2, n=1..NMAX"""
    PR = primes_upto(NMAX)
    a = [None]*(NMAX+1); a[1] = (1, 0)
    pp = {}
    for p in PR:
        if p in RAM:
            pp[p] = {}; continue
        ap = recog(an_float[p-1][0]); assert abs(an_float[p-1][1]) < 1e-8
        seq = [(1, 0), ap]; k = 1; q = p
        while q*p <= NMAX:
            x, y = seq[-1]; u, v = ap; z, w = seq[-2]
            # (u+v r)(x+y r) - (z+w r), r^2 = 2
            seq.append((u*x + 2*v*y - z, u*y + v*x - w)); q *= p; k += 1
        pp[p] = {k: seq[k] for k in range(1, len(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 in RAM else pp[p][k]
        x, y = a[m]; u, v = loc
        a[n] = (u*x + 2*v*y, u*y + v*x)
    # audit vs PARI floats
    worst = 0.0
    for n in range(1, NMAX+1):
        u, v = a[n]; worst = max(worst, abs(u + v*S2f - an_float[n-1][0]), abs(an_float[n-1][1]))
    return a, pp, worst

t0 = time.time()
out = dict(field='2O = GAP [48,28], PARI galpol real degree-48 polynomial (poly1112/measure_2O.py P48)', conductor=N,
           arb_prec_bits=ctx.prec, cn_cutoff=CN, NMAX=NMAX)
a_r, pp_r, w_r = build(D['Lr']['an'], False)
a_t, pp_t, w_t = build(D['Lr2']['an'], False)
out['coeff_audit_vs_pari_max_abs_diff'] = dict(rho=w_r, rho_eps=w_t)
# audit: rho_eps = rho * (n/5); residue degrees
mis_tw = sum(1 for n in range(1, NMAX+1) if a_t[n] != tuple(legendre5(n)*x for x in a_r[n]))
# legendre5 is completely multiplicative, so this checks the twist at every n
exp_by_f = {1: {(2,0)}, 2: {(-2,0)}, 3: {(-1,0)}, 6: {(1,0)}, 4: {(0,0)}, 8: {(0,1),(0,-1)}}
mis_deg = 0; nchk = 0
eps_pari = D['Le']['an']; mis_eps = 0
for ps, f in D['residue_degree'].items():
    p = int(ps); nchk += 1
    if a_r[p] not in exp_by_f[f]: mis_deg += 1
    if abs(eps_pari[p-1][0] - legendre5(p)) > 1e-8: mis_eps += 1
    # eps(Frob) = -1 exactly on the odd classes: order 8, and order 4 with ... (size-12 class); check order-8 primes
    if f == 8 and legendre5(p) != -1: mis_eps += 1
out['audit'] = dict(twist_equals_rho_times_legendre5_mismatches=mis_tw, primes_checked_residue_degree=nchk,
                    residue_degree_mismatches=mis_deg, eps_mismatches=mis_eps)
print('audit', out['audit'], out['coeff_audit_vs_pari_max_abs_diff'], flush=True)
assert mis_tw == 0 and mis_deg == 0 and mis_eps == 0 and w_r < 1e-8 and w_t < 1e-8

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

# ---- root numbers from theta(1/2) vs 2 theta(2) -----------------------------------------------------------
def theta(a, y, nmax):
    y = arb(y); s = arb(0)
    for n in range(1, nmax+1):
        if a[n] == (0, 0): continue
        s += A(a[n])*(c*n*y).bessel_k(0)
    r = (-c*y).exp(); m = nmax+1
    tail = 4*(arb.pi()/(2*c*y)).sqrt()*r**m*(m/(1-r) + r/(1-r)**2)
    return 4*s + arb(0, tail.upper())
rootno = {}
for nm, a in (('rho', a_r), ('rho_eps', a_t)):
    th_half = theta(a, arb(1)/2, NMAX); th2 = theta(a, 2, M)
    Wb = th_half/(2*th2)
    th1 = theta(a, 1, M)
    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(15), two_theta_2=(2*th2).str(15), ratio=Wb.str(15), theta_1=th1.str(15), W=W)
    print(nm, rootno[nm], flush=True)
    assert W is not None
out['root_numbers'] = rootno
assert rootno['rho']['W'] == -1 and rootno['rho_eps']['W'] == 1

# ---- F and H tables ---------------------------------------------------------------------------------------
def f_FH(x, analytic):
    if analytic and (x.real < 0 or x.real.contains(0)):
        z = acb(0); return z/z
    return x.bessel_k(0)*x.rsqrt(analytic=analytic)*(1 + acb(0, 1)*x.log(analytic=analytic))
t1 = time.time()
X0 = c*(M+1)
# tails beyond X0: K0(x) <= sqrt(pi/(2x)) e^-x  =>  F-tail <= sqrt(pi/2) e^-X0 / X0 ; H-tail <= sqrt(pi/2) e^-X0 (log x/x < 1)
bF = (arb.pi()/2).sqrt()*(-X0).exp()/X0; bH = (arb.pi()/2).sqrt()*(-X0).exp()
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)
    Fv[n] = Fv[n+1] + piece.real; Hv[n] = Hv[n+1] + piece.imag
    if n % 3000 == 0: print('  F/H table n =', n, f'{time.time()-t1:.0f}s', flush=True)
out['FH_table_seconds'] = time.time()-t1
# sanity: F(0+) -> 2^{-3/2} Gamma(1/4)^2, H(0+) -> 2^{-3/2} Gamma(1/4)^2 (log 2 + psi(1/4)) (Mellin of K0); compare at z = c
F0 = arb(2)**(-arb(3)/2)*(arb(1)/4).gamma()**2
out['sanity_F_c_vs_F0'] = dict(F_c=Fv[1].str(20), F0=F0.str(20), note='F(0)-F(c) should be about 2 sqrt(c)(2-log(c/2)-gamma) (leading terms of K0 near 0)')

# ---- sums ---------------------------------------------------------------------------------------------------
def total(a, which):
    s = arb(0)
    for n in range(1, M+1):
        if a[n] == (0, 0): continue
        z = c*n
        if which == 1: G = 2*z.rsqrt()*(Hv[n] - z.log()*Fv[n])
        else: G = 2*z.rsqrt()*Fv[n]
        s += A(a[n])*G
    # n > M tail: |a_n| <= d(n) <= n ;  G1(z) <= 2 sqrt(pi/(2z)) e^-z / z^2 ; G0(z) <= 2 sqrt(pi/(2z)) e^-z / z
    k = 2 if which == 1 else 1
    tail = 2*(arb.pi()/(2*c)).sqrt()*c**(-k)*(-c*(M+1)).exp()/(1-(-c).exp())
    return 4*(s + arb(0, tail.upper())), tail
completion = arb(N)**(arb(1)/4)*arb.pi()**(-arb(1)/2)*(arb(1)/4).gamma()**2
Lam1, tail1 = total(a_r, 1)
Lam0, tail0 = total(a_t, 0)
Lp = Lam1/completion; Lh = Lam0/completion
out['rho'] = dict(lfmdb_note='PARI char col 5', W=-1, Lambda_prime_half=Lam1.str(30, radius=True), L_prime_half=Lp.str(30, radius=True),
                  L_prime_lower=float(Lp.lower()), L_prime_upper=float(Lp.upper()), radius=float(Lp.rad()), n_tail_bound=tail1.str(5),
                  excludes_zero=bool(Lp > 0 or Lp < 0), pari_float=D['pari_float_Lprime_rho_half'])
out['rho_eps'] = dict(lmfdb_note='PARI char col 4', W=1, Lambda_half=Lam0.str(30, radius=True), L_half=Lh.str(30, radius=True),
                      L_half_lower=float(Lh.lower()), L_half_upper=float(Lh.upper()), radius=float(Lh.rad()), n_tail_bound=tail0.str(5),
                      excludes_zero=bool(Lh > 0 or Lh < 0), pari_float=D['pari_float_L_rhoeps_half'])
out['completion'] = completion.str(20)
out['seconds'] = time.time()-t0
print(json.dumps({k: out[k] for k in ('rho', 'rho_eps')}, indent=1), flush=True)
tag = f'cn{int(CN)}-p{ctx.prec}'
(HERE/f'certify-octa-results-{tag}.json').write_text(json.dumps(out, indent=2)+'\n')
print('PASS' if out['rho']['excludes_zero'] and out['rho_eps']['excludes_zero'] else 'FAIL', out['seconds'])
