#!/usr/bin/env python3
"""Field-level 2O check: galpol real S48-Galois field, Gal = [48,28] = 2O.
Frobenius classes from Artin characters (lfunartin), aligned Euler product of
Model A along the certified β-minimiser I*, slope of log nrd vs log(2σ-1).
"""
import json, math, time, sys
from pathlib import Path
import numpy as np
from collections import Counter
from cypari2 import Pari

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent / 'beta1112'))
from groups import group as qgroup, qmul, classes as qclasses

P48 = ('x^48-240*x^46+25920*x^44-1678000*x^42+73172500*x^40-2289120000*x^38+'
       '53407835000*x^36-953417800000*x^34+13252719687500*x^32-145174013000000*x^30+'
       '1263298386275000*x^28-8774902841000000*x^26+48752581206125000*x^24-'
       '216556444800000000*x^22+766756434906250000*x^20-2151558775875000000*x^18+'
       '4741960222000000000*x^16-8102659497500000000*x^14+10539042418750000000*x^12-'
       '10168138068750000000*x^10+7010849148593750000*x^8-3267296725000000000*x^6+'
       '941829776562500000*x^4-143551718750000000*x^2+8156347656250000')

# certified minimiser from beta1112/exact.json (groups.py coordinates)
Istar = np.array([0.8432633099626551494622691,
                  -0.214935276248321137164764,
                  -0.4926558810111626630336896])
Istar = Istar / np.linalg.norm(Istar)
BETA_MIN = 0.1487126053742838865496535571920854802404

# PARI class index (1-based as in galoischartable rows) — filled after sanity
# χ_ρ we use is character 5 (root number -1, simple central zero):
# values on classes 1..8: 2, 0, 1, -1, √2, 0, -√2, -2
# distinguished order-4 classes by the sign character (col 2): class 2 ε=-1, class 6 ε=+1

RAM = (2, 5, 17)
X = int(sys.argv[1]) if len(sys.argv) > 1 else 20000

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 nrd_local(g, r, phi, I):
    """nrd(1 - g * r (cos φ - I sin φ))."""
    # Re(gw) = Re(g) r cosφ + (pure(g)·I) r sinφ
    re = g[0]*r*math.cos(phi) + float(np.dot(g[1:], I))*r*math.sin(phi)
    return 1.0 - 2.0*re + r*r

