"""T732 builder checks; independent Hecke coefficients and radial quadrature.

Run with SageMath and numberdb, beside generate.py and heegner.py:
    sage -python builder_check.py > builder-check.jsonl
JSON lines preserve completed quadratures. This is builder evidence, not an
independent-actor verdict. Coefficient provenance and numerical evaluation differ
from production; the comparison shares CM representatives, lattice enclosures,
the modularity theorem, and Arb. All rows receive conjugation/selection checks;
the quadrature sample covers each level's first field, largest class orbit,
closest reduction boundary, and every exceptional-unit discriminant.
"""
import numberdb.sage as numberdb
from sage.rings.complex_arb import ComplexBallField
from sage.rings.real_arb import RealBallField
from sage.rings.rational_field import QQ
from sage.rings.qqbar import _init_qqbar
_init_qqbar()
from sage.modular.modsym.modsym import ModularSymbols
from sage.schemes.elliptic_curves.constructor import EllipticCurve
from numberdb._write import to_text
from generate import HeegnerTrace
from heegner import LEVELS, MODELS, topology
from functools import lru_cache
import json,math,time
from pathlib import Path
from numbertext import decode_number
_cache_path=Path(__file__).with_name("quadrature-checkpoints.json")
_saved={}
if _cache_path.exists():
    for _r in json.loads(_cache_path.read_text()):_saved[tuple(_r[k] for k in ["N","A","B","D"])]=_r
C=ComplexBallField(480);R=RealBallField(480)
def emit(x): print(json.dumps(x,default=str),flush=True)
def finite(z):return z.real().is_finite() and z.imag().is_finite()
def narrow(z,d=103):return finite(z) and R(z.real().rad())<R(10)**(-d) and R(z.imag().rad())<R(10)**(-d)
def agree(a,b):return narrow(a) and narrow(b) and (a-b).contains_zero()
@lru_cache(None)
def hecke(N,M):
    f=ModularSymbols(N,2,sign=1).cuspidal_submodule().q_eigenform(M+1,names='a')
    return [QQ(f[n]) for n in range(M+1)]
