"""Run independent recurrence checks on read-back values, then verify().
Run with stored-records.json, generator and offline_check.py in this directory.
Private draft read authorization arrives on stdin; it is never printed.
"""
import sys,json,io,contextlib
from pathlib import Path
import numberdb.sage as numberdb
import generate as g
import offline_check as independent

records=json.loads(Path(__file__).with_name('stored-records.json').read_text())
expected_ids=list(g.APolynomials().enumerate())
assert [x['params'] for x in records]==expected_ids
rec=independent.recurrence();checked=0
for row in records:
    p=g.R(row['number']);params=row['params'];n=g.knot_index(params['knot'])
    q=rec[n]
    if params['hand']=='mirror':q=g.normalize(g.F(q)(g.L,1/g.F(g.M)))
    if params['form']=='with-abelian':q=g.normalize((g.L-1)*q)
    assert p==q,params
    checked+=1
# Exercise the displayed Programs example outside the stored finite prefix.
namespace={}
with contextlib.redirect_stdout(io.StringIO()):
    exec(Path(__file__).with_name('program_example.py').read_text(),namespace)
L,M=g.L,g.M
X=(1-L)*M**8+2*L*M**6+(L+1)**2*M**4+2*L*M**2+L**2-L
D=M**2*(L+M**2)**2
assert g.R(namespace['p'])==g.normalize(X*rec[-4]-D**2*rec[-3])
key=sys.stdin.read().strip()
if '=' in key and key.split('=',1)[0] in ('NUMBERDB_API_KEY','NUMBERDB_KEY'):
    key=key.split('=',1)[1].strip().strip('"\'')
client=numberdb.Client(api_key=key,as_sage=True)
report=g.APolynomials().verify(sample=None,client=client)
assert report.ok and report.matched==30 and report.checked==30
print('VERIFY',str(report))
print('VERIFY_FIELDS',json.dumps({k:getattr(report,k) for k in ('table','checked','matched','differing','missing','extra','coarser','refined')},default=str,sort_keys=True))
print('STORED_RESULT',json.dumps({'checked_entries':checked,'total_entries':len(records),'failures':[],'all_identities_match':True,'independent_recurrence_matches':True,'program_example_matches_next_negative_twist':True}))
