"""Check T863's actual stored intervals using the independent PD area/shape packet.
Run with SageMath, numberdb, checks-evidence-{1,2}.json, and an authorized key
on stdin. All geometric inputs are original interval endpoints, not midpoints.
The geometry evidence itself is regenerated by check-geometry.py. This checker
writes no website data and prints its complete results JSON on stdout.
"""
import numberdb.sage as numberdb
from sage.rings.real_mpfi import RealIntervalField
from sage.rings.rational_field import QQ
from fractions import Fraction
from decimal import Decimal
import sys,json,pathlib
numberdb.configure(api_key=sys.stdin.read().strip());ROOT=pathlib.Path(__file__).parent
R=RealIntervalField(600)
rows=sum([json.loads((ROOT/f'checks-evidence-{i}.json').read_text())['knots'] for i in [1,2]],[])
evidence={(r['n'],r['k']):r for r in rows}
def interval(e):return R(QQ(e[0]),QQ(e[1]))
def text_interval(s):
 v=QQ(Fraction(s))
 if '.' not in s and 'e' not in s.lower():return R(v)
 ulp=QQ(10)**Decimal(s).as_tuple().exponent
 return R(v-ulp,v+ulp)
def formula(n,k,p,q):
 r=evidence[n,k];area=interval(r['area']);x=interval(r['pd_tau'][0]);y=interval(r['pd_tau'][1]);return (area/y*((p+q*x)**2+(q*y)**2)).sqrt()
def match(v,c):
 return bool(v.lower()>0 and v.upper()<10**6 and c.lower()>0 and c.upper()<10**6 and c.absolute_diameter()<QQ(1)/10**120 and v.overlaps(c))
doc=numberdb.table('T863');failures=[];comp=[];identities=set()
for ns,ks in doc['Numbers'].items():
 for ki,ps in ks.items():
  for pi,qs in ps.items():
   for qi,rec in qs.items():
    key=tuple(map(int,[ns,ki,pi,qi]));identities.add(key);value=text_interval(rec['number']);oracle=formula(*key)
    if not match(value,oracle):failures.append({'params':key,'issue':'stored interval differs from PD area/shape formula'})
    comp.append({'params':key,'stored':rec['number'],'comparison':'overlap' if match(value,oracle) else 'disagree','oracle_width':str(oracle.absolute_diameter())})
expected={tuple(v['params'][s] for s in ['n','k','p','q']) for r in rows for v in r['values']};assert identities==expected
known=match(R(4),formula(4,1,2,1))
negative=not match(R(8),formula(4,1,2,1)) and not match(text_interval(doc['Numbers']['5']['2']['1']['1']['number']),formula(5,2,-1,1))
assert known and negative
out={'table':'T863','checked_entries':len(comp),'total_entries':469,'failures':failures,'known_answer_control':known,'negative_control_rejected':negative,'identity_sets_match':identities==expected,'controls':{'known':'figure-eight (2,1) gives 4','wrong_scale':'8 rejected','wrong_peripheral_sign':'5_2 (1,1) differs from (-1,1)'},'comparisons':comp,'method':'Stored interval compared with sqrt(A/y*((p+q*x)^2+(q*y)^2)) using separately certified PD geometry. Shared SnapPy geometry acknowledged.'}
print('RESULT_JSON '+json.dumps(out),flush=True);assert not failures
