#!/usr/bin/env python3
"""2I galpol field (ramified 2, 11, 23): Artin L-functions of the two faithful 2-dim characters rho, rho'.
Find the conductor 2^a*11^2*23^2 and the root number from the functional equation; then central values.
Unramified Euler factor 1 - 2Re(q) x + x^2 (Frobenius quaternion q in SU(2)); ramified factors 1
(inertia at 2 is a nontrivial 2-group, at 11 has order 6, at 23 order 3: no fixed vectors in a faithful rho)."""
import json, glob, math, sys, time
from pathlib import Path
from cypari2 import Pari
HERE=Path(__file__).resolve().parent; P12=HERE.parent/'poly1112'
res=json.loads((P12/'measure-2I-results.json').read_text())
qinfo=res['quaternion_classes']
pclass={int(k):v for k,v in res['pclass'].items()}
bl=json.loads((HERE/'blocked-frob.json').read_text())
for k,v in bl['blocked'].items(): pclass[int(k)]=v['qidx']
for f in glob.glob(str(HERE/'pclass-*.json')):
    pclass.update({int(k):v for k,v in json.loads(Path(f).read_text()).items()})
NMAX=max(pclass)
pari=Pari(); pari.allocatemem(2*10**9)
plist=[int(p) for p in pari(f'primes([2,{NMAX}])')]
missing=[p for p in plist if p not in pclass and p not in (2,11,23)]
assert not missing, missing[:10]
# conjugation sqrt5 -> -sqrt5 on traces 2cos(2pi k/5 or /10)
s5=math.sqrt(5)
tr=[2*c['re'] for c in qinfo]
def conjtr(t):
    for a,b in (((s5-1)/2,(-s5-1)/2),((s5+1)/2,(-s5+1)/2)):
        if abs(t-a)<1e-9: return b
        if abs(t-b)<1e-9: return a
    return t
def an_vec(trmap):
    a=[0.0]*(NMAX+1); a[1]=1.0
    # multiplicative build via prime powers
    pp={}
    for p in plist:
        if p in (2,11,23): continue
        t=trmap(tr[pclass[p]]); c=[1.0,t]; k=1
        while p**(k+1)<=NMAX:
            c.append(t*c[-1]-c[-2]); k+=1
        pp[p]=c
    # sieve: smallest prime factor
    spf=list(range(NMAX+1))
    for p in plist:
        if p*p>NMAX: break
        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
        a[n]= (0.0 if p in (2,11,23) else pp[p][k])*a[m]
    return a[1:]
out=dict(NMAX=NMAX, nprimes=len(plist))
for name,trmap in (('rho',lambda t:t),('rho_conj',conjtr)):
    av=an_vec(trmap)
    pari.set_real_precision(19)
    pari('AV=[' + ','.join(repr(x) for x in av) + '];')
    scan={}
    for a in range(2,13):
        N=2**a*121*529
        for eps in (1,-1):
            try:
                v=int(pari(f'L=lfuncreate([AV,0,[0,0],1,{N},{eps}]); lfuncheckfeq(L)'))
            except Exception as e:
                v=str(e)[:80]
            scan[f'{a},{eps}']=v
            print(name,'a',a,'eps',eps,'checkfeq',v,flush=True)
    out[name]=dict(scan=scan)
    best=min((v,k) for k,v in scan.items() if isinstance(v,int))
    a,eps=map(int,best[1].split(',')); N=2**a*121*529
    pari.set_real_precision(38)
    pari(f'L=lfuncreate([AV,0,[0,0],1,{N},{eps}]);')
    rec=dict(a2=a, conductor=N, eps=eps, checkfeq_best=best[0])
    try:
        rec['checkfeq_38dig']=int(pari('lfuncheckfeq(L)'))
        rec['L_half']=str(pari('lfun(L,1/2)'))
        rec['Lprime_half']=str(pari('lfun(L,1/2,1)'))
        rec['L_2']=str(pari('lfun(L,2)'))
    except Exception as e:
        rec['err']=str(e)[:200]
    e2=1.0
    for p in plist:
        if p in (2,11,23): continue
        t=trmap(tr[pclass[p]]); x=p**-2.0; e2*=1/(1-t*x+x*x)
    rec['L_2_eulerprod_p_le_NMAX']=e2
    rec['W_check_other_eps']=int(pari(f'lfuncheckfeq(lfuncreate([AV,0,[0,0],1,{N},{-eps}]))'))
    out[name].update(rec); print(name,rec,flush=True)
(HERE/'lfun-2I-results.json').write_text(json.dumps(out,indent=1))
