"""Independent-formula checks prepared by the builder, not a critique verdict.

Requires SageMath 10.9 and numberdb. Example:
    sage -python build_check.py --table T123 --output check-results.json
For a private draft configure NUMBERDB_API_KEY, or pipe the key while setting
NUMBERDB_KEY_FROM_STDIN=1. The script only reads the website.

All stored rows are checked against Pruessner--Moloney (1)--(2), using the
five residue-class sums separately, native Arb modular_eta, and a separately
implemented Poisson-transformed form (11). No production helper is imported.
The residue coefficient has absolute value at most 2. Its omitted tail beyond
|n|<=K is bounded by 4 exp(-c*(K+1)^2)/(1-exp(-c*(2K+3))), c=2*pi*A/3.
This is evaluation independence within the same CFT formula, not a proof of
its physical scaling-limit interpretation. The controller must obtain a fresh
independent scientific and argument-selection critique.
"""
import argparse
from fractions import Fraction
from functools import lru_cache
from math import gcd
import json,os,re,sys
from pathlib import Path
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField

BITS=640
F=RealBallField(BITS); C=ComplexBallField(BITS)


def rational(x):
    f=Fraction(str(x)); return QQ(f.numerator)/f.denominator


def expected_parameters():
    shapes=sorted({Fraction(u,v) for v in range(1,7) for u in range(v,7)})
    rows=[]
    for r in shapes:
        pairs=[]
        # Bounds 8 and 4 strictly enclose the ellipse for every selected r.
        for a in range(9):
            for b in range(5):
                metric=Fraction(a*a,1)/r+b*b*r
                if gcd(a,b)==1 and metric<=10:
                    pairs.append((a,b,metric))
        pairs.sort(key=lambda p:(p[0]*p[1]!=0,p[2],p[0],p[1]))
        rows += [(str(r),str(a),str(b)) for a,b,metric in pairs]
    return rows


@lru_cache(maxsize=50000)
def eta(r):
    e=C(0,F(r)).modular_eta()
    assert e.real().is_finite() and e.imag().is_finite() and e.imag().contains_zero()
    assert e.real().lower()>0 and e.real().accuracy()>BITS-30
    return e.real()


def theta(t):
    v=C(0).jacobi_theta(C(0,F(t)))[2]
    assert v.real().is_finite() and v.imag().is_finite() and v.imag().contains_zero()
    return v.real()


@lru_cache(maxsize=20000)
def residue_probability(r,a,b):
    r=QQ(r); A=QQ(a*a)/r+b*b*r
    c=F.pi()*F(QQ(2)/3)*F(A)
    k=0
    target=F(2)**(-BITS+40)
    while True:
        tail=4*(-c*(k+1)**2).exp()/(1-(-c*(2*k+3)).exp())
        if tail.upper()<target.lower(): break
        k+=1
    gaussians={n:(-c*n*n).exp() for n in range(-k,k+1)}
    # The five sums in (1); do not use the compact theta coefficients.
    s0=sum((v for n,v in gaussians.items() if n%3==0),F(0))
    s1=sum((v for n,v in gaussians.items() if n%3==1),F(0))
    s2=sum((v for n,v in gaussians.items() if n%3==2),F(0))
    seven=sum((v for n,v in gaussians.items() if n%2==0),F(0))
    sodd=sum((v for n,v in gaussians.items() if n%2==1),F(0))
    raw=(s0-(s1+s2)/2-seven+sodd).add_error(tail)
    return (F(QQ(2)/(3*r))).sqrt()*raw/eta(r)**2


def poisson_probability(r,a,b):
    r=QQ(r); B=QQ(a*a)+b*b*r*r
    sums=[]
    for g in [QQ(6),QQ(8)/3,QQ(2)/3]:
        # Pruessner--Moloney (11), using native theta at the dual argument.
        sums.append(theta(r/(g*B))/F(B).sqrt())
    return (sums[0]/2-sums[1]+sums[2]/2)/eta(r)**2


def cross_probability(r):
    # Original partition sums (5)--(6), rather than the dossier's transformed X.
    r=QQ(r); g=QQ(8)/3
    def zc(f):
        return F(f)*(F(g/r)).sqrt()*theta(g*f*f/r)*theta(g*f*f*r)/eta(r)**2
    return (zc(QQ(1))-zc(QQ(1)/2))/2


def decimal_interval(text):
    match=re.fullmatch(r'([+-]?\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?',str(text))
    if not match: raise ValueError('Expected an ordinary stored decimal')
    center=Fraction(str(text)); decimals=match.group(2)
    exponent=int(match.group(3) or '0')
    if decimals is None and match.group(3) is None:
        return rational(center),rational(center),QQ(0)
    unit=Fraction(10)**(exponent-len(decimals or ''))
    return rational(center-unit),rational(center+unit),rational(unit)


def narrow(v,digits=120):
    return bool(v.is_finite() and v.lower()>0 and
                (v.rad_as_ball()/abs(v)).upper() < (F(10)**(-digits)).lower())


def matches(text,v):
    if not narrow(v): return False
    lo,hi,ulp=decimal_interval(text)
    return bool((v-F(lo)).lower()>0 and (F(hi)-v).lower()>0)


def same(v,w):
    return bool(narrow(v) and narrow(w) and v.overlaps(w))


def diagonal_tail_bound(r,M):
    # Bound D=2*sum_{a,b>=1,gcd=1}P outside a,b<=M; discard coprimality.
    r=QQ(r); c=2*F.pi()/3
    alpha=c/F(r); beta=c*F(r)
    def positive_bound(t): return (-t).exp()/(1-(-3*t).exp())
    def tail_bound(t): return (-t*(M+1)**2).exp()/(1-(-t*(2*M+3)).exp())
    pref=F(QQ(2)/(3*r)).sqrt()/eta(r)**2
    return 8*pref/(1-(-6*c).exp())*(tail_bound(alpha)*positive_bound(beta)+positive_bound(alpha)*tail_bound(beta))


