"""Independent stdlib-only rational bounds for 2**sqrt(2).

python3 check_math.py --stored-file stored-number.txt --output check-results.json
Without --stored-file, checks numerical-evidence.json beside this script.
No Sage, Arb, floating point sqrt/log/exp, or production generator is used.

For x>=1, z=(x-1)/(x+1) is in [0,1), and integrating the geometric
series gives log(x)=2*sum z**(2*n+1)/(2*n+1). After N terms, replacing
all later denominators by 2*N+1 bounds the positive tail by
2*z**(2*N+1)/((2*N+1)*(1-z*z)).
Square-root bisection preserves lower**2<=a<=upper**2 on nonnegative
rationals. For exp, positive Taylor terms are bounded separately with
outward rational rounding. After degree M, all consecutive tail-term
ratios are <=upper/(M+2)<1, giving a geometric upper bound from the first
omitted term. Monotonicity propagates the enclosed inputs throughout.
"""
import argparse
from fractions import Fraction as F
import hashlib
import json
from pathlib import Path
import re
import sys

sys.set_int_max_str_digits(100000)
SCALE = 10**180

def floor_grid(x): return F((x.numerator*SCALE)//x.denominator, SCALE)
def ceil_grid(x): return -floor_grid(-x)
def sqrt_bounds(a, steps=650):
    a=F(a)
    if a<0: raise ValueError('negative radicand')
    if not a: return F(0),F(0)
    lo,hi=F(0),max(F(1),a)
    for _ in range(steps):
        mid=(lo+hi)/2
        if mid*mid==a: return mid,mid
        if mid*mid<a: lo=mid
        else: hi=mid
    assert 0<=lo<=hi and lo*lo<=a<=hi*hi
    return lo,hi

def log_bounds(x, terms=220):
    x=F(x)
    if x<1: raise ValueError('this checker uses log only for x>=1')
    z=(x-1)/(x+1); z2=z*z; power=z; total=F(0)
    for n in range(terms):
        total+=2*power/(2*n+1); power*=z2
    tail=2*power/((2*terms+1)*(1-z2))
    return floor_grid(total),ceil_grid(total+tail)

def exp_bounds(lo,hi,degree=160):
    lo,hi=F(lo),F(hi)
    if not 0<=lo<=hi<=1: raise ValueError('exp checker requires [0,1]')
    if hi==0: return F(1),F(1)
    termlo=termhi=sumlo=sumhi=F(1)
    for n in range(1,degree+1):
        termlo=floor_grid(termlo*lo/n); termhi=ceil_grid(termhi*hi/n)
        sumlo+=termlo; sumhi+=termhi
    ratio=hi/(degree+2)
    assert ratio<1
    tail=termhi*hi/(degree+1)/(1-ratio)
    return sumlo,ceil_grid(sumhi+tail)

def decimal_interval(s):
    s=s.strip()
    if s.startswith('['):
        a,b=s[1:-1].split(','); return F(a),F(b)
    m=re.fullmatch(r'([+-]?\d+)\.(\d+)',s)
    if not m: raise ValueError('expected a bare decimal or explicit endpoints')
    u=F(1,10**len(m[2])); c=F(s)
    return c-u,c+u

def contained(outer,inner):
    a,b=outer; c,d=inner
    return a<=c<=d<=b and 0<b-a<=F(1,10**98) and 0<=d-c<F(1,10**170)

def pair(bounds):return [str(x) for x in bounds]
def run(stored, output):
    sqrt2=sqrt_bounds(2); log2=log_bounds(2)
    exponent=(floor_grid(sqrt2[0]*log2[0]),ceil_grid(sqrt2[1]*log2[1]))
    bounds=exp_bounds(*exponent)
    controls={
        'sqrt_zero':sqrt_bounds(0)==(F(0),F(0)),
        'sqrt_four':sqrt_bounds(4)==(F(2),F(2)),
        'sqrt_two_straddle':sqrt2[0]**2<2<sqrt2[1]**2,
        'log_one':log_bounds(1)==(F(0),F(0)),
        'exp_zero':exp_bounds(0,0)==(F(1),F(1)),
        'exp_log_two':exp_bounds(*log2)[0]<=2<=exp_bounds(*log2)[1],
        'exp_log_two_narrow':0<exp_bounds(*log2)[1]-exp_bounds(*log2)[0]<F(1,10**170),
        'exp_half_nonzero':F(3,2)<exp_bounds(F(1,2),F(1,2))[0]<exp_bounds(F(1,2),F(1,2))[1]<2,
    }
    claimed=decimal_interval(stored)
    negative={n:not contained(decimal_interval(n),bounds) for n in ('2.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000','4.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000')}
    shifted=(claimed[0]+F(1,10**97),claimed[1]+F(1,10**97))
    negative['shift_by_100_ulp']=not contained(shifted,bounds)
    failures=[]
    if not contained(claimed,bounds):failures.append('independent enclosure not inside stored uncertainty')
    if not all(controls.values()):failures.append('known-answer control failed')
    if not all(negative.values()):failures.append('wrong-value control accepted')
    evidence={'checked_entries':1,'total_entries':1,'failures':failures,'known_answer_control':all(controls.values()),'negative_control_rejected':all(negative.values()),'stored_number':stored,'stored_interval':pair(claimed),'independent_interval':pair(bounds),'independent_width':str(bounds[1]-bounds[0]),'width_less_than_1e-170':bounds[1]-bounds[0]<F(1,10**170),'sqrt2':pair(sqrt2),'log2':pair(log2),'exponent':pair(exponent),'controls':controls,'negative_controls':negative,'method':{'rational_bisections':650,'log_series_terms':220,'exp_degree':160,'outward_decimal_places':180},'python_version':sys.version,'checker_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
    Path(output).write_text(json.dumps(evidence,indent=2)+'\n')
    print(json.dumps({k:evidence[k] for k in ('checked_entries','failures','known_answer_control','negative_control_rejected','width_less_than_1e-170')}))
    if failures: raise SystemExit(1)
    return evidence

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--stored-file',type=Path);p.add_argument('--output',type=Path,default=Path(__file__).with_name('check-results.json'));a=p.parse_args()
    stored=a.stored_file.read_text().strip() if a.stored_file else json.loads(Path(__file__).with_name('numerical-evidence.json').read_text())['stored_number']
    run(stored,a.output)
