"""Resumable stdout checkpoint producer for T770; no website writes.

Each completed OBJECT line is independently durable in the calling log.
All numerical routes run on the builder. Pass a prior checkpoint.json beside
this script to resume completed objects without recomputation. Completion
checks still require the exact current source dependency hashes to match.
"""
from generate import Pairings,catalogue,curve,eligible,raw_matrix,target,retained,PARAMETERS,PRIMES
from checks import projected,agrees,control
from sage.libs.pari import pari
from sage.rings.integer_ring import ZZ
from sage.arith.functions import lcm
from sage.env import SAGE_VERSION
from pathlib import Path
import time,json,hashlib,itertools,platform

def enc(a):
    return {'valuation':int(a.valuation()),'unit':str(a.unit_part().lift()),'precision':int(a.precision_absolute())}

def emit(kind,data):
    print(kind+' '+json.dumps(data,separators=(',',':')),flush=True)

base=Path(__file__).parent
hashes={n:hashlib.sha256((base/n).read_bytes()).hexdigest() for n in ['generate.py','checks.py','points.txt']}
emit('VERSIONS',{'sage':SAGE_VERSION,'pari':str(pari.version()),'python':platform.python_version(),'hashes':hashes})
prior={}
if (base/'checkpoint.json').exists():
    ck=json.loads((base/'checkpoint.json').read_text());assert ck['hashes']==hashes
    prior={o['key']:o for o in ck['objects']}
rows=catalogue(); rows.sort(key=lambda r:(r['label'] not in ['37a1','389a1','5077a1'],r['N'],r['label']))
objects=entries=anomalous=0
controls={};counts={p:0 for p in PRIMES}
for row in rows:
    E,pts=curve(row);r=len(pts)
    assert int(E.conductor())==row['N']
    assert E.is_global_minimal_model()
    tors=[E(ZZ(X)/ZZ(Z),ZZ(Y)/ZZ(Z)) for X,Y,Z in row['torsion']]
    assert all(T.is_finite_order() for T in tors)
    pe=pari(list(E.a_invariants())).ellinit()
    ts=time.monotonic()
    try:
        rb=pe.ellrank(0,[[P[0],P[1]] for P in pts]);bounds=[int(rb[0]),int(rb[1])]
    except Exception as exc:bounds={'unavailable':type(exc).__name__+': '+str(exc)}
    emit('ARITHMETIC',{'label':row['label'],'source_rank':r,'pari_descent_bounds':bounds,
         'seconds':time.monotonic()-ts,'source_claim':'full Mordell-Weil generators',
         'independent_saturation_primes':[],'independent_saturation_bound':None,
         'lattice_status':'explicit subgroup; no new full-lattice certificate claimed'})
    for p in PRIMES:
        if not eligible(E,p):continue
        key=','.join(map(str,(row['N'],E.c4(),E.c6(),p)))
        if key in prior:
            rec=prior[key];controls.update(rec['controls']);emit('OBJECT',rec)
        else:
            begin=time.monotonic();k=target(p);nlo=k+24;nhi=k+44
            raw,h=raw_matrix(E,pts,p,nlo)
            hi,hh=raw_matrix(E,pts,p,nhi)
            lo2=projected(E,pts,p,nlo);hi2=projected(E,pts,p,nhi)
            known=control(row['label'],E,pts,p,raw,h);controls.update(known)
            n1=ZZ(p+1)-E.ap(ZZ(p));n2=lcm(E.tamagawa_numbers());m=lcm([n1,n2]);loss=2*ZZ(m).valuation(p)
            values=[]
            for ij,a in raw.items():
                v=retained(a,p);N=int(v.precision_absolute())
                assert agrees(a,hi[ij],min(a.precision_absolute(),nlo)),('repeat-sage',key,ij)
                assert agrees(lo2[ij],hi2[ij],min(lo2[ij].precision_absolute(),nlo)),('repeat-pari',key,ij)
                assert agrees(v,lo2[ij],N) and agrees(v,hi2[ij],N),('independent',key,ij)
                assert not agrees(v,-hi2[ij],N),('sign-control',key,ij)
                assert v.precision_relative()==k
                values.append({'i':ij[0],'j':ij[1],'number':str(v),'retained':enc(v),
                   'sage_low':enc(a),'sage_high':enc(hi[ij]),'pari_low':enc(lo2[ij]),'pari_high':enc(hi2[ij]),
                   'comparison_exponent':N,'difference_valuation':int((v-lo2[ij]).valuation())})
            # Supplemental identities at every curve/prime object.
            P=pts[0];N=min(int(raw[1,1].precision_absolute()),nlo)
            assert (h(-P)-h(P)).valuation()>=N
            assert (h(2*P)-4*raw[1,1]).valuation()>=N
            assert h(E(0)).is_zero()
            for T in tors:
                assert h(T).is_zero()
                assert (h(P+T)-h(P)).valuation()>=N
            if r>=2:
                Q=pts[1];b=raw[1,2]
                assert ((h(Q+P)-h(Q)-h(P))/ZZ(2)-b).valuation()>=N
                assert ((h(-P+Q)-h(P)-h(Q))/ZZ(2)+b).valuation()>=N
                assert ((h(P+2*Q)-h(P)-4*h(Q))/ZZ(2)-2*b).valuation()>=N
            recognition=None
            if row['label'] in ['37a1','389a1','5077a1'] and p==13:
                vals={}; tested=0
                for cs in itertools.product(range(-2,3),repeat=r):
                    R=sum((ZZ(c)*P for c,P in zip(cs,pts)),E(0))
                    pred=sum((ZZ(cs[i])*ZZ(cs[j])*(1 if i==j else 2)*raw[i+1,j+1]
                              for i in range(r) for j in range(i,r)),raw[1,1].parent()(0))
                    actual=h(R)
                    assert (actual-pred).valuation()>=int(min(N,actual.precision_absolute(),pred.precision_absolute()))
                    if not actual.is_zero(): vals.setdefault(str(retained(actual,p,30)),[]).append(list(cs))
                    tested+=1
                recognition={'coefficient_bound':2,'tested':tested,'ambiguities':[v for v in vals.values() if len(v)>1],
                             'interpretation':'known-identity check; height cannot determine point sign'}
            rec={'key':key,'label':row['label'],'p':p,'rank':r,'entries':values,'n_low':nlo,'n_high':nhi,
                 'm':str(m),'division_loss':int(loss),'anomalous':bool(E.ap(ZZ(p))%p==1),
                 'controls':known,'supplementary_identities':True,'recognition':recognition,'seconds':time.monotonic()-begin}
            emit('OBJECT',rec)
        objects+=1;entries+=len(rec['entries']);counts[p]+=1;anomalous+=int(rec['anomalous'])
        if objects%25==0:emit('PROGRESS',{'objects':objects,'entries':entries})
assert (objects,entries,anomalous)==(541,1249,47),(objects,entries,anomalous)
assert counts=={5:134,7:137,11:128,13:142}
emit('COMPLETE',{'objects':objects,'entries':entries,'anomalous':anomalous,'by_prime':counts,'known_controls':controls})