@lru_cache(None)
def integrate(N,A,B,D):
    if (N,A,B,D) in _saved:
        rec=_saved[(N,A,B,D)];v=decode_number(rec["value"],repair_ball_rounding=True);assert narrow(v);emit(dict(rec,kind="cached-quadrature",encoding="Display-only original ball text; recovery adds one ulp of both printed center and printed radius."));return v
    tau=C(-QQ(B)/(2*A),R(-D).sqrt()/(2*A));q=(2*C.pi()*C.gen(0)*tau).exp();rho=R(q.abs().upper())
    M=max(1,int(math.ceil((-400*math.log(2)+math.log(float(1-rho))-math.log(2))/math.log(float(rho)))))
    tail=2*rho**(M+1)/(1-rho)
    while not tail<R(2)**-400:M+=1;tail=2*rho**(M+1)/(1-rho)
    a=hecke(N,M);block=16;calls=[0]
    def fun(t,analytic):
        # A finite polynomial is entire, so it satisfies acb_calc's analytic contract.
        calls[0]+=1;z=q*t;p=[z**j for j in range(block)];qb=z**block;v=C(0)
        for k in reversed(range((M+block-1)//block)):
            part=sum((a[n+1]*p[n-k*block] for n in range(k*block,min((k+1)*block,M)) if a[n+1]),C(0));v=v*qb+part
        return q*v
    start=time.time();v=C.integral(fun,0,1,abs_tol=R(2)**-365,rel_tol=R(2)**-365,eval_limit=200000)
    v+=C(R(0,rad=tail.upper()),R(0,rad=tail.upper()));assert narrow(v)
    emit(dict(kind='quadrature',N=N,A=A,B=B,D=D,terms=M,calls=calls[0],seconds=time.time()-start,value=to_text(v,115,form='decimal'),tail=str(tail)))
    return v

def reduce(z,w1,w2):
    v=z.imag()/w2.imag();u=(z.real()-v*w2.real())/w1.real()
    # Rectangular cases may have an exact half boundary in u. The source theorem
    # used by production proves the real coordinate; comparison here tests both
    # closed enclosures if u touches that boundary, without picking by midpoint.
    ku=int((u+R(1)/2).center().floor());kv=int((v+R(1)/2).center().floor())
    opts=[]
    for a in [ku-1,ku,ku+1]:
        for b in [kv-1,kv,kv+1]:
            ur=u-a;vr=v-b
            if ur.upper()>=-QQ(1)/2 and ur.lower()<QQ(1)/2 and vr.upper()>=-QQ(1)/2 and vr.lower()<QQ(1)/2:opts.append(z-a*w1-b*w2)
    return opts

if __name__=='__main__':
    start=time.time();g=HeegnerTrace();allrows=[];lookup={};failures=[];checks=[]
    for p in g.enumerate():
        ev=g.evaluator(p['N'],100);z,e=ev.trace(p['D'],p['beta']);assert narrow(z)
        row=dict(params=p,z=z,e=e);allrows.append(row);lookup[tuple(p.values())]=row
    assert len(allrows)==262
    # Independent primewise integer enumeration is stored in selection-check.json.
    from pathlib import Path
    sc=Path(__file__).with_name('selection-check.json')
    if sc.exists():assert [r['params'] for r in allrows]==json.loads(sc.read_text())['entries']
    # Complex conjugation sends beta to -beta. Full period shifts are accounted for.
    for row in allrows:
        p=row['params'];N,D,b=p.values();other=lookup[(N,D,(-b)%(2*N))];w1,w2=row['e']['periods']
        assert any(agree(row['z'].conjugate(),q) for q in reduce(other['z'],w1,w2)) or any(agree(q,other['z']) for q in reduce(row['z'].conjugate(),w1,w2))
    emit(dict(kind='all-row-checks',entries=262,conjugation=True,selection=True,finite_narrow=True))
    # Independent period implementation on the exact coefficient-source models.
    for N in LEVELS:
        ev=g.evaluator(N,100);w1,w2,*_=ev.periods();m=EllipticCurve(MODELS[N]).period_lattice().basis(prec=500)
        residual=[abs(w1.real().center()-m[0].real()),abs(w2.real().center()-m[1].real()),abs(w2.imag().center()-m[1].imag())]
        assert all(t<R(10)**-120 for t in map(R,residual))
        emit(dict(kind='period-check',N=N,residual=list(map(str,residual)),claim='Numerical agreement with independent invariant-differential periods; not a new period enclosure.'))
    samples=[]
    for N in LEVELS:
        rows=[r for r in allrows if r['params']['N']==N]
        def margin(row):
            u,v=row['e']['u'],row['e']['v'];a,b=row['e']['shifts'];return min(abs(float(u-a)-.5),abs(float(u-a)+.5),abs(float(v-b)-.5),abs(float(v-b)+.5))
        candidates=[rows[0],max(rows,key=lambda r:(len(r['e']['forms']),abs(r['params']['D']))),min(rows,key=margin)]+[r for r in rows if r['params']['D'] in [-3,-4]]
        for row in candidates:
            if row['params'] not in [r['params'] for r in samples]:samples.append(row)
    emit(dict(kind='sample-plan',entries=[r['params'] for r in samples],criteria='Per level: first field, largest class orbit (largest |D| tie), closest half-boundary, all D=-3,-4 orientations.'))
    for row in samples:
        N,D,beta=row['params'].values();forms=row['e']['forms'];q=sum((integrate(N,A,B,D) for A,B,Cc,red in forms),C(0))
        rawok=agree(q,row['e']['raw']);opts=reduce(q,*row['e']['periods']);reducedok=any(agree(t,row['z']) for t in opts)
        if not (rawok and reducedok):failures.append(row['params'])
        checks.append(dict(params=row['params'],raw=to_text(q,110,form='decimal'),stored_representative=to_text(row['z'],110,form='decimal'),raw_agreement=rawok,reduced_agreement=reducedok))
        emit(dict(kind='sample-check',**checks[-1]))
    # Known-answer controls: polynomial quadrature, zero cusp, modular-symbol
    # cusp ratio and an independent critical integral using the Fricke fixed point.
    polynomial=C.integral(lambda z,analytic:z*z,0,1);assert agree(polynomial,C(QQ(1)/3))
    ev=g.evaluator(11,100);w1,w2,delta,kappa,*_=ev.periods();assert kappa==QQ(1)/5
    # tau=i/sqrt(11) is written as (-B+sqrt(D))/(2*A) with A=11, B=0, D=-44;
    # it is a quadrature control, not an additional table entry.
    critical=2*integrate(11,11,0,-44);assert agree(critical,w1/5)
    known=agree(C(0),C(0)) and any(agree(C(0),z) for z in reduce(w1+w2,w1,w2))
    row=next(r for r in samples if len(r['e']['forms'])>1 and any(int(k)%2 for k in r['e']['shifts']) and float(r['z'].abs().center())>.01)
    N,D,b=row['params'].values();q=sum((integrate(N,A,B,D) for A,B,Cc,red in row['e']['forms']),C(0));w1,w2=row['e']['periods'];h=len(row['e']['forms']);A,B,Cc,red=row['e']['forms'][0]
    controls={
      'sign_reversal':not agree(row['z'],-row['z']),
      'average_instead_of_trace':not any(agree(row['z'],z) for z in reduce(q/h,w1,w2)),
      'omitted_class':not any(agree(row['z'],z) for z in reduce(q-integrate(N,A,B,D),w1,w2)),
      'unreduced_full_period':not agree(row['z'],row['z']+w1),
      'wrong_sublattice':not any(agree(row['z'],z) for z in reduce(q,2*w1,2*w2)),
      'dropped_cusp_translation':not any(agree(row['z'],z) for z in reduce(q-h*ev.periods()[3]*w1,w1,w2)),
      'nan':not agree(row['z'],C('nan')),
      'vacuous':not agree(row['z'],C(R(0,rad=R(100).upper()),R(0,rad=R(100).upper())))}
    # The cusp-translation test uses the current level's exact cusp coordinate.
    controls['dropped_cusp_translation']=not any(agree(row['z'],z) for z in reduce(q-h*g.evaluator(N,100).periods()[3]*w1,w1,w2))
    emit(dict(kind='controls',known_answer_control=known,negative_controls=controls,critical_integral=to_text(critical,110,form='decimal')))
    assert known and all(controls.values())
    emit(dict(kind='summary',checked_entries=len(checks),total_entries=262,all_row_conjugation_checks=262,failures=failures,known_answer_control=known,negative_control_rejected=all(controls.values()),checks=checks,seconds=time.time()-start,limitations='Quadrature is sampled, lattice enclosures and CM representatives are shared; coefficient provenance and evaluation differ. No independent-actor verdict.'))
    assert not failures
