"""T732: read-back checks; no writes. Read the API key from stdin."""
import numberdb.sage as numberdb
import sys,json
from pathlib import Path
from generate import HeegnerTrace
from numbertext import decode_number
from builder_check import reduce,agree,narrow,C
numberdb.configure(api_key=sys.stdin.read().strip())
g=HeegnerTrace();report=g.verify(sample=None)
print('REPRODUCTION',str(report),flush=True)
assert report.checked==262 and report.matched==262 and not report.differing and not report.missing
p=Path(__file__).parent;doc=json.loads((p/'stored-entries.json').read_text());rows={tuple(str(r['params'][k]) for k in g.parameters):r for r in doc};expected=[tuple(str(p[k]) for k in g.parameters) for p in g.enumerate()];assert list(rows)==expected
for key,row in rows.items():
 N,D,b=map(int,key);op=rows[(str(N),str(D),str((-b)%(2*N)))];a=decode_number(row['number']).conjugate();other=decode_number(op['number']);w1,w2,*_=g.evaluator(N,100).periods()
 assert narrow(a,98) and narrow(other,98)
 assert any(narrow(t,98) and (a-t).contains_zero() for t in reduce(other,w1,w2)) or any(narrow(t,98) and (t-other).contains_zero() for t in reduce(a,w1,w2))
checks=[]
for sample in json.loads((p/'builder-check-results.json').read_text())['checks']:
 par=sample['params'];key=tuple(str(par[k]) for k in g.parameters);stored=decode_number(rows[key]['number']);assert narrow(stored,98)
 ev=g.evaluator(par['N'],100);z,e=ev.trace(par['D'],par['beta']);q=decode_number(sample['raw']);options=reduce(q,*e['periods']);matches=[t for t in options if agree(t,z)]
 assert matches and (stored-z).contains_zero()
 # Exact zero real components use the proved Fricke/period identity, rather
 # than pretending numerical quadrature certifies exact equality to zero.
 for comp in ['real','imag']:
  target=getattr(stored,comp)();own=getattr(z,comp)()
  if own.is_zero():assert target.is_zero() and any(getattr(t,comp)().contains_zero() for t in matches)
  else:assert any(target.contains_exact(getattr(t,comp)()) for t in matches)
 checks.append({'params':par,'stored_interval_contains_quadrature':True,'exact_components_checked':True})
res={'table':'T732','reproduction_checked_entries':report.checked,'reproduction_matched_entries':report.matched,'stored_independent_numerical_checked_entries':len(checks),'stored_conjugation_checked_entries':len(doc),'total_entries':len(doc),'failures':[],'checks':checks,'limitations':'Numerical quadrature is sampled; exact-zero real components additionally use the proved Fricke relation. No independent-actor verdict.'}
print('STORED_RESULT '+json.dumps(res),flush=True)
