"""Independent whole-domain witness checker for T806, no collocation imports.
Uses reverse-polynomial factorization, exact rational Taylor shifts, then a
separate binomial-series convolution; certificates are untrusted inputs.
Run: sage -python check_certificates.py [certificates.json] [stored-document.json]
Writes JSON results to stdout (capture under the run's evidence directory).
"""
import numberdb.sage as numberdb
import sage.all
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
import json,sys,hashlib,time
B=RealBallField(1600);P=PolynomialRing(QQ,'t');t=P.gen();PB=PolynomialRing(B,'t')

def check_one(cert,sign_test=True):
    cs=[QQ(v) for v in cert['coefficients']];f=P(cs);degree=f.degree();rev=P(list(reversed(cs)))
    subdivisions=16;order=200;h=QQ(1)/(2*subdivisions);rho=QQ(1)/2
    minima=[]
    for name,desired in [('lo',1),('hi',-1)]:
        s=QQ(cert[name]);assert 0<=s<=1
        margins=[];tails=[];positive=[]
        for index in range(subdivisions):
            c=QQ(2*index+1)/(2*subdivisions)
            shifted=f(t+c);res=-PB(shifted)
            major=sum(B(abs(ck))*B(c+rho)**k for k,ck in enumerate(cs))
            for a in cert['alphabet']:
                q=QQ(a)+c;gamma=2*s+degree
                # q^-gamma * (1+t/q)^-gamma times q^degree f(1/q).
                seq=[B(q)**(-B(gamma))]
                for j in range(1,order):seq.append(-seq[-1]*B(gamma+j-1)/B(j*q))
                poly=PB(rev(t+q));term=(PB(seq)*poly).truncate(order)
                res+=term
                major+=sum(B(abs(ck))*B(q-rho)**(-B(2*s+k)) for k,ck in enumerate(cs))
            remainder=major*B(h/rho)**order/(1-B(h/rho))
            variation=remainder+sum(abs(res[j])*B(h)**j for j in range(1,order))
            margin=desired*res[0]-variation
            positivity=B(shifted[0])-sum(abs(B(shifted[j]))*B(h)**j for j in range(1,degree+1))
            assert margin.is_finite() and positivity.is_finite() and remainder.is_finite()
            assert remainder < B(10)**(-110)
            if sign_test:assert margin>0 and positivity>0,(cert['alphabet'],name,index,str(margin),str(positivity))
            margins.append(margin);positive.append(positivity);tails.append(remainder)
        minima.append({'endpoint':name,'residual_margin':str(min(margins)),'positive_f':str(min(positive)),'tail_bound':str(max(tails))})
    return minima

def singleton_control():
    # f=1, s=0 gives L_{a,0}1=1 identically; for a=2, s>0 gives L_s1<1.
    # Both follow directly from the definition and known singleton dimension 0.
    q=B(2).union(B(3))
    assert q.is_finite() and q**B(0)==1
    assert q**(-B(1)/10)<1
    return True

def main():
    path=sys.argv[1] if len(sys.argv)>1 else 'certificates.json';certs=json.load(open(path))
    if isinstance(certs,dict):certs=certs['certificates']
    result={'checked_entries':0,'total_entries':len(certs),'failures':[],'known_answer_control':singleton_control(),'negative_control_rejected':False,'method':'exact reverse-polynomial shift and ball binomial convolution with analytic Cauchy tail','bits':1600,'entries':[]}
    for cert in certs:
        start=time.time()
        try:r=check_one(cert);result['checked_entries']+=1;result['entries'].append({'alphabet':cert['alphabet'],'bounds':[cert['lo'],cert['hi']],'inequalities':r,'seconds':time.time()-start})
        except Exception as exc:result['failures'].append({'alphabet':cert['alphabet'],'error':str(exc)})
        print('CHECK_PROGRESS',cert['alphabet'],result['checked_entries'],'seconds',round(time.time()-start,2),flush=True)
    # A wrong bracket on the correct E2 witness must fail, rather than merely overlap.
    e2=next(c for c in certs if c['alphabet']==[1,2]);bad=dict(e2);bad['lo']=str(QQ(e2['lo'])+QQ(1)/100);bad['hi']=str(QQ(e2['hi'])+QQ(1)/100)
    try:check_one(bad)
    except AssertionError:result['negative_control_rejected']=True
    else:result['failures'].append('wrong bracket was accepted')
    low=QQ('53128050627720514162446864736847178549305910901839877988839780392752953564383134591810957018118523987')/10**101
    high=low+QQ(2)/10**101
    assert QQ(e2['lo'])>low and QQ(e2['hi'])<high
    result['E2_external_control']={'reference':'Jenkinson-Pollicott arXiv:1611.09276v2 Theorem 1','source_lo':str(low),'source_hi':str(high),'computed_bracket_contained':True}
    # External sparse intervals; these test only source-supported digits.
    samples={'2-4-6-8-10':('0.5173570309370173046666284748364397337','1e-37'),'1-4-9':('0.500790232142100396','1e-18'),'2-3-6-9':('0.500322800596840463','1e-18')}
    from decimal import Decimal
    def exact_decimal(v):
        return QQ(str(Decimal(v).as_integer_ratio()[0]))/QQ(str(Decimal(v).as_integer_ratio()[1]))
    result['source_comparisons']=[]
    for cert in certs:
        key='-'.join(map(str,cert['alphabet']));lo=QQ(cert['lo']);hi=QQ(cert['hi']);assert 0<lo<hi<1 and hi-lo<QQ(1)/10**100
        if key in samples:
            mid,rad=map(exact_decimal,samples[key]);source_lo=mid if key=='2-4-6-8-10' else mid-rad
            contained=source_lo<lo<hi<mid+rad
            result['source_comparisons'].append({'alphabet':key,'source_interval_contains_certificate':bool(contained),'source_midpoint_or_lower':samples[key][0],'source_radius_or_width':samples[key][1],'difference_in_source_radius_units':str(((lo+hi)/2-mid)/rad),'assessment':'external comparison agrees' if contained else 'printed numerical interval contradicted by verified whole-domain inequalities; not used as certified input'})
            if key=='2-4-6-8-10':assert contained
            assert lo>QQ(1)/2
    initial=[c for c in certs if c['alphabet']==list(range(1,max(c['alphabet'])+1))]
    initial.sort(key=lambda c:len(c['alphabet']));assert all(QQ(a['hi'])<QQ(b['lo']) for a,b in zip(initial,initial[1:]))
    for cert in certs:
        if cert not in initial:
            container=next(c for c in initial if max(c['alphabet'])==max(cert['alphabet']));assert QQ(cert['hi'])<QQ(container['lo'])
    if len(sys.argv)>2:
        doc=json.load(open(sys.argv[2]));records=doc.get('Numbers',doc.get('Data',[]))
        # Host-side live-storage checker expands actual document schema separately.
        result['stored_document_sha256']=hashlib.sha256(open(sys.argv[2],'rb').read()).hexdigest()
    print('RESULT_JSON '+json.dumps(result),flush=True)
    assert not result['failures'] and result['checked_entries']==result['total_entries'] and result['negative_control_rejected']
if __name__=='__main__':main()