def main():
    out = dict(group='2O', source='PARI galpol-4 real polynomial, galoisidentify [48,28]',
               polynomial=P48, ramified=list(RAM), Istar=Istar.tolist(),
               beta_min_predicted=BETA_MIN, X=X)
    # quaternion classes in groups.py coordinates
    G = qgroup('2O')
    clQ = qclasses(G)
    qinfo = []
    for C in clQ:
        g = C[0]; ax = g[1:]; nrm = np.linalg.norm(ax)
        # optimal representative for I*
        best, bestsc = None, -1
        for h in C:
            an = h[1:]; nn = np.linalg.norm(an)
            if nn < 1e-12:
                sc = 0.0; u = np.zeros(3)
            else:
                u = an/nn; sc = float(u @ Istar)**2
            if sc > bestsc:
                bestsc, best, bestu = sc, h, u
        qinfo.append(dict(size=len(C), order=int(round(max(1, 2*math.pi/max(1e-9, math.acos(max(-1,min(1,g[0]))))))),
                          re=float(g[0]), sin2=float(1-g[0]**2),
                          aligned=[float(x) for x in best],
                          axis_aligned=bestu.tolist(), align=(bestsc),
                          beta_local=float((1-g[0]**2)*(1-bestsc))))
    # fix orders properly
    def qorder(g):
        ident=np.array([1.,0,0,0]); r,n=g,1
        while n<40 and np.linalg.norm(r-ident)>1e-8:
            r=qmul(r,g); n+=1
        return n
    for i,C in enumerate(clQ):
        qinfo[i]['order']=qorder(C[0])
        qinfo[i]['size']=len(C)

    # map PARI class -> qinfo index by (size, order, sign of Re / ε)
    # computed after we build a_p; here by invariants:
    # PARI 1 id, 8 -1, 3 ord6, 4 ord3, 5 Re>0 ord8, 7 Re<0 ord8, 6 ord4 size6, 2 ord4 size12
    pari_to_q = {}
    for i,inf in enumerate(qinfo):
        key = (inf['size'], inf['order'], round(inf['re'], 6))
        pari_to_q.setdefault(key, []).append(i)
    out['quaternion_classes'] = qinfo

    pari = Pari(); pari.allocatemem(4*10**9); pari.set_real_precision(38)
    t0=time.time()
    print('setup...', flush=True)
    pari(f'P={P48}; NF=nfinit(P); G=galoisinit(NF); TC=galoischartable(G);')
    assert [int(x) for x in pari('galoisidentify(G)')]==[48,28]
    # characters 2 (ε, cond 5), 5 (ρ, rootno -1)
    print('lfunartin ε and ρ...', flush=True)
    pari('Le=lfunartin(NF,G,TC[1][,2],8); Lr=lfunartin(NF,G,TC[1][,5],8); Lr2=lfunartin(NF,G,TC[1][,4],8);')
    par_r = pari('lfunparams(Lr)'); par_r2=pari('lfunparams(Lr2)'); par_e=pari('lfunparams(Le)')
    def unpack(par):
        return dict(conductor=int(par[0]), Vga=[int(x) for x in par[2]])
    out['L_rho'] = unpack(par_r)
    out['L_rho']['rootno'] = str(pari('lfunrootres(Lr)[3]'))
    out['L_rho']['ordzero'] = int(pari('lfunorderzero(Lr)'))
    out['L_rho_twist'] = unpack(par_r2)
    out['L_rho_twist']['rootno'] = str(pari('lfunrootres(Lr2)[3]'))
    try:
        out['L_rho_twist']['ordzero'] = int(pari('lfunorderzero(Lr2)'))
    except Exception as e:
        out['L_rho_twist']['ordzero'] = str(e)
    out['L_eps'] = unpack(par_e)
    print('ρ', out['L_rho'], 'ρ⊗ε', out['L_rho_twist'], 'ε', out['L_eps'], flush=True)

    print(f'lfunan to {X}...', flush=True)
    t1=time.time()
    pari(f'Ar=lfunan(Lr,{X}); Ae=lfunan(Le,{X});')
    print('lfunan done', time.time()-t1, flush=True)
    PR = primes_upto(X)
    # classify primes
    SQRT2 = math.sqrt(2)
    def cls_of(p):
        # skip ramified
        a = complex(pari(f'Ar[{p}]')).real
        e = complex(pari(f'Ae[{p}]')).real
        # match
        if abs(a-2)<1e-8: return 1
        if abs(a+2)<1e-8: return 8
        if abs(a-1)<1e-8: return 3
        if abs(a+1)<1e-8: return 4
        if abs(a-SQRT2)<1e-6: return 5
        if abs(a+SQRT2)<1e-6: return 7
        if abs(a)<1e-8:
            return 6 if e>0 else 2
        return f'UNRECOGNIZED a={a} e={e}'

    # map PARI class id -> qinfo index
    def qindex_for_pari(c):
        # unique by (size, order, re)
        meta = {1:(1,1,1.0), 8:(1,2,-1.0), 3:(8,6,0.5), 4:(8,3,-0.5),
                5:(6,8, SQRT2/2), 7:(6,8, -SQRT2/2),
                6:(6,4,0.0), 2:(12,4,0.0)}
        sz,od,re=meta[c]
        hits=[i for i,inf in enumerate(qinfo) if inf['size']==sz and inf['order']==od and abs(inf['re']-re)<1e-3]
        assert len(hits)==1, (c,sz,od,re,hits)
        return hits[0]

    pclass={}; freq=Counter(); bad=[]
    for q in PR:
        if q in RAM: continue
        c=cls_of(q)
        if isinstance(c,str):
            bad.append((q,c)); continue
        pclass[q]=c; freq[c]+=1
    nused=len(pclass)
    out['class_freq']={str(c): freq[c] for c in range(1,9)}
    out['nprimes']=nused
    out['unrecognized']=bad[:10]
    print('class freq', dict(freq), 'unrec', len(bad), 'nused', nused, flush=True)
    # Chebotarev expected
    sizes={1:1,2:12,3:8,4:8,5:6,6:6,7:6,8:1}
    out['chebotarev_expected']={str(c): sizes[c]/48*nused for c in range(1,9)}
    print('expected', out['chebotarev_expected'], flush=True)

    # aligned quaternions per PARI class
    aligned={}
    beta_loc={}
    for c in range(1,9):
        qi=qindex_for_pari(c)
        aligned[c]=np.array(qinfo[qi]['aligned'])
        beta_loc[c]=qinfo[qi]['beta_local']
        print(f'  PARI class {c} -> q[{qi}] order={qinfo[qi]["order"]} size={qinfo[qi]["size"]} re={qinfo[qi]["re"]:.4f} β_loc={beta_loc[c]:.5f}')
    # typo fix below if needed

    # predicted β as Chebotarev sum of beta_local (should equal BETA_MIN)
    beta_from_aligned=sum(sizes[c]/48*beta_loc[c] for c in range(1,9))
    out['beta_from_aligned_reps']=beta_from_aligned
    print('β from aligned reps', beta_from_aligned, 'predicted', BETA_MIN, 'diff', beta_from_aligned-BETA_MIN, flush=True)

    # ---- t=0: nrd E_A(σ) = L(ρ,σ) (partial, ramified primes omitted consistently via PARI L) ----
    print('central L(ρ) slopes...', flush=True)
    pari('Ic=lfuninit(Lr,[0.5,0.6,3]); Ic2=lfuninit(Lr2,[0.5,0.6,3]);')
    def labs(I, s):
        z=complex(pari(f'lfun({I},{s})'))
        return abs(z), z
    eps=[1e-1,1e-2,1e-3,1e-4,1e-5]
    def slopes_of(I):
        lv=[math.log(labs(I, 0.5+e)[0]) for e in eps]
        sl=[(lv[i+1]-lv[i])/(math.log(eps[i+1])-math.log(eps[i])) for i in range(len(eps)-1)]
        return lv, sl
    lv5, sl5 = slopes_of('Ic')
    lv4, sl4 = slopes_of('Ic2')
    Lhalf5=labs('Ic', 0.5)
    Lhalf4=labs('Ic2', 0.5)
    out['central_rho_rootno_minus'] = dict(eps=eps, log_abs=lv5, slopes=sl5, Lhalf=[Lhalf5[1].real, Lhalf5[1].imag],
                                           predicted_slope=1.0, ordzero=out['L_rho']['ordzero'])
    out['central_rho_rootno_plus'] = dict(eps=eps, log_abs=lv4, slopes=sl4, Lhalf=[Lhalf4[1].real, Lhalf4[1].imag],
                                          predicted_slope=0.0, ordzero=out['L_rho_twist']['ordzero'])
    print('char5 (ε=-1) slopes', sl5, 'L(1/2)', Lhalf5)
    print('char4 (ε=+1) slopes', sl4, 'L(1/2)', Lhalf4, flush=True)

    # ---- Model A nrd along I* at generic t and t=0 ----
    def log_nrd_direct(sig, t, XX):
        tot=0.0
        for q,c in pclass.items():
            if q>XX: continue
            r=q**(-sig); phi=t*math.log(q)
            tot += math.log(nrd_local(aligned[c], r, phi, Istar))
        return tot  # this is sum log nrd = -log of the Euler product of 1/nrd, so log nrd E_A = -tot

    def log_nrd_completed(sig, t, XX):
        # -sum log nrd  + β log ζ(2σ) - β_loc terms already: we report log(nrd E) = -sum log nrd_p
        # completed: log nrd E ≈ -sum_{p≤X} log nrd_p  - sum_{p>X} β_loc_expected * (-log(1-p^{-2σ})) ...
        # Use: log nrd E_X_completed = -sum_{p≤X} [log nrd_p + β_loc(p) log(1-p^{-2σ})]  - β log ζ(2σ)
        # wait: nrd E = prod 1/nrd_p, log nrd E = -sum log nrd_p
        # log nrd_p = -β_loc(p) log(1-p^{-2σ}) + rem_p
        # log nrd E = sum β_loc(p) log(1-p^{-2σ}) - sum rem
        #           = -β log ζ(2σ) + β sum_{all} -log(1-p^{-2σ}) wait no
        # ζ(2σ)= prod (1-p^{-2σ})^{-1}, log ζ = -sum log(1-p^{-2σ})
        # sum_p β_loc(p) log(1-p^{-2σ})  ≈ β * sum log(1-p^{-2σ}) = -β log ζ
        # so log nrd E ≈ -β log ζ(2σ) - sum rem
        main=0.0; rem=0.0
        for q,c in pclass.items():
            if q>XX: continue
            r=q**(-sig); phi=t*math.log(q)
            ln=math.log(nrd_local(aligned[c], r, phi, Istar))
            # log(1-p^{-2σ})
            l2=math.log(1-q**(-2*sig))
            rem += ln + beta_loc[c]*l2   # rem piece: log nrd - (-β_loc log(1-p^{-2s})) wait
            # log nrd_p + β_loc log(1-p^{-2σ})  should be the remainder (no r^2 zeta part)
            main += beta_loc[c]*l2
        # missing ramified and p>X in the β log ζ: add full -β log ζ and subtract the included main
        # log nrd E ≈ -sum_{p≤X} log nrd_p  + tail
        #          = -sum rem + (-main) + tail
        logzeta=math.log(abs(float(pari(f'zeta({2*sig})'))))
        # included primes' zeta part is main = sum_{p≤X unram} β_loc log(1-p^{-2σ})
        # full -β log ζ = β sum_{all p} log(1-p^{-2σ})
        # completion: replace main by -β log ζ, keep -sum_{p≤X} rem? 
        # log nrd E = -sum_p log nrd_p = -sum (rem_p - β_loc log(1-p^{-2σ})) = -sum rem + (-main_all)
        #           = -sum rem - β * (sum log(1-p^{-2σ})) = -sum rem + β? no
        # log ζ = - sum log(1-p^{-2σ}), so sum log(1-p^{-2σ}) = -log ζ
        # main_all = β * sum log(1-p^{-2σ}) = -β log ζ
        # log nrd E = -sum rem + main_all = -sum rem - β log ζ
        # truncated rem sum over p≤X unram; tail rem is small
        sumrem=rem
        log_nrd_E = -sumrem - BETA_MIN*logzeta
        # also report uncompleted direct
        direct=0.0
        for q,c in pclass.items():
            if q>XX: continue
            r=q**(-sig); phi=t*math.log(q)
            direct += -math.log(nrd_local(aligned[c], r, phi, Istar))
        return dict(log_nrd_E_completed=log_nrd_E, log_nrd_E_direct=direct,
                    sum_remainder=sumrem, log_zeta_2sig=logzeta)

    barrier={}
    for tval in (0.0, 5.0, 11.3, 23.5):
        vals=[]
        for e in (1e-1, 1e-2, 1e-3, 1e-4):
            d=log_nrd_completed(0.5+e, tval, X)
            vals.append(dict(eps=e, **d))
            print(f'  t={tval} ε={e} completed={d["log_nrd_E_completed"]:.6f} direct={d["log_nrd_E_direct"]:.6f}', flush=True)
        # slopes of completed vs log(2ε)=log(2σ-1)
        sl=[]
        for i in range(len(vals)-1):
            dy=vals[i+1]['log_nrd_E_completed']-vals[i]['log_nrd_E_completed']
            dx=math.log(2*vals[i+1]['eps'])-math.log(2*vals[i]['eps'])
            sl.append(dy/dx)
        # at t=0 the completed β form is not the whole story (L(ρ) zero / forced branch);
        # also record slope of direct and of L
        pred = (out['L_rho']['ordzero'] if tval==0.0 else BETA_MIN)
        barrier[str(tval)]=dict(values=vals, slopes_completed_vs_log_2sig_minus_1=sl,
                                predicted_generic_t=BETA_MIN, predicted_t0_branch=out['L_rho']['ordzero'])
        print(f'  t={tval} slopes', sl, 'pred generic', BETA_MIN, flush=True)
    out['barrier']=barrier
    out['secs']=time.time()-t0
    HERE.joinpath('measure-2O-results.json').write_text(json.dumps(out, indent=1, default=str))
    print('wrote measure-2O-results.json in', out['secs'], 's')

if __name__=='__main__':
    main()
