#!/usr/bin/env python3
"""Interval certificate that L'(1/2) != 0 for admissible sign -1 quadratic twists of the two
negative-sign Q8 Artin bases, so the forced central zero of each twist is SIMPLE.

Lambda_D'(1/2) = 2 * int_1^inf theta_D(x) x^(-1/2) log x dx   (sign -1 symmetry about x=1)
theta_D(x) = 4 (x/Q_D)^nu sum_n chi_D(n) a_n n^nu K0(2 pi n x / Q_D),  Q_D = Q*D.
Validated Gauss-Legendre on dyadic bands [2^j,2^(j+1)] with the analytic-circle error bound
of q8-extended.py, the |sin(t log u)| factor replaced by a bound on |log u| on the circle.
Explicit coefficient tail and integration tail as in q8-simplicity.py. Base coefficients from
PARI lfunan, cross-checked against the previously audited coefficient lists; twisted
coefficients are exact integers a_n * kronecker(D,n). PARI floating L'(1/2) is a comparison only.
"""
from pathlib import Path
import json,time,sys
from flint import arb,ctx
from cypari2 import Pari
R=Path(__file__).resolve().parent;ctx.prec=256
p=Pari();p.allocatemem(1024000000);p.set_real_precision(38)
old={f['label']:f for f in json.loads((R/'q8-results.json').read_text())['fields']}
classic=json.loads((R/'q8-magma-results.json').read_text())
audited={'2.2304.8t5.b.a':old['2.2304.8t5.b.a']['coefficients_first_2000'],
         classic['label']:json.loads((R/'q8-coefficients-results.json').read_text())['coefficients']}
bases={'2.2304.8t5.b.a':dict(polynomial=old['2.2304.8t5.b.a']['polynomial'],Q=48,nu=1),
       classic['label']:dict(polynomial=classic['lmfdb_polynomial'],Q=205,nu=0)}
pari=json.loads((R/'twist-derivs-pari-results.json').read_text())
GAUSS=48
roots=[arb.legendre_p_root(GAUSS,k,weight=True) for k in range(GAUSS)]
def S2(r,m):return r**m*(m*m/(1-r)+2*m*r/(1-r)**2+r*(1+r)/(1-r)**3)
outpath=R/'twist-simplicity-results.json'
rec=json.loads(outpath.read_text()) if outpath.exists() else dict(method=__doc__,arb_bits=ctx.prec,gauss_order=GAUSS,cases=[])
done={(c['base'],c['D']) for c in rec['cases']}
jobs=[(b,int(D)) for b,D in (a.split(':') for a in sys.argv[1:])]
coef={}
for label,D in jobs:
    if (label,D) in done:continue
    t0=time.monotonic();B=bases[label];Q=B['Q']*D;nu=B['nu'];c=2*arb.pi()/Q
    M=int(70*Q/6.2832)+1  # e^{-cM} about e^{-70}
    U=1
    while float((c*U).mid())<75:U*=2
    if label not in coef or len(coef[label])<M:
        p(f'P={B["polynomial"]};NF=nfinit(P);G=galoisinit(NF);TC=galoischartable(G);L=lfunartin(NF,G,TC[1][,5],TC[2]);')
        coef[label]=[int(x) for x in p(f'lfunan(L,{M})')]
    a=coef[label][:M];aud=audited[label]
    k=min(len(a),len(aud));assert a[:k]==list(aud)[:k],'PARI coefficients disagree with audited list'
    assert int(p(f'isfundamental({D})'))==1 and D>0
    tw=[a[n-1]*int(p.kronecker(D,n)) for n in range(1,M+1)]
    terms=[(c*n,tw[n-1]*n**nu) for n in range(1,M+1) if tw[n-1]]
    absterms=[(cn,abs(an)) for cn,an in terms]
    C=8*arb(Q)**(-nu)*(arb.pi()/(2*c)).sqrt()
    en=C*(1/c+1/c**2)*S2((-c).exp(),M+1)
    rt=(-c*U).exp();eu=C*(arb(U)/c+1/c**2)*rt*(1+rt)/(1-rt)**3
    alpha=(arb(2)/3).asin();quad=arb(0);I=arb(0)
    for j in range(U.bit_length()-1):
        lo=arb(2)**j;mid=3*lo/2;half=lo/2
        absolute=sum(an*(cn*lo/2).bessel_k(0) for cn,an in absterms)
        logb=max(abs((lo/2).log()).upper(),abs((5*lo/2).log()).upper())+alpha
        Ma=16/lo*(5*lo/(2*Q))**nu*(5*lo/2)**(arb(3)/2)*logb*absolute
        quad+=4*lo*Ma*arb(2)**(-2*GAUSS)
        for r,w in roots:
            u=mid+half*r
            theta=4*(u/Q)**nu*sum(an*(cn*u).bessel_k(0) for cn,an in terms)
            I+=2*half*w*theta*u.log()/u.sqrt()
    err=en+eu+quad
    Lam=I+arb(0,err.upper())
    completion=arb(Q).sqrt()*arb.pi()**(-arb(1)/2-nu)*(arb(1)/4+arb(nu)/2).gamma()**2
    Lp=Lam/completion
    ref=[r for r in pari if r['base']==label and r['D']==D][0]
    agrees=Lp.contains(arb(ref['Lprime_half'][:30])) or abs(float(Lp.mid())-float(ref['Lprime_half']))<1e-20
    row=dict(base=label,D=D,Q=Q,gamma_shift=nu,coefficient_cutoff=M,audited_prefix_checked=min(M,len(audited[label])),integration_cutoff=U,nodes=GAUSS*(U.bit_length()-1),
        coefficient_tail=en.str(10),integration_tail=eu.str(10),quadrature_error=quad.str(10),
        Lprime_enclosure=Lp.str(40,more=True),excludes_zero=bool(Lp>0 or Lp<0),
        central_multiplicity=1 if (Lp>0 or Lp<0) else None,pari_float_comparison=ref['Lprime_half'],agrees_with_pari=bool(agrees),
        elapsed_seconds=round(time.monotonic()-t0,1))
    print(row,flush=True)
    rec['cases'].append(row);outpath.write_text(json.dumps(rec,indent=2)+'\n')
