#!/usr/bin/env python3
"""Part (c): Model A, complex unit I = n = (i+j+k)/sqrt3 (axis of the order-6 subgroup <g6>, g6=(1+i+j+k)/2).
Run with /workspace/tools/pari-venv/bin/python3.
 F6(s)  = prod_{p: Frob not of order 4} (1 - psi_p p^-s)^-1,  psi_p = 1/2 chi_rho + i Im chi_{rho⊗ω}  (the slice value of the aligned rep)
 claim  F6 = L(rho)^{1/2} [L(rho⊗ω)/L(rho⊗ω̄)]^{1/2} Λ4(2s)^{1/8} H(s),  Λ4 = ζ L(ω) L(ω̄) / L(psi3)   (all partial: p=163 removed)
 O4(σ,t)= prod_{p: order 4} (1 - 2c p^-σ sin(t log p) + p^-2σ)^-1, c = u·n = 1/sqrt3 (rep u in {i,j,k})
 claim  log O4 = -(c/2) Im log Λ4(s) - (c²/4) log|Λ4(2s)| - ((1-c²)/4) log Λ4(2σ) + log K,  K local terms O(p^-3σ)
 Model A norm nrd E_A(σ+tI) = |F6|² · O4 (choice-free up to the sign of u·n in the linear term)."""
import json, math, cmath, time, sys
import numpy as np
from cypari2 import Pari
pari = Pari(); pari.allocatemem(6*10**9); pari.set_real_precision(30)
RAB = json.load(open('results-ab.json'))
FIELDS = {'2.26569.24t7.b.a': 'x^8-x^7+x^6-4*x^5+5*x^4-8*x^3+4*x^2-8*x+16',
          '2.26569.24t7.a.a': 'x^8-x^7-44*x^6+43*x^5+442*x^4-32*x^3-1311*x^2-1156*x-241'}
X = int(sys.argv[1]) if len(sys.argv) > 1 else 200000
Z3 = cmath.exp(2j*math.pi/3); c = 1/math.sqrt(3)
TG = np.round(np.arange(0, 40.0001, 0.1), 10)
def gp(s): return complex(pari(s))
OUT = {}
def eig(cl):  # eigenvalues for the local factors, from (chi_rho, omega) of Frob
    a, w = cl
    # rho eigenvalues e^{±iθ}: θ from a = 2cosθ
    th = math.acos(max(-1, min(1, a/2)))
    e = [cmath.exp(1j*th), cmath.exp(-1j*th)]
    return dict(rho=e, rw=[w*x for x in e], rwb=[w.conjugate()*x for x in e], om=[w], omb=[w.conjugate()],
                psi3=[e[0]**2, 1, e[1]**2], zeta=[1])
def llog(lams, x):  # log of local factor prod (1 - lam x)^-1, principal series-valid
    return -sum(np.log(1 - l*x) for l in lams)
