#!/usr/bin/env python3
"""F10 direct check (15 Nov 2026).  Assembles the 10-fold aligned product F10(s) of the 2I fields 2.3806401.120.a (p0=1951)
and 2.4583881.120.a (p0=2141) from
  (i)  the exact identity of icosa-exp1113 (weights a_chi at s, b_chi at 2s, read from derive-identity-results.json),
  (ii) global L-values: PARI 160-bit (rho, rho', 3, 3'; pari-<label>-b160.json), double theta sums (4', 4, 5;
       theta-<rep>-<label>.json), mpmath zeta, and an Euler product for L(6 = Sym^5 rho, 2s) (phase only),
  (iii) H(s) = prod_p F10_p / prod_chi L_p(chi)^{w}: computed prime by prime from the Frobenius data (oriented classes for
       p < 1.2e5, orders + orientation average for 1.2e5 < p <= 3.5e7, Chebotarev-mean tail beyond).
Checks the identity against the DIRECT Euler product of F10 at Re s = 1.2, 1.5, 2, then evaluates F10(1/2+eps),
fits log|F10| and arg F10 against log eps, and computes c two ways (fit/extrapolation and closed-form limit).
Branch: F10 has a branch point at s = 1 (factor zeta(s)^{i(s1+s2)/5}); on (1/2, 1) we report the continuation through the
upper half plane ("+", log zeta = log|zeta| - i pi), the lower one ("-") and the symmetric value ("0", log|zeta|).
FLOAT numerics.  Conditional on Artin holomorphy of every L-function used.  usage: f10_assemble.py LABEL"""
import json, math, sys, time
from pathlib import Path
import numpy as np
import mpmath as mp
mp.mp.dps = 40
HERE = Path(__file__).resolve().parent; HC = HERE.parent
label = sys.argv[1]; t0 = time.time()
SWAP = len(sys.argv) > 2 and sys.argv[2] == 'swap'   # orientation swapped: rho <-> rho' (Galois conjugate traces)
p0 = 1951 if label.startswith('2.3806401') else 2141
DI = json.loads((HC/'icosa-exp1113'/'derive-identity-results.json').read_text())
A = {k: complex(*v) for k, v in DI['a_num'].items()}; B = {k: complex(*v) for k, v in DI['b_num'].items()}
s1, s2 = math.sin(math.pi/5), math.sin(2*math.pi/5); gam = (s1+s2)/10; wz = (s1+s2)/5
assert abs(A['1'].imag-wz) < 1e-15 and abs(B['1']-(1/8-1j*gam)) < 1e-15
CH = ['1', 'rho', "rho'", '3', "3'", '4', '5', "4'", '6']
def angles(chi, t, tp):
    return {'1': [0*t], 'rho': [t, -t], "rho'": [tp, -tp], '3': [2*t, 0*t, -2*t], "3'": [2*tp, 0*t, -2*tp],
            '4': [t+tp, t-tp, -t+tp, -t-tp], '5': [4*t, 2*t, 0*t, -2*t, -4*t], "4'": [3*t, t, -t, -3*t],
            '6': [5*t, 3*t, t, -t, -3*t, -5*t]}[chi]
PI = math.pi
# class -> (theta, theta') ; theta from a_p(rho) = 2cos(theta), theta' = Galois conjugate angle
CLS = {'C1': (0, 0), 'Cm1': (PI, PI), 'C4': (PI/2, PI/2), 'C3': (2*PI/3, 2*PI/3), 'C6': (PI/3, PI/3),
       'C10a': (PI/5, 3*PI/5), 'C5a': (2*PI/5, 4*PI/5), 'C10b': (3*PI/5, PI/5), 'C5b': (4*PI/5, 2*PI/5)}
SLICE = {'C1', 'Cm1', 'C10a', 'C5a', 'C10b', 'C5b'}
SIZES = DI['sizes']
# character-table consistency (rho, rho' traces)
for c, (t, tp) in CLS.items():
    i = DI['classes'].index(c)
    for chi in CH:
        tr = sum(np.exp(1j*np.array(angles(chi, t, tp)))).real
        ref = complex(eval(DI['character_table'][chi][i], {'sqrt': math.sqrt})) if chi in DI['character_table'] else None
        if ref is not None: assert abs(tr-ref.real) < 1e-9, (c, chi, tr, ref)
