#!/usr/bin/env python3
"""L(3 = Sym^2 rho, s) and L(3' = Sym^2 rho', s) for the root-number -1 2I fields 2.3806401.120.a (p0=1951) and
2.4583881.120.a (p0=2141), from the ORIENTED Frobenius traces a_p(rho) of cert1113/oriented_2I.py (all p < 1.2e5).
Exact coefficients in Z[phi] (integer pairs x+y*phi), sent to PARI as x+y*quadgen(5)-> real at BITS.
Local data (project, from D abelian at p0, cf. icosa-oddW-aligned-exponent-20261114.md §2): Sym^2 rho|D = psi^2 + 1 + psi^-2,
conductor p0^2, Euler factor (1-p0^-s)^-1; Gamma_R(s)^3 for both fields (rho(c) = +-1 acts trivially on Sym^2).
FLOAT numerics (PARI lfun), not interval. Presupposes Artin holomorphy.
usage: oddW_sym2.py LABEL REP(three|threep) BITS NMAX [p2flip]"""
import sys, json, time
from pathlib import Path
from cypari2 import Pari
HERE = Path(__file__).resolve().parent; HC = HERE.parent
label, rep, bits, NM = sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv[4])
flip = len(sys.argv) > 5 and sys.argv[5] == 'p2flip'
fn = HC/'cert1113'/(f'ap-oriented-{label}' + ('-p2flip' if flip else '') + '.json')
d = json.loads(fn.read_text()); N0 = int(d['N']); p0 = int(round(N0**0.5)); assert p0*p0 == N0
PHI = (1+5**0.5)/2
def topair(a):
    for v, pr in ((2,(2,0)),(-2,(-2,0)),(0,(0,0)),(1,(1,0)),(-1,(-1,0)),(PHI,(0,1)),(-PHI,(0,-1)),(PHI-1,(-1,1)),(1-PHI,(1,-1))):
        if abs(a-v) < 1e-9: return pr
    raise ValueError(a)
def conj(pr): x, y = pr; return (x+y, -y)          # sigma(phi) = 1 - phi
def mul(a, b): return (a[0]*b[0]+a[1]*b[1], a[0]*b[1]+a[1]*b[0]+a[1]*b[1])
def add(a, b): return (a[0]+b[0], a[1]+b[1])
def sub(a, b): return (a[0]-b[0], a[1]-b[1])
ap = {}
for k, v in d['ap'].items():
    if v is None: continue
    pr = topair(v); ap[int(k)] = conj(pr) if rep == 'threep' else pr
lim = max(ap)+1; assert NM <= lim, (NM, lim)
K = 20
def hseq(t):   # Sym^2 with trace t: e1 = t, e2 = t, e3 = 1
    h = [(1,0)]
    for k in range(1, K+1):
        s = mul(t, h[k-1])
        if k >= 2: s = sub(s, mul(t, h[k-2]))
        if k >= 3: s = add(s, h[k-3])
        h.append(s)
    return h
loc = {}
for p, a in ap.items():
    t = sub(mul(a, a), (1, 0)); loc[p] = hseq(t)
loc[p0] = [(1,0)]*(K+1)
spf = list(range(NM+1))
for p in range(2, int(NM**.5)+1):
    if spf[p] == p:
        for m in range(p*p, NM+1, p):
            if spf[m] == m: spf[m] = p
A = [(0,0)]*(NM+1); A[1] = (1,0)
for n in range(2, NM+1):
    p = spf[n]; m = n; k = 0
    while m % p == 0: m //= p; k += 1
    A[n] = mul(loc[p][k], A[m])
pari = Pari(); pari.allocatemem(3*10**9); pari.set_real_precision_bits(bits)
pari('w=(1+sqrt(5))/2;')
AV = pari([pari(f'{x}+({y})*w') if y else pari(x) for (x, y) in A[1:]])
N = p0**2
out = dict(label=label, rep=rep, bits=bits, nan=NM, N=N, p2flip=flip, a2=str(A[2]))
pari('(v)->AVG=v')(AV)   # GP-side evaluation so that the working precision is BITS (cypari method calls default to 64 bits)
for W in (1, -1):
    out[f'checkfeq_W{W}'] = int(pari(f'lfuncheckfeq(lfuncreate([AVG,0,[0,0,0],1,{N},{W}]))'))
pari(f'LG=lfuncreate([AVG,0,[0,0,0],1,{N},1]);')
out['cost'] = str(pari('lfuncost(LG,[0,0])'))
out['checkfeq_wrongGamma[1,1,0]'] = int(pari(f'lfuncheckfeq(lfuncreate([AVG,0,[1,1,0],1,{N},1]))'))
out['L_half'] = str(pari('lfun(LG,1/2)'))
out['L_half_der1'] = str(pari('lfun(LG,1/2,1)'))
out['L2'] = str(pari('lfun(LG,2)'))
L = pari('LG')
# Euler product at s=2 over p < lim (incl. p0 factor)
ep = pari('1.')
for p, h in loc.items():
    t = h[1]; tv = t[0] + t[1]*PHI
    x = p**-2.0
    ep *= 1.0/((1-x)*(1 - (tv-1)*x + x*x)) if p != p0 else 1.0/(1-x)
out['L2_euler_float'] = float(ep)
out['orderzero'] = int(pari('lfunorderzero(LG)'))
print(json.dumps(out), flush=True)
json.dump(out, open(HERE/f'oddW-{rep}-{label}-b{bits}-n{NM}{"-p2flip" if flip else ""}.json', 'w'), indent=1)