for lab, pol in FIELDS.items():
    t0 = time.time(); ch = RAB[lab]['characters']
    col = {k: ch[k]['pari_col'] for k in ('rho', 'rho⊗ω', 'rho⊗ω̄', 'ω', 'ω̄', 'psi3')}
    pari(f"P={pol}; S=polredbest(nfsplitting(P)); NF=nfinit(S); G=galoisinit(NF); TC=galoischartable(G);")
    names = {'rho': 'Lr', 'rho⊗ω': 'Lw', 'rho⊗ω̄': 'Lwb', 'ω': 'Lo', 'ω̄': 'Lob', 'psi3': 'L3'}
    for k, v in names.items(): pari(f"{v}=lfunartin(NF,G,TC[1][,{col[k]}],3);")
    pari("Lz=lfuncreate(1);")
    pari(f"Ar=lfunan(Lr,{X}); Ao=lfunan(Lo,{X});")
    PR = [int(q) for q in pari(f"primes([2,{X}])")]
    ar = [complex(pari(f"Ar[{q}]")).real for q in PR]; ao = [complex(pari(f"Ao[{q}]")) for q in PR]
    # sanity: omega(g6)=Z3 convention: psi = 1/2 chi_rho + i Im(chi_rho*omega)
    cls = {}
    for q, a, w in zip(PR, ar, ao):
        if q == 163: continue
        cls[q] = (round(a), complex(round(w.real*2)/2, w.imag))
    eu = {k: str(pari(f"lfuneuler({v},163)")) for k, v in names.items()}
    def loc163(k, s):  # log of the 163 Euler factor of L_k at s (x = 163^-s)
        ex = eu[k]
        x = 163.0**(-s)
        return np.log(complex(eval(ex.replace('^', '**'), {'x': x}))) if ex != '1' else 0j
    eu['zeta'] = '1/(1-x)'   # partial zeta: 163 removed as well
    res = {'euler163': eu}
    # ---- local order of H_p and K_p (series check by small-x scaling) ----
    orders = {}
    for nm, cl in [('1', (2, 1)), ('-1', (-2, 1)), ('4a', (0, 1)), ('6a', (1, Z3)), ('6b', (1, Z3.conjugate())), ('3a', (-1, Z3)), ('3b', (-1, Z3.conjugate()))]:
        a, w = cl; E = eig(cl)
        psi = 0.5*a + 1j*(a*w).imag
        def logH(x):
            f6 = 0 if nm == '4a' else -np.log(1 - psi*x)
            return f6 - 0.5*llog(E['rho'], x) - 0.5*llog(E['rw'], x) + 0.5*llog(E['rwb'], x) \
                   - 0.125*(llog(E['zeta'], x*x) + llog(E['om'], x*x) + llog(E['omb'], x*x) - llog(E['psi3'], x*x))
        def logK(r, ph):
            z = r*cmath.exp(-1j*ph)
            o4 = -math.log(1 - 2*c*r*math.sin(ph) + r*r) if nm == '4a' else 0
            L4 = lambda y: llog(E['zeta'], y) + llog(E['om'], y) + llog(E['omb'], y) - llog(E['psi3'], y)
            return o4 - (-(c/2)*L4(z).imag - (c*c/8)*(L4(z*z) + L4(np.conj(z)**2)).real - ((1 - c*c)/4)*L4(r*r).real)
        xs = [1e-2, 1e-3]
        hH = [abs(logH(x)) for x in xs]; hK = [max(abs(logK(x, ph)) for ph in np.linspace(0, 6.28, 37)) for x in xs]
        oH = math.log10(hH[0]/hH[1]) if hH[1] > 0 else float('inf'); oK = math.log10(hK[0]/hK[1]) if hK[1] > 0 else float('inf')
        orders[nm] = dict(H_order=oH, K_order=oK, absH_x001=hH[0], absK_x001=hK[0], psi=[psi.real, psi.imag])
    res['local_orders'] = orders
    print(lab, 'local orders (order, |value| at x=1e-2; orders meaningless when |value|~1e-17)', {k: (round(v['H_order'], 3), '%.1e' % v['absH_x001'], round(v['K_order'], 3), '%.1e' % v['absK_x001']) for k, v in orders.items()}, flush=True)
    # ---- F6 and O4 at sigma = 2, 3/2 on the t grid ----
    for k, v in names.items(): pari(f"I{v}=lfuninit({v},[2.5,1.6,82]);")
    pari("ILz=lfuninit(Lz,[2.5,1.6,82]);")
    def Lval(nm, s): return gp(f"lfun(I{names[nm]}, {s.real}+{s.imag}*I)") if nm != 'zeta' else gp(f"lfun(ILz,{s.real}+{s.imag}*I)")
    def logpart(nm, svec, branch_anchor=None):
        vals = np.array([Lval(nm, s) for s in svec])
        lg = np.log(np.abs(vals)) + 1j*np.unwrap(np.angle(vals))
        lg = lg - np.array([loc163(nm, s) for s in svec])
        return lg
    for sig in (2.0, 1.5):
        s = sig + 1j*TG
        for XX in (X//4, X):
            lF = np.zeros(len(TG), complex); lH = np.zeros(len(TG), complex); lO = np.zeros(len(TG)); lK = np.zeros(len(TG))
            L4loc = lambda E, y: llog(E['zeta'], y) + llog(E['om'], y) + llog(E['omb'], y) - llog(E['psi3'], y)
            for q, cl in cls.items():
                if q > XX: break
                E = eig(cl); a, w = cl; psi = 0.5*a + 1j*(a*w).imag
                x = q**(-s); x2 = q**(-2*s)
                f6 = np.zeros(len(TG), complex) if a == 0 else -np.log(1 - psi*x)
                lF += f6
                lH += f6 - 0.5*llog(E['rho'], x) - 0.5*llog(E['rw'], x) + 0.5*llog(E['rwb'], x) - 0.125*L4loc(E, x2)
                r = q**(-sig); ph = TG*math.log(q)
                o4 = -np.log(1 - 2*c*r*np.sin(ph) + r*r) if a == 0 else np.zeros(len(TG))
                lO += o4
                lK += o4 - (-(c/2)*L4loc(E, x).imag - (c*c/8)*2*L4loc(E, x2).real - ((1 - c*c)/4)*L4loc(E, np.full(len(TG), r*r)).real)
            if XX == X//4: lF4, lH4, lO4, lK4 = lF, lH, lO, lK
        # closed forms with PARI global values
        lr, lw, lwb = logpart('rho', s), logpart('rho⊗ω', s), logpart('rho⊗ω̄', s)
        lz2, lo2, lob2, l32 = logpart('zeta', 2*s), logpart('ω', 2*s), logpart('ω̄', 2*s), logpart('psi3', 2*s)
        lo1, lob1, l31 = logpart('ω', s), logpart('ω̄', s), logpart('psi3', s)
        lz1 = logpart('zeta', s)
        L4_2s = lz2 + lo2 + lob2 - l32
        L4_s = lz1 + lo1 + lob1 - l31
        L4_2sig = (L4_2s[0]).real  # t=0 value = Λ4(2σ)
        closedF = 0.5*lr + 0.5*lw - 0.5*lwb + 0.125*L4_2s
        # branch anchor at t=0 against the Euler product (fix multiples of 2πi/8 etc.)
        def anchor(direct, closed):
            k = np.round((direct[0] - closed[0]).imag/(2*math.pi)); return closed + 2j*math.pi*k
        errF = np.abs(lF - lH - anchor(lF - lH, closedF)); errF4 = np.abs(lF4 - lH4 - anchor(lF4 - lH4, closedF))
        closedO = -(c/2)*L4_s.imag - (c*c/4)*L4_2s.real - ((1 - c*c)/4)*L4_2sig
        errO = np.abs(lO - lK - closedO); errO4 = np.abs(lO4 - lK4 - closedO)
        naive = np.abs(lF - 0.5*lr)
        res[f'sigma{sig}'] = dict(X=X, maxerr_logF6=float(errF.max()), maxerr_logF6_Xquarter=float(errF4.max()),
            maxerr_logO4=float(errO.max()), maxerr_logO4_Xquarter=float(errO4.max()),
            naive_sqrtL_offset_range=[float(naive.min()), float(naive.max())],
            max_abs_logH=float(np.abs(lH).max()), max_abs_logK=float(np.abs(lK).max()),
            sample=[dict(t=float(TG[i]), logF6_direct=[lF[i].real, lF[i].imag], closed_plus_H=[(closedF[i]+lH[i]).real, (closedF[i]+lH[i]).imag],
                         logO4_direct=float(lO[i]), closed_plus_K=float(closedO[i]+lK[i])) for i in (0, 50, 141, 300, 400)])
        print(lab, 'sigma', sig, {k: v for k, v in res[f'sigma{sig}'].items() if k != 'sample'}, round(time.time()-t0), 's', flush=True)
    # ---- quaternion check: ordered product over aligned primes stays in the slice and equals the complex product ----
    def qm(a, b):
        a0,a1,a2,a3 = a; b0,b1,b2,b3 = b
        return np.array([a0*b0-a1*b1-a2*b2-a3*b3, a0*b1+a1*b0+a2*b3-a3*b2, a0*b2-a1*b3+a2*b0+a3*b1, a0*b3+a1*b2-a2*b1+a3*b0])
    def qinv(a): return np.array([a[0], -a[1], -a[2], -a[3]])/np.dot(a, a)
    nv = np.array([1, 1, 1])/math.sqrt(3)
    qerr = 0; nrderr = 0
    for (sig, t) in [(2.0, 3.7), (1.5, 11.3)]:
        Q = np.array([1., 0, 0, 0]); zc = 1+0j; Qfull = np.array([1., 0, 0, 0]); nprod = 1.0
        for q, cl in cls.items():
            if q > 3000: break
            a, w = cl; psi = 0.5*a + 1j*(a*w).imag
            r = q**(-sig); ph = t*math.log(q)
            xq = np.array([r*math.cos(ph), *(-r*math.sin(ph)*nv)])     # p^{-s} in the slice C_n
            if a == 0: g = np.array([0, 1., 0, 0])                     # u = i, u·n = 1/sqrt3
            else: g = np.array([psi.real, *(psi.imag*nv)])
            fac = qinv(np.array([1., 0, 0, 0]) - qm(g, xq))
            Qfull = qm(Qfull, fac); nprod *= 1/np.dot(np.array([1., 0, 0, 0]) - qm(g, xq), np.array([1., 0, 0, 0]) - qm(g, xq))
            if a != 0:
                Q = qm(Q, fac); zc *= 1/(1 - psi*r*cmath.exp(-1j*ph))
        perp = np.linalg.norm(Q[1:] - np.dot(Q[1:], nv)*nv)
        qerr = max(qerr, perp, abs(Q[0] - zc.real), abs(np.dot(Q[1:], nv) - zc.imag))
        nrderr = max(nrderr, abs(np.dot(Qfull, Qfull)/nprod - 1))
    res['quaternion_slice_check'] = dict(max_err_slice_vs_complex=float(qerr), nrd_multiplicative_rel_err=float(nrderr))
    # ---- central point: F6 ~ C (s-1/2)^{3/8} ----
    pari("IcLr=lfuninit(Lr,[0.5,0.6,3]); IcL3=lfuninit(L3,[1.0,0.2,3]); IcLo=lfuninit(Lo,[1.0,0.2,3]); IcLob=lfuninit(Lob,[1.0,0.2,3]); IcLw=lfuninit(Lw,[0.5,0.6,3]); IcLwb=lfuninit(Lwb,[0.5,0.6,3]);")
    def logH_at(sv, XX=200000):
        tot = 0j
        for q, cl in cls.items():
            if q > XX: break
            E = eig(cl); a, w = cl; psi = 0.5*a + 1j*(a*w).imag
            x = q**(-sv); x2 = q**(-2*sv)
            f6 = 0 if a == 0 else -cmath.log(1 - psi*x)
            tot += f6 - 0.5*complex(llog(E['rho'], x)) - 0.5*complex(llog(E['rw'], x)) + 0.5*complex(llog(E['rwb'], x)) \
                   - 0.125*complex(llog(E['zeta'], x2) + llog(E['om'], x2) + llog(E['omb'], x2) - llog(E['psi3'], x2))
        return tot
    def logabsF6(sv):
        def L(I, z): return gp(f"lfun({I},{z.real}+{z.imag}*I)")
        val = 0.5*math.log(abs(L('IcLr', sv))) + 0.5*math.log(abs(L('IcLw', sv))) - 0.5*math.log(abs(L('IcLwb', sv)))
        z2 = 2*sv
        l4 = math.log(abs(gp(f"zeta({z2.real}+{z2.imag}*I)"))) + math.log(abs(L('IcLo', z2))) + math.log(abs(L('IcLob', z2))) - math.log(abs(L('IcL3', z2)))
        l4 -= (loc163('zeta', z2) + loc163('ω', z2) + loc163('ω̄', z2) - loc163('psi3', z2)).real
        return val + 0.125*l4 + logH_at(sv).real
    eps = [1e-1, 1e-2, 1e-3, 1e-4, 1e-5]
    lv = [logabsF6(complex(0.5+e, 0)) for e in eps]
    slopes = [(lv[i+1]-lv[i])/(math.log(eps[i+1])-math.log(eps[i])) for i in range(len(eps)-1)]
    res['central'] = dict(eps=eps, log_abs_F6=lv, slopes=slopes, predicted=3/8)
    print(lab, 'central slopes', slopes, flush=True)
    # monodromy of F6 around s=1/2 (circle radius 1e-3): predicted Δarg = 2π·3/8
    th = np.linspace(0, 2*math.pi, 241); rad = 1e-3
    pts = 0.5 + rad*np.exp(1j*th)
    def argtrack(I, zs): v = np.array([gp(f"lfun({I},{z.real}+{z.imag}*I)") for z in zs]); return np.unwrap(np.angle(v))
    dr = argtrack('IcLr', pts); dw = argtrack('IcLw', pts); dwb = argtrack('IcLwb', pts)
    dz = np.unwrap(np.angle(np.array([gp(f"zeta({z.real}+{z.imag}*I)") for z in 2*pts])))
    do = argtrack('IcLo', 2*pts); dob = argtrack('IcLob', 2*pts); d3 = argtrack('IcL3', 2*pts)
    dF = 0.5*(dr[-1]-dr[0]) + 0.5*(dw[-1]-dw[0]) - 0.5*(dwb[-1]-dwb[0]) + 0.125*((dz[-1]-dz[0]) + (do[-1]-do[0]) + (dob[-1]-dob[0]) - (d3[-1]-d3[0]))
    res['monodromy_half'] = dict(delta_arg_F6=float(dF), predicted=2*math.pi*3/8)
    print(lab, 'monodromy around 1/2:', dF, 'pred', 2*math.pi*3/8, flush=True)
    # ---- barrier of the Model A norm factor O4 as sigma -> 1/2 (closed form + K by direct product) ----
    def logO4_closed(sig, t, XX=200000):
        sv = complex(sig, t)
        # Im log Λ4(s) by continuous tracking along sigma from 2 down to sig at fixed t
        path = [complex(x, t) for x in np.linspace(2.0, sig, 400)]
        def arg_track(fn): v = np.array([fn(z) for z in path]); return np.unwrap(np.angle(v))[-1]
        pari(f"Ib3=lfuninit(L3,[1.2,0.8,{abs(t)+3}]); Ibo=lfuninit(Lo,[1.2,0.8,{abs(t)+3}]); Ibob=lfuninit(Lob,[1.2,0.8,{abs(t)+3}]);")
        A = 0.0 if t == 0 else arg_track(lambda z: gp(f"zeta({z.real}+{z.imag}*I)")) + arg_track(lambda z: gp(f"lfun(Ibo,{z.real}+{z.imag}*I)")) \
            + arg_track(lambda z: gp(f"lfun(Ibob,{z.real}+{z.imag}*I)")) - arg_track(lambda z: gp(f"lfun(Ib3,{z.real}+{z.imag}*I)"))
        A -= (loc163('zeta', sv) + loc163('ω', sv) + loc163('ω̄', sv) - loc163('psi3', sv)).imag
        if t == 0: A = 0.0   # on the real axis the linear (sin) term is identically 0; avoids the pole of zeta at 1
        z2 = 2*sv
        pari(f"Ic3=lfuninit(L3,[1.0,0.2,{2*abs(t)+3}]); Ico=lfuninit(Lo,[1.0,0.2,{2*abs(t)+3}]); Icob=lfuninit(Lob,[1.0,0.2,{2*abs(t)+3}]);")
        def l4abs(z):
            v = math.log(abs(gp(f"zeta({z.real}+{z.imag}*I)"))) + math.log(abs(gp(f"lfun(Ico,{z.real}+{z.imag}*I)"))) \
                + math.log(abs(gp(f"lfun(Icob,{z.real}+{z.imag}*I)"))) - math.log(abs(gp(f"lfun(Ic3,{z.real}+{z.imag}*I)")))
            return v - (loc163('zeta', z) + loc163('ω', z) + loc163('ω̄', z) - loc163('psi3', z)).real
        lK = 0.0
        for q, cl in cls.items():
            if q > XX: break
            E = eig(cl); a, w = cl; r = q**(-sig); ph = t*math.log(q); z = r*cmath.exp(-1j*ph)
            L4 = lambda y: complex(llog(E['zeta'], y) + llog(E['om'], y) + llog(E['omb'], y) - llog(E['psi3'], y))
            o4 = -math.log(1 - 2*c*r*math.sin(ph) + r*r) if a == 0 else 0.0
            lK += o4 - (-(c/2)*L4(z).imag - (c*c/4)*L4(z*z).real - ((1 - c*c)/4)*L4(r*r).real)
        return -(c/2)*A - (c*c/4)*l4abs(z2) - ((1 - c*c)/4)*l4abs(complex(2*sig, 0)), lK
    bar = {}
    for t in (0.0, 7.0, 23.5):
        vals = []
        for e in (1e-1, 1e-2, 1e-3, 1e-4):
            main, lK = logO4_closed(0.5+e, t, XX=100000)
            vals.append((e, main+lK))
        sl = [(vals[i+1][1]-vals[i][1])/(math.log(2*vals[i+1][0])-math.log(2*vals[i][0])) for i in range(len(vals)-1)]
        bar[str(t)] = dict(values=vals, slopes_vs_log_2sigma_minus_1=sl, predicted=(0.25 if t == 0 else 1/6))
        print(lab, 'barrier t=', t, sl, flush=True)
    res['barrier_O4'] = bar
    # direct-vs-closed O4 at sigma=1 (slow convergence, informational)
    OUT[lab] = res
    json.dump(OUT, open('results-c.json', 'w'), indent=1, default=str)
# barrier exponent beta(I) = sum_C delta_C sin^2θ_C min_{g in C} sin^2 α(g,I) over unit vectors I
def beta(I):
    I = I/np.linalg.norm(I)
    coord = np.max(np.abs(I))**2                                    # best order-4 axis
    diag = np.max(np.abs(np.array([[1,1,1],[1,1,-1],[1,-1,1],[-1,1,1]])@I)/math.sqrt(3))**2
    return 0.25*1*(1 - coord) + (16/24)*(3/4)*(1 - diag)
rng = np.random.default_rng(1)
V = rng.normal(size=(200000, 3)); b = np.array([beta(v) for v in V])
OUT['beta_axis_scan'] = dict(min=float(b.min()), argmin=(V[b.argmin()]/np.linalg.norm(V[b.argmin()])).tolist(), max=float(b.max()),
    at_n=beta(np.array([1.,1,1])), at_i=beta(np.array([1.,0,0])), q8_check='Q8 aligned: 2 classes of density 1/4, θ=α=π/2 -> β=1/2')
print('beta scan', OUT['beta_axis_scan'])
json.dump(OUT, open('results-c.json', 'w'), indent=1, default=str)