def logL_loc(chi, t, tp, x):   # x = p^{-s} (array), t, tp arrays of same shape
    return -sum(np.log(1-np.exp(1j*ang)*x) for ang in angles(chi, t, tp))
def logF_loc(t, inslice, x): return np.where(inslice, -np.log(1-np.exp(1j*t)*x), 0)
def logH_loc(t, tp, inslice, x, x2):
    r = logF_loc(t, inslice, x)
    for chi in CH: r = r - A[chi]*logL_loc(chi, t, tp, x) - B[chi]*logL_loc(chi, t, tp, x2)
    return r
# identity sanity: log H_p = O(x^3) on every class
idchk = {}
for c, (t, tp) in CLS.items():
    v = [abs(logH_loc(np.array(t), np.array(tp), c in SLICE, xx, xx*xx))/xx**3 for xx in (1e-2, 1e-3)]
    idchk[c] = [float(u) for u in v]
assert max(max(v) for v in idchk.values()) < 5, idchk
# Chebotarev means of log H (for the tail) at small x: m(x) ~ m3 x^3 + m4 x^4
def mean_logH(x):
    return sum(SIZES[c]/120*logH_loc(np.array(CLS[c][0]), np.array(CLS[c][1]), c in SLICE, x, x*x) for c in CLS)
m3 = complex(mean_logH(1e-4)/1e-12); m4 = complex((mean_logH(1e-3)-m3*1e-9)/1e-12)
mu = {k: sum(SIZES[c]/120*np.exp(1j*k*CLS[c][0]) for c in SLICE) for k in (1, 2, 3)}   # Chebotarev means of the F10 log-coefficients
# ---- Frobenius data
d = json.loads((HC/'cert1113'/f'ap-oriented-{label}.json').read_text())
PHI = (1+5**0.5)/2
TR2C = [(2, 'C1'), (-2, 'Cm1'), (0, 'C4'), (-1, 'C3'), (1, 'C6'), (PHI, 'C10a'), (PHI-1, 'C5a'), (1-PHI, 'C10b'), (-PHI, 'C5b')]
po, co = [], []
for k, v in d['ap'].items():
    if v is None: continue
    if SWAP:
        v = {round(PHI, 9): 1-PHI, round(PHI-1, 9): -PHI, round(1-PHI, 9): PHI, round(-PHI, 9): PHI-1}.get(round(v, 9), v)
    po.append(int(k)); co.append([c for tr, c in TR2C if abs(v-tr) < 1e-9][0])
po = np.array(po, dtype=float); Xo = 120000
assert po.max() < Xo and p0 not in po
to = np.array([CLS[c][0] for c in co]); tpo = np.array([CLS[c][1] for c in co]); so = np.array([c in SLICE for c in co])
Z = np.load(HC/'sym3-1114'/f'ord-{label}-M35000000.npz'); PL = Z['PL']; OR = Z['OR']; XM = 35000000
mk = (PL > Xo) & (OR != 0); pu = PL[mk].astype(float); ou = OR[mk]
# audit: orders of oriented classes agree with the order table for p < 1.2e5
ORD = {'C1': 1, 'Cm1': -1, 'C4': 4, 'C3': 3, 'C6': 6, 'C10a': 10, 'C10b': 10, 'C5a': 5, 'C5b': 5}
om = dict(zip(PL.tolist(), OR.tolist())); mism = sum(1 for p, c in zip(po.tolist(), co) if om[int(p)] != ORD[c])
# unoriented: two orientation options for orders 5, 10 (averaged)
U1 = {1: (0, 0), -1: (PI, PI), 4: (PI/2, PI/2), 3: (2*PI/3, 2*PI/3), 6: (PI/3, PI/3), 5: (2*PI/5, 4*PI/5), 10: (PI/5, 3*PI/5)}
U2 = dict(U1); U2[5] = (4*PI/5, 2*PI/5); U2[10] = (3*PI/5, PI/5)
tu1 = np.array([U1[o][0] for o in ou]); tpu1 = np.array([U1[o][1] for o in ou])
tu2 = np.array([U2[o][0] for o in ou]); tpu2 = np.array([U2[o][1] for o in ou]); su = np.isin(ou, [1, -1, 5, 10])
def E1tail(alpha, X):   # sum_{p>X} p^{-alpha} ~ int_X^inf t^{-alpha}/log t dt = E1((alpha-1) log X)
    return complex(mp.e1((alpha-1)*mp.log(X)))
