"""Builder's alternate-formula check for T855; this is not a critique verdict.

Run with mpmath 1.4.1 (no Sage imports required):
    python check_values.py stored-document.json --output check-results.json
The input can be a NumberDB full document or offline-results.json. Every stored
interval is checked, not only its displayed midpoint. A theta series at the
original aspect ratio replaces the generator's modular_lambda. A smooth real
integral after t=y*u^3 replaces its hypergeometric call. For x>1/2 use the exact
beta-integral symmetry with y=1-x; direct theta evaluation still uses the
original r. The K-ratio is independently evaluated at x to catch orientation,
modulus and nome errors. mpmath is a high-precision independent implementation,
not a rigorous error-bound library; the producer's Arb enclosures carry the
rigour claim. This program evaluates at 160 decimal digits.
"""
import argparse
from decimal import Decimal
from fractions import Fraction
import hashlib
import json
from pathlib import Path
import re
import sys
import time
import mpmath as mp

mp.mp.dps = 160


def mfrac(v):
    return mp.mpf(v.numerator) / v.denominator


def interval(text):
    text = str(text).strip()
    if re.fullmatch(r'-?\d+(?:/\d+)?', text):
        return Fraction(text), Fraction(text), Fraction(0)
    if not re.fullmatch(r'-?(?:\d+\.\d*|\d*\.\d+)(?:[eE][+-]?\d+)?', text):
        raise ValueError('Unsupported, nonfinite or deliberately wide interval text')
    d = Decimal(text)
    center = Fraction(d)
    exp = d.as_tuple().exponent
    ulp = Fraction(10**exp) if exp >= 0 else Fraction(1, 10**(-exp))
    return center - ulp, center + ulp, ulp


def narrow_finite_containment(text, expected):
    lo, hi, ulp = interval(text)
    if not mp.isfinite(expected):
        return False
    if ulp and not (mfrac(ulp) < abs(expected) * mp.mpf('1e-97')):
        return False
    return mfrac(lo) <= expected <= mfrac(hi)


def reference(r):
    rr = mfrac(Fraction(r))
    q = mp.exp(-mp.pi * rr)
    x = (mp.jtheta(2, 0, q) / mp.jtheta(3, 0, q))**4
    a = mp.mpf(1) / 3
    y = min(x, 1-x)
    # Substitution t=y*u^3 removes the singularity at t=0.
    beta_y = 3 * mp.root(y, 3) * mp.quad(
        lambda u: (1-y*u**3)**(-mp.mpf(2)/3), [0, mp.mpf(1)/2, 1])
    c = beta_y / mp.beta(a, a)
    if x > mp.mpf(1)/2:
        c = 1-c
    k_ratio = mp.ellipk(1-x) / mp.ellipk(x)
    return c, x, abs(k_ratio-rr)


