#!/usr/bin/env python3
"""Exact Q8 field/character checks and non-interval Artin L computations.
Run with the interpreter in a venv containing cypari2==2.2.4.
No LMFDB values or root numbers are supplied to lfunartin.
"""
from pathlib import Path
from datetime import datetime
from zoneinfo import ZoneInfo
import json
from cypari2 import Pari

ROOT = Path(__file__).resolve().parent
p = Pari()
p.allocatemem(256_000_000)
FIELDS = [
    dict(name='minus', label='2.2304.8t5.b.a', field_label='8.0.12230590464.1',
         polynomial='x^8+12*x^6+36*x^4+36*x^2+9', sign=-1, gamma=[1,1]),
    dict(name='plus', label='2.2304.8t5.a.a', field_label='8.8.12230590464.1',
         polynomial='x^8-12*x^6+36*x^4-36*x^2+9', sign=1, gamma=[0,0]),
]
result = dict(checked_at=datetime.now(ZoneInfo('America/Los_Angeles')).isoformat(),
              pari_version=str(p('version()')), cypari2_version='2.2.4',
              arithmetic='exact fields/characters; floating-point, not interval, L-values',
              fields=[], checks=0)
def check(ok):
    assert ok
    result['checks'] += 1

def build(field, digits):
    p.set_real_precision(digits)
    p(f'P={field["polynomial"]}; N=nfinit(P); G=galoisinit(N); TC=galoischartable(G); T=TC[1];')
    degrees=[int(p(f'T[1,{j}]')) for j in range(1,6)]
    col=degrees.index(2)+1
    p(f'chi=T[,{col}]; L=lfunartin(N,G,chi,TC[2]);')
    check(int(p('polisirreducible(P)')) == 1)
    check([int(x) for x in p('galoisidentify(G)')] == [8,4]) # GAP SmallGroup(8,4) = Q8
    check(int(p('N.disc')) == 12230590464)
    check([int(x) for x in p('lfunparams(L)')[2]] == field['gamma'])
    check(int(p('lfunparams(L)')[0]) == 2304)
    check(int(p('L[6]')) == 0) # unknown root number in initial data
    classes=p('galoisconjclasses(G)')
    chi=[int(x) for x in p('chi')]
    char={tuple(int(x) for x in g):chi[j] for j,cl in enumerate(classes) for g in cl}
    numerator=sum(char[tuple(g[g[k]-1] for k in range(8))] for g in char)
    check(numerator == -8)
    indicator=numerator//8
    check(sum(c==2 for c in char.values()) == 1) # character kernel = identity
    return dict(degree=8, discriminant=str(p('N.disc')), signature=[int(x) for x in p('N.sign')],
                galois_smallgroup=[8,4], galois_transitive='8T5', character=chi,
                class_sizes=[len(cl) for cl in classes], frobenius_schur=indicator,
                conductor=2304, gamma_shifts=field['gamma'], initial_root_number=0)