loc0 = {'1': 1, '3': 1, "3'": 1, '5': 1, '6': (0 if p0 == 1951 else 2)}   # number of eigenvalues 1 at p0 (others: factor 1)
def logH(s):
    x = po**(-s); r = complex(np.sum(logH_loc(to, tpo, so, x, x*x)))
    x = pu**(-s); h1 = logH_loc(tu1, tpu1, su, x, x*x); h2 = logH_loc(tu2, tpu2, su, x, x*x)
    r += complex(np.sum((h1+h2)/2)); spread = float(np.sqrt(np.sum(np.abs((h1-h2)/2)**2)))
    x0 = p0**(-s)
    for chi, m in loc0.items(): r -= (A[chi]*(-m*np.log(1-x0)) + B[chi]*(-m*np.log(1-x0*x0)))
    tail = m3*E1tail(3*s, XM) + m4*E1tail(4*s, XM)
    return r + tail, spread, abs(tail)
def logF_direct(s):
    x = po**(-s); r = complex(np.sum(logF_loc(to, so, x)))
    x = pu**(-s); f1 = logF_loc(tu1, su, x); f2 = logF_loc(tu2, su, x)
    r += complex(np.sum((f1+f2)/2)); spread = float(np.sqrt(np.sum(np.abs((f1-f2)/2)**2)))
    tail = sum(mu[k]/k*E1tail(k*s, XM) for k in (1, 2, 3))
    return r + tail, spread, abs(tail)
PLf = PL.astype(float)
def logL6(sv, X=XM):   # Euler product of L(6 = Sym^5 rho, sv), orientation-free (chi_6 rational), incl. p0 factor
    m = (PL <= X) & (OR != 0); x = PLf[m]**(-sv); t = np.array([U1[o][0] for o in OR[m]])
    r = float(np.sum(logL_loc('6', t, t, x).real)) - loc0['6']*math.log(1-p0**(-sv))
    return r
# ---- global values
P = json.loads((HERE/f'pari-{label}-b160.json').read_text())
if SWAP:
    P['rho'], P['rhop'] = P['rhop'], P['rho']; P['three'], P['threep'] = P['threep'], P['three']
T = {r: json.loads((HERE/f'theta-{r}-{label}.json').read_text()) for r in ('4p', '4', '5')}
key = {'rho': ('P', 'rho'), "rho'": ('P', 'rhop'), '3': ('P', 'three'), "3'": ('P', 'threep'), '4': ('T', '4'), '5': ('T', '5'), "4'": ('T', '4p')}
EPS = P['eps']; assert np.allclose(EPS, T['4']['eps'])
def Lval(chi, kind, i=None, c=None):
    src, k = key[chi]
    if src == 'P':
        R = P[k]; v = R['L_s'][i] if kind == 's' else R['L_2s'][i] if kind == '2s' else R['L_check'][c]
        return mp.mpf(v.replace(' E', 'E'))
    R = T[k]; return mp.mpf(R['L_s'][i] if kind == 's' else R['L_2s'][i] if kind == '2s' else R['L_check'][str(float(eval(c)))])
out = dict(label=label, swap=SWAP, p0=p0, identity_check_logH_over_x3=idchk, m3=[m3.real, m3.imag], m4=[m4.real, m4.imag],
           oriented_vs_order_mismatches=mism, n_oriented=len(po), n_unoriented=int(len(pu)))
