"""T745 stored-interval checks; run in Sage beside generate.py.
Read-only. The key may arrive on stdin when NUMBERDB_KEY_FROM_STDIN=1.
Uses the live stored document and attached 220-digit PARI comparison data.
"""
import os,sys,json,time
from fractions import Fraction
import numberdb.sage as numberdb
from generate import BoydLValues,compute_curve,SELECTION,NORMALIZATIONS
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.real_mpfr import RealField
from numberdb._http import Client
if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
    key=sys.stdin.read().strip();numberdb.configure(api_key=key);client=Client(api_key=key)
else:client=Client()
start=time.time();g=BoydLValues();report=g.verify(sample=None);print(report,flush=True)
assert report.ok and report.checked==70 and report.matched==70
stored=numberdb.table('T745');results=client.request('api/table/T745/file/build-results.json') if False else None
# Attachments are fetched by the same authenticated client as the draft.
import urllib.request
req=urllib.request.Request('https://numberdb.org/files/T745/build-results.json?raw=1',headers={'Authorization':'Bearer '+client.api_key})
with urllib.request.urlopen(req) as r:results=json.load(r)
by_n={x['n']:x for x in results['curves']};B=RealBallField(800);R=RealField(800);checks=[];all_balls={}
def rational(x):return QQ(x.numerator)/x.denominator
def interval(text):
    f=Fraction(text);exp=int(text.lower().split('e')[1]) if 'e' in text.lower() else 0
    body=text.lower().split('e')[0];places=len(body.split('.')[1]) if '.' in body else 0
    step=Fraction(10)**(exp-places);lo=rational(f-step);hi=rational(f+step)
    return lo,hi,B(rational(f)).add_error(B(rational(step)))
for n in SELECTION:
    L,D,info,a=compute_curve(n,100)
    for mode,value in zip(NORMALIZATIONS,[L,D]):
        entry=stored['Numbers'][str(n)][mode];text=entry['number'] if isinstance(entry,dict) else entry
        lo,hi,ball=interval(text)
        assert ball.is_finite() and not ball.contains_zero() and ball.accuracy()>325
        assert lo<=value.lower().exact_rational()<=value.upper().exact_rational()<=hi
        control=R(by_n[n]['pari']['L2' if mode=='at-two' else 'D0']['at_220'])
        assert R(lo)<control<R(hi)
        if mode=='derivative-at-zero':assert (ball>0 if info['w']==1 else ball<0)
        all_balls[n,mode]=ball
        checks.append({'n':n,'normalization':mode,'enclosure_contained_in_stored_interval':True,'pari_220_inside_stored_interval':True})
    assert (all_balls[n,'derivative-at-zero']-info['w']*info['N']*all_balls[n,'at-two']/(4*B.pi()**2)).contains_zero()
wrong=all_balls[16,'at-two']+B(10)**-90
assert not wrong.overlaps(B(compute_curve(16,100)[0]))
print('STORED_RESULTS_JSON '+json.dumps({'table':'T745','stage':'build','checked_entries':70,'total_entries':70,'failures':[],
 'verify_matched':report.matched,'stored_interval_checks':checks,'perturbation_1e_minus_90_rejected':True,
 'elapsed_seconds':time.time()-start}),flush=True)
