"""Builder's independently implemented checks, not an independent actor verdict.
Run: sage -python checks.py. Requires mpmath and computed.json (or stored-input.json).
The result JSON and reference checkpoint are also emitted on stdout. Endpoint
checks use published angular formulas for r=1,2 and Levin acceleration of
analytic gamma/polygamma summands for r=3,4. The generator is not imported.
"""
import numberdb.sage
import mpmath as m
import math,json,time,sys,functools
from pathlib import Path
m.mp.dps=160


def accepts(number, expected):
    v=m.mpf(number)
    if not m.isfinite(v) or not m.isfinite(expected) or not v:
        return False
    exponent=int(m.floor(m.log10(abs(v))))-99
    return abs(v-expected) <= m.power(10,exponent)


def interior_reference(s,r,u):
    # Python's exact combinatorial implementation; high-precision fsum of
    # independently formed terms. No reciprocal-binomial recurrence or Arb.
    H=m.mpf(0); terms=[]
    for n in range(1,1601):
        terms.append(m.mpf(u)**n*H/(n**s*math.comb(2*n,n)))
        H += m.mpf(1)/n**r
    return m.fsum(terms)


@functools.lru_cache(maxsize=None)
def A21_at_precision(t,dps):
    with m.workdps(dps):
        return A21_uncached(t)


def A21_angle(t):
    return A21_at_precision(t,m.mp.dps)


def A21_uncached(t):
    if abs(t) < m.mpf('0.25'):
        u=4*m.sin(t/2)**2
        H=m.mpf(0); terms=[]
        for n in range(1,160):
            terms.append(u**n*H/(n*n*math.comb(2*n,n)))
            H += m.mpf(1)/n
        return m.fsum(terms)
    phi=m.pi-t
    z=m.exp(1j*phi)
    return 4*m.re(m.polylog(3,z))-2*t*m.im(m.polylog(2,z))+3*m.zeta(3)


def endpoint_reference(s,r,dps):
    with m.workdps(dps):
        if r==1:
            if s==2:
                return +7*m.zeta(3)   # DK (2.47) at theta=pi
            power=s-3
            def f(t):
                if not t or t==m.pi:return m.mpf(0)
                L=-2*m.log(m.sin(t/2))
                return A21_angle(t)*m.cot(t/2)*L**power/m.factorial(power)
            return +m.quad(f,[0,m.mpf('0.25'),1,2,m.pi])
        if r==2:
            power=s-2
            if power==0:return +m.pi**4/24
            def f(t):
                if not t:return m.mpf(0)
                return t**3*(-2*m.log(m.sin(t/2)))**power/(6*m.factorial(power))
            return +m.quad(f,[0,1,2,m.pi])  # DK (2.11),(2.44)
        def term(n):
            H=m.zeta(r)-(-1)**r*m.polygamma(r-1,n)/m.factorial(r-1)
            return m.sqrt(m.pi)*m.gammaprod([n+1],[n+m.mpf('0.5')])*H/n**s
        return +m.nsum(term,[2,m.inf],method='levin',levin_variant='u',steps=[100]*4,maxterms=400)


def compare_records(records, references):
    failures=[]; comparisons=[]
    for rec in records:
        key=','.join(str(rec['params'][k]) for k in ('s','r','u'))
        expected=m.mpf(references[key]);v=m.mpf(rec['number'])
        ok=accepts(rec['number'],expected)
        if not ok:failures.append(key)
        ulp=m.power(10,int(m.floor(m.log10(abs(v))))-99)
        comparisons.append({'key':key,'inside_stored_interval':ok,'error_in_ulp':m.nstr(abs(v-expected)/ulp,8)})
    return failures,comparisons


def main():
    started=time.time();base=Path(__file__).parent
    inp=base/('stored-input.json' if (base/'stored-input.json').exists() else 'computed.json')
    records=json.loads(inp.read_text())['records'];refs={};agreement=[]
    for rec in records:
        s,r,u=(int(rec['params'][k]) for k in ('s','r','u'));key=f'{s},{r},{u}'
        if u==4:
            v1=endpoint_reference(s,r,140);v2=endpoint_reference(s,r,180)
            err=abs(v1-v2)
            if not err < m.mpf('1e-120')*max(1,abs(v2)):
                raise AssertionError('independent endpoint precision disagreement '+key+' '+str(err))
            v=v2;agreement.append({'key':key,'difference':m.nstr(err,8),'precisions':[140,180]})
        else:v=interior_reference(s,r,u)
        refs[key]=m.nstr(v,150)
        print('REFERENCE_JSON '+json.dumps({'key':key,'reference':refs[key],'endpoint_agreement':agreement[-1] if u==4 else None}),flush=True)
    failures,comparisons=compare_records(records,refs)
    identities=[]
    for rec in records:
        s,r,u=(int(rec['params'][k]) for k in ('s','r','u'))
        if r==2 and s in (1,2):
            theta=2*m.asin(m.sqrt(m.mpc(u))/2)
            expected=theta**3*m.tan(theta/2)/6 if s==1 else theta**4/24
            assert abs(m.im(expected)) < m.mpf('1e-140')
            ok=accepts(rec['number'],m.re(expected));identities.append({'params':rec['params'],'passed':ok})
            if not ok:failures.append('DK2.11 '+str(rec['params']))
    known=accepts(m.nstr(m.pi**4/24,100),m.pi**4/24) and accepts(refs['2,2,4'],m.pi**4/24)
    bad=m.mpf(refs['2,2,4'])+m.mpf('1e-50')
    rejected=not accepts(m.nstr(bad,100),m.pi**4/24) and not accepts('nan',m.pi**4/24)
    assert known and rejected
    results={'stage':'builder','checked_entries':len(records),'total_entries':len(records),'failures':failures,'known_answer_control':bool(known),'negative_control_rejected':bool(rejected),'comparisons':comparisons,'published_identity_checks':identities,'endpoint_precision_agreement':agreement,'references':refs,'seconds':time.time()-started,'python':sys.version,'mpmath':m.__version__,'method':'exact combinatorial binomial implementation in mpmath; independent angular quadrature and closed forms for endpoint r=1,2; Levin gamma/polygamma summands for r=3,4','limitations':'Levin/quad comparisons are heuristic numerical evidence; the generator supplies separate rigorous error bounds. This is builder evidence, not an independent critic verdict.'}
    print('CHECK_JSON '+json.dumps(results),flush=True)
    try:
        (base/'check-results.json').write_text(json.dumps(results,indent=2))
    except PermissionError:
        pass  # The caller persists the stdout checkpoint in a read-only builder.
    if failures:raise SystemExit(1)

if __name__=='__main__':main()