# (A) Re s > 1: identity (global L-values) vs direct Euler product of F10
chk = []
for sc, s2c in (('6/5', '12/5'), ('3/2', '3'), ('2', '4')):
    s = float(mp.mpf(eval(sc))); lF, spF, tailF = logF_direct(s); lH, spH, tH = logH(s)
    rhs = A['1']*complex(mp.log(mp.zeta(s))) + B['1']*complex(mp.log(mp.zeta(2*s))) + lH + B['6']*logL6(2*s)
    for chi in ('rho', "rho'", '3', "3'", '4', '5', "4'"):
        rhs += A[chi]*float(mp.log(Lval(chi, 'c', c=sc))) + B[chi]*float(mp.log(Lval(chi, 'c', c=s2c)))
    chk.append(dict(s=s, logF_euler=[lF.real, lF.imag], logF_identity=[rhs.real, rhs.imag], diff=abs(lF-rhs),
                    orientation_spread_F=spF, orientation_spread_H=spH, tail_F=tailF, tail_H=tH))
    print('check s=%.2f |logF_euler - logF_identity| = %.2e  (F: %.12f%+.12fi)  spreadF %.1e tailF %.1e' % (s, abs(lF-rhs), lF.real, lF.imag, spF, tailF), flush=True)
out['ReS_gt_1_check'] = chk
# (B) near 1/2
L6 = {X: logL6(1.0, X) for X in (10**6, 10**7, XM)}
out['logL6_at_1_partial'] = {str(k): v for k, v in L6.items()}
rows = []
for i, e in enumerate(EPS):
    s = 0.5+e; lH, spH, tH = logH(s)
    z = mp.zeta(s); assert z < 0
    lz0 = complex(mp.log(-z))                                # log|zeta(s)|
    base = A['1']*lz0 + B['1']*complex(mp.log(mp.zeta(2*s))) + lH + B['6']*logL6(2*s)
    pos = {}
    for chi in ('rho', "rho'", '3', "3'", '4', '5', "4'"):
        vs, v2 = Lval(chi, 's', i=i), Lval(chi, '2s', i=i); pos[chi] = (float(vs), float(v2))
        assert vs > 0 and v2 > 0, (chi, vs, v2)
        base += A[chi]*float(mp.log(vs)) + B[chi]*float(mp.log(v2))
    rows.append(dict(eps=e, logF0=[base.real, base.imag], logH=[lH.real, lH.imag], H_orient_spread=spH, H_tail=tH, values=pos))
out['rows'] = rows
le = np.log(np.array(EPS)); re_ = np.array([r['logF0'][0] for r in rows]); im_ = np.array([r['logF0'][1] for r in rows])
out['local_slopes_modulus'] = list(np.diff(re_)/np.diff(le)); out['local_slopes_phase'] = list(np.diff(im_)/np.diff(le))
# least squares on the 6 smallest eps with model  y = e*log(eps) + C + d*eps
def fit(y, n=6):
    M_ = np.vstack([le[-n:], np.ones(n), np.array(EPS[-n:])]).T
    co_, res, *_ = np.linalg.lstsq(M_, y[-n:], rcond=None); return [float(v) for v in co_], float(np.max(np.abs(M_@co_-y[-n:])))
