"""Independently rebuild the frozen roster and labels from primary ecdata text.

Download the two frozen source URLs in source-manifest.json to the filenames
listed there, then run python3 input_check.py with points.json alongside.
No sibling table data or values are inputs to this reconstruction.
"""
import ast,json,hashlib
from fractions import Fraction
from pathlib import Path
W=Path(__file__).resolve().parent

def check():
    manifest=json.loads((W/'source-manifest.json').read_text())
    for name in ['ecdata-allgens.txt','ecdata-alllabels.txt']:
        assert hashlib.sha256((W/name).read_bytes()).hexdigest()==manifest[name]['sha256']
    labels={}
    for line in (W/'ecdata-alllabels.txt').read_text().splitlines():
        a=line.split();labels[a[0]+a[1]+a[2]]=a[3]+'.'+a[4]+a[5]
    records=[];exact_equations=0
    for n,line in enumerate((W/'ecdata-allgens.txt').read_text().splitlines(),1):
        a=line.split();N,rank,k=int(a[0]),int(a[4]),int(a[2])
        if k!=1 or not ((rank==1 and N<=175) or (rank==2 and N<=2000) or (rank>=3 and N<=10000)):continue
        ainvs=ast.literal_eval(a[3]);a1,a2,a3,a4,a6=ainvs
        b2=a1*a1+4*a2;b4=2*a4+a1*a3;b6=a3*a3+4*a6;c4=b2*b2-24*b4;c6=-b2**3+36*b2*b4-216*b6
        proj=[[int(t) for t in p.strip('[]').split(':')] for p in a[6:6+rank]]
        for X,Y,Z in proj:
            x,y=Fraction(X,Z),Fraction(Y,Z)
            assert y*y+a1*x*y+a3*y==x**3+a2*x*x+a4*x+a6;exact_equations+=1
        records.append(dict(N=N,c4=c4,c6=c6,cremona=a[0]+a[1]+a[2],lmfdb=labels[a[0]+a[1]+a[2]],ainvs=ainvs,source_rank=rank,projective=proj,source_line=n,torsion_structure=ast.literal_eval(a[5])))
    assert records==json.loads((W/'points.json').read_text())
    return {'curves':len(records),'point_equations':exact_equations,'entries':sum(r['source_rank']*(r['source_rank']+1)//2 for r in records),'source_hashes_checked':True,'exact_roster_match':True}
if __name__=='__main__':
    result=check();(W/'input-evidence.json').write_text(json.dumps(result,indent=2));print(json.dumps(result))
