"""Alternate formula and library check for T857, without importing its generator.

sage -python check_values.py offline-results.json
Uses Maier Formula 2.3 directly at 1-x, with D(1-x) evaluated by the
Kleban--Zagier equation (9) double integral, reducing the inner integral to
B_u(2/3,2/3). Independent mpmath theta constants replace modular_lambda.
Cubic substitutions remove the endpoint weights; the upper half is integrated
in the complementary coordinate to remain smooth near x=0. This checks all
orientations independently of the production complement branch. Quadrature
agreement is not a rigorous certificate; production and explicit series have
error-carrying balls. This is builder evidence, never an independent verdict.
"""
import json,sys,hashlib,time
from pathlib import Path
from fractions import Fraction
from decimal import Decimal
import mpmath as mp

mp.mp.dps=160
T=mp.mpf(1)/3


def fmp(q):
    q=Fraction(q)
    return mp.mpf(q.numerator)/q.denominator


def stored_bounds(text):
    d=Decimal(text);ulp=Fraction(10)**d.as_tuple().exponent;c=Fraction(d)
    return c-ulp,c+ulp,ulp


def integral_value(r):
    r=fmp(r);q=mp.exp(-mp.pi*r)
    x=(mp.jtheta(2,0,q)/mp.jtheta(3,0,q))**4
    t=1-x;cut=mp.mpf(1)/2;bc=mp.beta(2*T,2*T)
    low=lambda z:3*(1-z**3)**(-2*T)*mp.betainc(2*T,2*T,0,z**3)
    if t<=cut:
        integral=mp.quad(low,[0,t**T])
    else:
        high=lambda z:3*(1-z**3)**(-2*T)*(bc-mp.betainc(2*T,2*T,0,z**3))
        integral=mp.quad(low,[0,cut**T])+mp.quad(high,[x**T,cut**T])
    d=integral/(mp.sqrt(3)*mp.pi)
    n=mp.mpf(1)/2-d/2-mp.sqrt(3)/(4*mp.pi)*mp.log(t)
    u=min(x,1-x)
    csmall=3*u**T/mp.beta(T,T)*mp.quad(lambda z:(1-u*z**3)**(-2*T),[0,1])
    c=csmall if x<=cut else 1-csmall
    return n,x,c


def matches(text,value):
    if not mp.isfinite(value):return False
    lo,hi,_=stored_bounds(text)
    margin=mp.mpf('1e-135')*abs(value)
    return fmp(lo)+margin<value<fmp(hi)-margin


def main():
    source=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('offline-results.json')
    data=json.loads(source.read_text());out=[];failures=[]
    square=mp.mpf(3)/8+mp.sqrt(3)/(8*mp.pi)*(3*mp.log(3)-2*mp.log(2))
    square_value,_,_=integral_value('1');_,x2,_=integral_value('2')
    known=abs(square-square_value)<mp.mpf('1e-145') and mp.mpf('.5065')<square<mp.mpf('.5067') and abs(x2-(17-12*mp.sqrt(2)))<mp.mpf('1e-145')
    row2=next(r for r in data['entries'] if r['params']['r']=='2')
    reverse,_,_=integral_value('1/2')
    controls={'square_closed_form':bool(abs(square-square_value)<mp.mpf('1e-145')),
      'lambda_at_two':bool(abs(x2-(17-12*mp.sqrt(2)))<mp.mpf('1e-145')),
      'shift_rejected':not matches(data['entries'][0]['number'],square+mp.mpf('.001')),
      'two_color_factor_rejected':not matches(data['entries'][0]['number'],2*square),
      'reversed_orientation_rejected':not matches(row2['number'],reverse),
      'nan_rejected':not matches(data['entries'][0]['number'],mp.nan)}
    negative=all(v for k,v in controls.items() if 'rejected' in k)
    if not known or not negative:failures.append('controls')
    for row in data['entries']:
        start=time.monotonic();r=row['params']['r'];n,x,c=integral_value(r)
        lo,hi,ulp=stored_bounds(row['number']);mid=(lo+hi)/2
        ok=matches(row['number'],n);bounds=n>c>0 and c<1
        residual=abs(mp.ellipk(1-x)/mp.ellipk(x)-fmp(r))
        if not (ok and bounds and residual<mp.mpf('1e-140')):failures.append(r)
        item={'r':r,'independent_value':mp.nstr(n,150),'contained_in_stored_interval':bool(ok),
          'absolute_midpoint_error_ulps':mp.nstr(abs(n-fmp(mid))/fmp(ulp),12),
          'elliptic_aspect_residual':mp.nstr(residual,8),'count_exceeds_crossing_probability':bool(bounds),
          'seconds':round(time.monotonic()-start,3)}
        out.append(item);print('CHECK_ROW_JSON:'+json.dumps(item),flush=True)
    result={'table':'T857','stage':'builder alternate formula/library checks; no independent verdict',
      'program_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
      'input_sha256':hashlib.sha256(source.read_bytes()).hexdigest(),
      'skill_manifest':'../20261128T140524Z-build-skills/manifest.json',
      'skill_bundle_sha256':'f20b09e3db5fd443660c0c6b29391ee369b7c710a43e22d8abb971ec3f54dd14',
      'working_decimal_digits':mp.mp.dps,'mpmath':mp.__version__,'checked_entries':len(out),
      'total_entries':len(data['entries']),'failures':failures,'known_answer_control':bool(known),
      'negative_control_rejected':bool(negative),'controls':controls,'entries':out}
    print('CHECK_RESULT_JSON:'+json.dumps(result),flush=True)
    if failures:raise SystemExit(1)


if __name__=='__main__':main()
