"""Containment of the generator's actual Arb balls in the stored decimals.
Run with Sage and generate.py alongside this script. No remote writes.
Prints JSON for the run artifact collector.
"""
import json
from decimal import Decimal
from fractions import Fraction
from pathlib import Path
from generate import BananaConnection
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField

def endpoints(text):
    if text.startswith('['):
        a,b=text[1:-1].split(',');return Fraction(a.strip()),Fraction(b.strip())
    c=Fraction(Decimal(text));r=Fraction(0) if '.' not in text and 'e' not in text.lower() else Fraction(10)**Decimal(text).as_tuple().exponent
    return c-r,c+r

p=Path(__file__).parent
records=json.loads((p/'check-input.json').read_text());R=RealBallField(800);g=BananaConnection();fail=[];exact=0;inexact=0
for row in records:
    v=g.value(row['params'],100)
    txt=row['number'].split(' + i * ')
    if len(txt)==1:txt.append('0')
    parts=[v,ZZ(0)] if type(v).__name__=='Integer' else [v.real(),v.imag()]
    for comp,text in zip(parts,txt):
        lo,hi=endpoints(text);lo=QQ(lo.numerator)/ZZ(lo.denominator);hi=QQ(hi.numerator)/ZZ(hi.denominator)
        if lo==hi:
            exact+=1;ok=bool(comp==lo)
        else:
            inexact+=1;ok=bool(R(comp).is_finite() and R(comp)>R(lo) and R(comp)<R(hi))
        if not ok:fail.append({'params':row['params'],'component':text})
print('RESULT_JSON '+json.dumps({'checked_entries':len(records),'exact_components':exact,'inexact_components':inexact,'strict_ball_containment':not fail,'failures':fail,'method':'At 800 bits, compare entire 493-bit generator balls with exact rational decimal endpoints; strict comparison for nonzero-width stored intervals.'}))
assert not fail
