"""Dependent live-corpus consistency check, additional to alternate math checks.

Needs numberdb/Sage, check_evidence.py and the four selected live JSON files.
No sibling table supplies independent evidence. The current stored T775
polynomials must divide T657's transformed 2A polynomials exactly; T774's
complete coefficient brackets must isolate their correct positive roots.
"""
import pathlib,json
from decimal import Decimal
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.libs.pari import pari
from check_evidence import theta_value,qrat,narrow
p=pathlib.Path(__file__).parent
S=PolynomialRing(QQ,'x');x=S.gen()
def bounds(text):
 if '.' not in text and 'e' not in text.lower():return QQ(text),QQ(text)
 d=Decimal(text);mid=qrat(d);ulp=QQ(10)**int(d.as_tuple().exponent);return mid-ulp,mid+ulp
rows={tid:{int(e['params']['r']):e['number'] for e in json.load(open(p/(tid+'-selected.json')))} for tid in ['T774','T634','T657']}
polys={int(e['params']['r']):S(e['number']) for e in json.load(open(p/'stored-flat.json'))['Numbers']}
result=[]
for r,M in polys.items():
 t,lam=theta_value(r);B=t.parent();lo,hi=bounds(rows['T774'][r]);claim=B((lo+hi)/2).add_error(B((hi-lo)/2))
 assert M(lo)*M(hi)<0 and not M.derivative()(claim).contains_zero()
 assert claim.lower().exact_rational()<=t.lower().exact_rational() and t.upper().exact_rational()<=claim.upper().exact_rational()
 P=S(rows['T657'][r]);transformed=P(256*x**4-104)
 assert transformed%M==0
 a,b=bounds(rows['T634'][r]);v=B((a+b)/2).add_error(B((b-a)/2));actual=256*t**4-104
 assert narrow(actual) and narrow(v,280) and actual.overlaps(v)
 result.append({'r':r,'T775_minpoly':str(M),'T657_2A_polynomial':str(P),'exact_transformed_divisibility':True,'T774_full_bracket_isolates_root':True,'T634_scalar_agrees':True})
phi=pari.ellmodulareqn(2);assert phi[1]==0 and phi[0]==pari('(x+16)^3-x*y')
print('CROSSCHECK_JSON='+json.dumps({'checked_entries':10,'total_entries':10,'rows':result,'all_matched':True,'canonical_ellmodulareqn_2':str(phi),'limitations':'Dependent corpus consistency; this is not an independent scientific verdict.'}))
