"""Compute exact Fermat plane quotients, checkpoint before Smith/determinant work.

Run with lattice.py and modular.py beside this file. Optional target.json is a
list of [n,d] pairs to compute in this process. Previous certificate-*.json.gz
and quotient-*.json.gz checkpoints can be supplied beside the script.
The wrapper capture_sage.py writes named artifact lines to the run work dir.
"""
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.matrix.constructor import matrix
from sage.misc.misc_c import prod
from lattice import selected_pairs,gram,quotient,matrix_json
from modular import smith_factors
from pathlib import Path
import json,time,gzip,sys,base64,gc
work=Path(__file__).parent

def emit(name,data):print('ARTIFACT '+name+' '+base64.b64encode(data).decode(),flush=True)

def packed(obj):return gzip.compress(json.dumps(obj,separators=(',',':')).encode(),mtime=0)

pairs=json.loads((work/'target.json').read_text()) if (work/'target.json').exists() else selected_pairs()
results=[]
for n,d in pairs:
 name=f'certificate-{n}-{d}.json.gz';rawname=f'quotient-{n}-{d}.json.gz'
 if (work/name).exists():
  obj=json.loads(gzip.decompress((work/name).read_bytes()));results.append(obj['summary']);print('resume complete',n,d,flush=True);continue
 t=time.monotonic();print('start',n,d,flush=True)
 if (work/rawname).exists():
  obj=json.loads(gzip.decompress((work/rawname).read_bytes()));G=matrix(ZZ,obj['G']);K=matrix(ZZ,obj['K']);r=K.nrows();N=len(obj['planes']);print('resume quotient',n,d,flush=True)
 else:
  gramname=f'gram-{n}-{d}.json.gz'
  if (work/gramname).exists():
   go=json.loads(gzip.decompress((work/gramname).read_bytes()));ps=go['planes'];G=matrix(ZZ,go['G']);print('resume Gram',n,d,flush=True)
  else:
   ps,G=gram(n,d);emit(gramname,packed({'planes':ps,'G':matrix_json(G)}));print('gram',len(ps),'elapsed',round(time.monotonic()-t,2),flush=True)
  J,H,C,K=quotient(G);r=K.nrows();N=len(ps)
  obj={'n':n,'d':d,'planes':ps,'pivot_columns':J,'H':matrix_json(H),'C':matrix_json(C),'K':matrix_json(K),'G':matrix_json(G),'quotient_seconds':time.monotonic()-t}
  emit(rawname,packed(obj));print('quotient checkpoint',n,d,flush=True)
  del C,H;gc.collect()
 determinant=K.det(algorithm='flint');print('determinant',n,d,'elapsed',round(time.monotonic()-t,2),flush=True)
 ed,proof=smith_factors(K,determinant);print('local Smith complete',n,d,flush=True)
 signature=[1,r-1] if n%4==2 else [r,0]
 assert determinant==(-1)**signature[1]*prod(ed)
 summary={'n':n,'d':d,'planes':N,'rank':r,'signature':signature,'signed_determinant':str(determinant),'absolute_discriminant':str(abs(determinant)),'elementary_divisors':ed,'elapsed_seconds':time.monotonic()-t,'quotient_seconds':obj.get('quotient_seconds')}
 obj['summary']=summary;obj['local_smith_certificate']=proof
 emit(name,packed(obj));results.append(summary)
 emit('latest-computation.json',json.dumps(results,indent=2).encode());print('done',n,d,'rank',r,'seconds',round(time.monotonic()-t,2),flush=True)