out['fit_modulus'], out['fit_modulus_maxres'] = fit(re_); out['fit_phase'], out['fit_phase_maxres'] = fit(im_)
out['predicted'] = dict(modulus_slope=1/24, phase_slope=gam)
# c(eps) = F10 * eps^{-(1/24 + i gam)}  (symmetric branch), Richardson on the two smallest eps
ce = [complex(math.exp(r_), 0)*np.exp(1j*i_)*np.exp(-(1/24)*l_ - 1j*gam*l_) for r_, i_, l_ in zip(re_, im_, le)]
ra = EPS[-2]/EPS[-1]; cR = (ra*ce[-1]-ce[-2])/(ra-1)
out['c_eps'] = [[abs(c), float(np.angle(c))] for c in ce]
# (C) closed-form limit: c = L'(rho)^{1/3} L'(rho')^{-1/6} L(4',1/2)^{1/6} 2^{-1/8+i gam} |zeta(1/2)|^{i wz} * prod A5(1/2)^{ia}
#      * prod L(chi,1)^{b} * L(6,1)^{b6} * H(1/2)    [the eps^{...} factors are removed analytically]
lc = (1/3)*float(mp.log(mp.mpf(P['rho']['Lp_half']))) - (1/6)*float(mp.log(mp.mpf(P['rhop']['Lp_half']))) + (1/6)*math.log(T['4p']['L_half'])
lc += (-1/8+1j*gam)*math.log(2) + A['1']*float(mp.log(-mp.zeta(0.5)))
lc += A['3']*float(mp.log(mp.mpf(P['three']['L_half']))) + A["3'"]*float(mp.log(mp.mpf(P['threep']['L_half']))) + A['4']*math.log(T['4']['L_half'])
lc += B['3']*float(mp.log(mp.mpf(P['three']['L_one']))) + B["3'"]*float(mp.log(mp.mpf(P['threep']['L_one']))) + B['5']*math.log(T['5']['L_one'])
lc += B['4']*math.log(T['4']['L_one']) + B['rho']*float(mp.log(mp.mpf(P['rho']['L_one']))) + B["rho'"]*float(mp.log(mp.mpf(P['rhop']['L_one']))) + B["4'"]*math.log(T['4p']['L_one'])
lc += B['6']*L6[XM]
lH12, spH12, tH12 = logH(0.5); lc += lH12
# zeta(2s) = 1/(2eps) + gamma_E + ...: the constant 2^{-1/8+i gam} accounts for the 1/(2eps); limit taken analytically
cC = complex(np.exp(lc))
br = math.pi*wz
out['c'] = {'symmetric(0)': dict(abs=abs(cC), arg=float(np.angle(cC))),
            'upper(+)': dict(abs=abs(cC)*math.exp(br), arg=float(np.angle(cC))),
            'lower(-)': dict(abs=abs(cC)*math.exp(-br), arg=float(np.angle(cC))),
            'from_fit_richardson(0)': dict(abs=abs(cR), arg=float(np.angle(cR))),
            'rel_diff_closed_vs_fit': abs(cC-cR)/abs(cC)}
# phase budget of c (radians, symmetric branch)
pb = {'zeta(2s): 2^{i gam}': gam*math.log(2), 'zeta(s): wz log|zeta(1/2)|': wz*float(mp.log(-mp.zeta(0.5))),
      'A5 at s: L(3),L(3\'),L(4) at 1/2 (= phi_A5 of 15 Nov)': (A['3']*float(mp.log(mp.mpf(P['three']['L_half']))) + A["3'"]*float(mp.log(mp.mpf(P['threep']['L_half']))) + A['4']*math.log(T['4']['L_half'])).imag,
      '2s pieces L(4,1),L(rho,1),L(rho\',1),L(4\',1),L(6,1)': (B['4']*math.log(T['4']['L_one']) + B['rho']*float(mp.log(mp.mpf(P['rho']['L_one']))) + B["rho'"]*float(mp.log(mp.mpf(P['rhop']['L_one']))) + B["4'"]*math.log(T['4p']['L_one']) + B['6']*L6[XM]).imag,
      '2s pieces with real+imag weight L(3,1),L(3\',1)': (B['3']*float(mp.log(mp.mpf(P['three']['L_one']))) + B["3'"]*float(mp.log(mp.mpf(P['threep']['L_one'])))).imag,
      'L(6,1) alone (Euler product, X=3.5e7)': (B['6']*L6[XM]).imag,
      'arg H(1/2)': lH12.imag}
pb['total'] = sum(v for k, v in pb.items() if 'alone' not in k)
out['phase_budget_c'] = pb
out['L6_phase_uncertainty_from_truncation'] = abs(B['6'].imag)*max(abs(L6[XM]-L6[10**7]), abs(L6[XM]-L6[10**6]))
out['H_half'] = dict(logH=[lH12.real, lH12.imag], orient_spread=spH12, tail=tH12)
out['secs'] = round(time.time()-t0)
print(json.dumps({k: v for k, v in out.items() if k not in ('rows',)}, indent=1, default=str))
json.dump(out, open(HERE/(f'assemble-{label}' + ('-swap' if SWAP else '') + '.json'), 'w'), indent=1, default=str)