for field in FIELDS:
    rec={**field, 'exact':build(field,100), 'precision_runs':[]}
    # Arithmetic audit: factorization modulo unramified primes determines Frobenius order.
    coeff=[int(x) for x in p('lfunan(L,10000)')]
    rec['coefficients_first_2000']=coeff[:2000]
    audit=[]
    for ell in [5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]:
        factors=p(f'factormod(P,{ell})')
        ds=[int(factors[j,0].poldegree()) for j in range(factors.nrows())]
        check(len(set(ds)) == 1)
        order=ds[0]
        ap={1:2,2:-2,4:0}[order]
        check(coeff[ell-1] == ap)
        check(coeff[ell*ell-1] == ap*ap-1)
        audit.append(dict(prime=ell, factor_degrees=ds, trace=ap,
                          coefficient_p2=coeff[ell*ell-1]))
    check(coeff[1] == coeff[2] == 0) # ramified Euler factors at 2 and 3 are 1
    rec['independent_local_factor_audit']=audit
    for digits in [40,70,100]:
        build(field,digits)
        # Compute the theta ratios BEFORE asking PARI to determine a root number.
        # These sums use the coefficients/gamma kernel, not a supplied FE sign.
        ratios=[]
        tolerance=p(f'10.^(-{digits-8})')
        for ts in ['3/4','5/4','335/339+I/7']:
            # GP evaluation honors the requested global precision. Direct cypari2
            # lfuntheta calls otherwise default to 53 bits unless precision is explicit.
            p(f't={ts}; th=lfuntheta(L,t); du=lfuntheta(L,1/t); rat=du/t/th;')
            theta=p('th')
            ratio=p('rat')
            error=abs(ratio-field['sign'])
            check(error < tolerance)
            ratios.append(dict(t=ts, theta=str(theta), computed_ratio=str(ratio),
                               error_from_expected=str(error)))
        check(int(p('L[6]')) == 0)
        root=p('lfunrootres(L)')[2]
        check(int(root) == field['sign'])
        bits=int(p('lfuncheckfeq(L)'))
        check(bits < -(digits*3-15))
        centre=p('lfun(L,1/2)')
        if field['sign']==-1:
            check(abs(centre) < tolerance)
        else:
            check(p('0.70') < centre < p('0.72'))
        # Negative control: intentionally wrong sign must fail the theta FE check.
        p(f'Lbad=L; Lbad[6]={-field["sign"]};')
        wrong_bits=int(p('lfuncheckfeq(Lbad)'))
        check(wrong_bits >= 0)
        run=dict(decimal_digits=digits, real_bits=int(p('default(realbitprecision)')),
                 computed_root_number=int(root), functional_equation_error_bits=bits,
                 wrong_sign_error_bits=wrong_bits, theta_ratios=ratios,
                 central_value=str(centre), central_absolute_value=str(abs(centre)),
                 central_first_derivative=str(p('lfun(L,1/2,1)')),
                 completed_central_value=str(p('lfunlambda(L,1/2)')))
        rec['precision_runs'].append(run)
        print(field['name'],digits,'digits:', 'W=',root,'L(1/2)=',centre,'FE bits',bits,flush=True)
    # Real-axis samples show that a numerical zero is isolated, not an identically zero object.
    rec['real_axis_near_centre']=[]
    for offset in ['-1/100','-1/1000','0','1/1000','1/100']:
        rec['real_axis_near_centre'].append(dict(offset=offset,L=str(p(f'lfun(L,1/2+({offset}))'))))
    # Actual completed values, not cosh/sinh models, on the critical hyperplane.
    rec['completed_critical_values']=[]
    for ts in ['1/10','7/10']:
        value=p(f'lfunlambda(L,1/2+I*({ts}))')
        forbidden=value.real() if field['sign']==-1 else value.imag()
        check(abs(forbidden) < p('1e-90'))
        rec['completed_critical_values'].append(dict(t=ts, value=str(value),
                                                   forbidden_component=str(forbidden)))
    # Hardy normalization: divide Lambda by |Q| and, for W=-1, by i.
    # This gives a real signed function with |Z|=|L| for both fields.
    p.set_real_precision(50)
    p('LI=lfuninit(L,[1/2,0,1/2]);')
    plot=[]
    for n in range(-100,101):
        p(f's=1/2+I*({n}/200); lam=lfunlambda(LI,s); val=lfun(LI,s);')
        nu=field['gamma'][0]
        p(f'Q=2304^(s/2)*Pi^(-s-{nu})*gamma((s+{nu})/2)^2;')
        z=p('imag(lam)/abs(Q)' if field['sign']==-1 else 'real(lam)/abs(Q)')
        check(abs(abs(z)-p('abs(val)')) < p('1e-40'))
        plot.append(dict(t=n/200, Z=float(z), abs_L=float(p('abs(val)'))))
    for a,b in zip(plot,reversed(plot)):
        check(abs(a['Z']-field['sign']*b['Z']) < 1e-12)
    rec['hardy_plot']=plot
    result['fields'].append(rec)

# Same-conductor fields are not the same L-function: their gamma factors differ.
a,b=result['fields']
check(a['exact']['gamma_shifts'] != b['exact']['gamma_shifts'])
# Finite coefficient cross-check of the expected quadratic-twist relation.
for n,(am,ap) in enumerate(zip(a['coefficients_first_2000'],b['coefficients_first_2000']),1):
    check(am == int(p.kronecker(-4,n))*ap)
result['quadratic_twist_coefficient_check']='a_minus(n)=Kronecker(-4,n)*a_plus(n), checked n=1..2000 (finite check, not by itself proof for all n)'
result['central_zero_caveat']='The exact zero follows from the established functional equation and W=-1. PARI central evaluation uses that equation; it is not independent evidence of the zero. Unknown-sign theta-ratio tests, wrong-sign rejection, local factors, derivatives and nearby values provide independent consistency checks. This file has non-interval L-values. A separate reproducible Arb theta-sign certificate is supplied by q8-certify.py and q8-certificate.json. No interval enclosure of the central derivative is claimed.'
(ROOT/'q8-results.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS',result['checks'],'assertions; wrote q8-results.json',flush=True)
