"""Verify T650 and test independent identities on the actual stored values.

Download the generator and its helpers, check.py, integral-checks.jsonl,
hypergeom-checks.jsonl and lvalue-check.json alongside this file.
    sage -python readback_checks.py
Reading an unpublished draft requires NUMBERDB_API_KEY.
"""
import os,sys,json,pathlib
import numberdb.sage as numberdb
import mpmath as mp
from decimal import Decimal
import check
from generate import ModifiedHessian
from catalogue import selected
if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
 key=sys.stdin.read().strip()
 if '=' in key and key.split('=',1)[0].replace('_','').isupper():key=key.split('=',1)[1].strip().strip('\"\'')
 os.environ['NUMBERDB_API_KEY']=key
p=pathlib.Path(__file__).parent
report=ModifiedHessian().verify(sample=None)
print('GENERATOR_VERIFY',report,flush=True);assert report.ok

def values(doc):
 block=doc['Numbers']
 if isinstance(block,list):
  return {str(r['params']['t']):str(r['number']) for r in block}
 return {str(k):str(v.get('number') if isinstance(v,dict) else v) for k,v in block.items()}

def ulp(text):
 return mp.power(10,Decimal(text).as_tuple().exponent)

stored=values(numberdb.table('T650'))
ordinary=values(numberdb.table('T649'))
assert list(stored)==[item['key'] for item in selected()]
assert not check.exactness(stored)
roots={r['t']:r for r in map(json.loads,(p/'integral-checks.jsonl').read_text().splitlines()) if 't'in r}
hyper={r['t']:r for r in map(json.loads,(p/'hypergeom-checks.jsonl').read_text().splitlines())}
rows=[]
with mp.workdps(220):
 for key,text in stored.items():
  value=mp.mpf(text);I=mp.mpf(roots[key]['I']);J=mp.mpf(roots[key]['J']);h=mp.mpf(hyper[key]['hypergeometric']);N=mp.mpf(ordinary[key])
  error=abs(value-h)/ulp(text)
  relation=abs(value+3*J-N)/(ulp(text)+ulp(ordinary[key]))
  ordinary_error=abs(I+J-N)/ulp(ordinary[key])
  assert value<0 and error<1 and relation<1 and ordinary_error<1
  rows.append({'t':key,'independent_error_in_stored_ulps':mp.nstr(error,10),'Ntilde_plus_3J_equals_stored_N_combined_ulps':mp.nstr(relation,10),'ordinary_I_plus_J_error_in_stored_ulps':mp.nstr(ordinary_error,10)})
 l=json.loads((p/'lvalue-check.json').read_text());v=mp.mpf(l['evaluations'][-1]['modified_24'])
 lerr=abs(mp.mpf(stored['24'])-v)/ulp(stored['24']);assert lerr<1
result={'table':'T650','verified_entries':len(stored),'generator_verify_ok':True,'identity_checks':rows,'elliptic_L_value_control_in_stored_ulps':mp.nstr(lerr,10),'measure':check.measure(stored),'instruction_manifest':'agents/runs/20261101T114635Z-build-skills/manifest.json'}
print('READBACK_JSON='+json.dumps(result),flush=True)