def check_records(records):
    expected=expected_parameters()
    actual=[tuple(str(row['params'][k]) for k in ['r','a','b']) for row in records]
    assert actual==expected, 'Stored selection/order differs from the independent ellipse enumeration'
    assert len(actual)==75 and len(set(actual))==75
    failures=[]; comparisons=[]; worst=100000
    for row,identity in zip(records,actual):
        r=rational(identity[0]);a=int(identity[1]);b=int(identity[2]); text=str(row['number'])
        v=residue_probability(r,a,b); p=poisson_probability(r,a,b)
        checks={'residue_in_stored':matches(text,v), 'poisson_in_stored':matches(text,p),
                'independent_overlap':same(v,p),
                'reciprocity':same(v,residue_probability(1/r,b,a)),
                'reflection':same(v,residue_probability(r,a,-b))}
        if not all(checks.values()): failures.append({'identity':identity,'checks':checks})
        worst=min(worst,int(v.accuracy()),int(p.accuracy()))
        comparisons.append({'identity':identity,'checks':checks,'residue_bits':int(v.accuracy()),
                            'poisson_bits':int(p.accuracy()),'stored':text})
    # Published square control: Newman--Ziff (15), an interpretation/scale check.
    square=residue_probability(QQ(1),1,0)
    square_cross=cross_probability(QQ(1))
    known=matches('0.169415435',square) and matches('0.309526275',square_cross)
    sample=records[0]; sample_text=sample['number']; sample_id=actual[0]
    reference=residue_probability(rational(sample_id[0]),int(sample_id[1]),int(sample_id[2]))
    lo,hi,ulp=decimal_interval(sample_text)
    nonaxial=residue_probability(QQ(2),1,2)
    # A deliberately wrong geometric convention puts r in both terms of A.
    wrong_metric=QQ(1)*2+4*2
    right_metric=QQ(1)/2+4*2
    wrong_geometry=residue_probability(QQ(1),1,3) # A=10, with a separate prefactor
    # Directly evaluate the wrong A with the same independent residue scheme:
    wrong_geometry=wrong_geometry*eta(QQ(1))**2/eta(QQ(2))**2/F(2).sqrt()
    controls={'known_square_axial':bool(matches('0.169415435',square)),
              'known_square_cross':bool(matches('0.309526275',square_cross)),
              'reject_shift_10_ulp':not matches(sample_text,reference+F(10*ulp)),
              'reject_two_colors':not matches(sample_text,2*reference),
              'reject_exact_zero_snap':not matches('0',reference),
              'reject_nan':not matches(sample_text,F('nan')),
              'reject_wide_ball':not matches(sample_text,F(0).add_error(1)),
              'reject_wrong_aspect_one_coordinate':not same(nonaxial,wrong_geometry),
              'reject_diagonal_as_cross':not same(residue_probability(QQ(1),1,1),square_cross)}
    partition=[]
    shapes=sorted({rational(identity[0]) for identity in actual})
    M=32
    for r in shapes:
        diag=2*sum((residue_probability(r,a,b) for a in range(1,M+1)
                    for b in range(1,M+1) if gcd(a,b)==1),F(0))
        tail=diagonal_tail_bound(r,M)
        diag=diag.add_error(tail)
        x=cross_probability(r); ax=residue_probability(r,1,0);ay=residue_probability(r,0,1)
        residual=2*x+ax+ay+diag-1
        ok=bool(residual.is_finite() and residual.contains_zero() and residual.rad_as_ball().upper()<(F(10)**(-120)).lower())
        if not ok:failures.append({'partition_r':str(r),'residual':str(residual)})
        partition.append({'r':str(r),'max_index':M,'omitted_D_bound':str(tail.upper()),
                          'residual':str(residual),'pass':ok})
        wrong=residual-diag/2
        controls['reject_one_slope_r='+str(r)]=bool(wrong.is_finite() and not wrong.contains_zero())
        # Both-direction wrapping includes nonaxial rank-one classes.
        controls['reject_both_equals_cross_r='+str(r)]=not same(x+diag,x)
    if not all(controls.values()):failures.append({'controls':controls})
    return {'checked_entries':len(records),'total_entries':75,'failures':failures,
            'known_answer_control':bool(known),'negative_control_rejected':all(controls.values()),
            'minimum_independent_accuracy_bits':worst,'working_bits':BITS,
            'controls':controls,'comparisons':comparisons,'event_partition':partition,
            'independence':'Original five residue-class sums with native modular_eta; separate native-theta Poisson implementation. Same CFT input, builder-authored checks; no independent actor verdict.'}



def records_of(document):
    """Use the installed client's existing reader for nested/grouped storage."""
    assert tuple(document['Parameters'])==('r','a','b')
    if isinstance(document['Numbers'],list):
        return document['Numbers']
    from numberdb._generate import _stored_entries
    found=_stored_entries(document)
    rows=[]
    for identity,text in found.items():
        values=identity.split(',')
        assert len(values)==3
        rows.append({'params':dict(zip(('r','a','b'),values)),'number':text})
    return rows


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--table',required=True);parser.add_argument('--output',type=Path,required=True)
    args=parser.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1': numberdb.configure(api_key=sys.stdin.read().strip())
    table=numberdb.table(args.table)
    results=check_records(records_of(table));args.output.write_text(json.dumps(results,indent=2)+'\n')
    print(json.dumps({k:results[k] for k in ['checked_entries','total_entries','failures','known_answer_control','negative_control_rejected']}))
    if results['failures']:raise SystemExit(1)

if __name__=='__main__':main()