def entries(data):
    if 'entries' in data:
        return data['entries']
    block = data['Numbers']
    if isinstance(block, list):
        return block
    return [{'params': {'r':str(r)}, 'number': v if isinstance(v,str) else v['number']}
            for r,v in block.items()]


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('input', type=Path)
    p.add_argument('--output', default='-')
    args = p.parse_args()
    start = time.monotonic()
    data = json.loads(args.input.read_text())
    rows = entries(data)
    expected_ids = {str(Fraction(a,b)) for a in range(1,9) for b in range(1,9)}
    actual_ids = [str(row['params']['r']) for row in rows]
    failures = []
    if set(actual_ids) != expected_ids or len(actual_ids) != 43:
        failures.append('Default 43-ratio enumeration mismatch')
    refs = {}; comparisons=[]
    for i,row in enumerate(rows):
        r=str(row['params']['r']); val,x,kerr=reference(r);refs[r]=val
        passed=narrow_finite_containment(row['number'],val)
        if not passed:failures.append('Reference outside stored interval at r='+r)
        if not (kerr < mp.mpf('1e-140')):failures.append('K-ratio mismatch at r='+r)
        lo,hi,ulp=interval(row['number']);center=(lo+hi)/2
        # If input retains exact Arb endpoints, test containment of the whole enclosure.
        arb_contained = None
        if 'lower' in row:
            arb_contained=lo<=Fraction(row['lower'])<=Fraction(row['upper'])<=hi
            if not arb_contained:failures.append('Arb ball not contained in stored interval at r='+r)
        comparisons.append({'r':r,'contained':bool(passed),'reference':mp.nstr(val,145),
                            'lambda':mp.nstr(x,145),'K_ratio_error':mp.nstr(kerr,8),
                            'center_error_ulps':mp.nstr(abs(mfrac(center)-val)/mfrac(ulp),10) if ulp else 'exact',
                            'arb_contained':arb_contained})
        if (i+1)%10==0:print('Checked',i+1,'of',len(rows),flush=True)
    c1,x1,k1=reference('1');c2,x2,k2=reference('2')
    known_square=abs(c1-mp.mpf(1)/2)<mp.mpf('1e-150') and abs(x1-mp.mpf(1)/2)<mp.mpf('1e-150')
    known_lambda2=abs(x2-(17-12*mp.sqrt(2)))<mp.mpf('1e-150')
    if not known_square or not known_lambda2:failures.append('Known-answer control failed')
    row2=next(row for row in rows if str(row['params']['r'])=='2')
    lo,hi,ulp=interval(row2['number'])
    shifted=mp.nstr(mfrac((lo+hi)/2+10*ulp),100,strip_zeros=False)
    negative_shift=not narrow_finite_containment(shifted,c2)
    negative_orientation=not narrow_finite_containment(row2['number'],1-c2)
    negative_inputs=True
    for bad in ['NaN','[0,1]','0.2']:
        try:okay=narrow_finite_containment(bad,c2)
        except ValueError:okay=False
        negative_inputs=negative_inputs and not okay
    negative=negative_shift and negative_orientation and negative_inputs
    if not negative:failures.append('Deliberately wrong control was accepted')
    duality=max(abs(refs[r]+refs[str(1/Fraction(r))]-1) for r in actual_ids)
    if not duality<mp.mpf('1e-140'):failures.append('Duality identity failed')
    ordered=sorted((Fraction(r),v) for r,v in refs.items())
    monotone=all(ordered[i][1]>ordered[i+1][1] for i in range(len(ordered)-1))
    if not monotone:failures.append('Horizontal orientation monotonicity failed')
    result={'table':'T855','actor_role':'builder alternate-formula check; not independent scientific review',
            'input_sha256':hashlib.sha256(args.input.read_bytes()).hexdigest(),
            'program_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            'checked_entries':len(rows),'total_entries':len(rows),'failures':failures,
            'known_answer_control':bool(known_square and known_lambda2),
            'negative_control_rejected':bool(negative),
            'controls':{'square':bool(known_square),'lambda_2i_equals_17_minus_12_sqrt2':bool(known_lambda2),
                        'ten_ulp_shift_rejected':bool(negative_shift),'orientation_reversal_rejected':bool(negative_orientation),
                        'nonfinite_and_wide_rejected':bool(negative_inputs),
                        'ten_ulp_shift_input':shifted,'original_r2_text':row2['number']},
            'duality_max_error':mp.nstr(duality,8),'monotone_decreasing':bool(monotone),
            'working_decimal_digits':mp.mp.dps,'versions':{'Python':sys.version,'mpmath':mp.__version__},
            'elapsed_seconds':time.monotonic()-start,'comparisons':comparisons}
    out=json.dumps(result,indent=2)+'\n'
    if args.output=='-':print('CHECK_RESULT_JSON:'+json.dumps(result))
    else:Path(args.output).write_text(out)
    if failures:raise SystemExit(1)


if __name__=='__main__':
    main()
