"""Independent exact-Neumann angular-contour check.

sage -python checks.py [--stored stored.json] [--output check-results.json]

This does not read the production finite-expression coefficients or its log(2)
correction. For l>=1 it reconstructs BGEK (4.18)-(4.28) with u=-(d-2)/2,
using exact Debye derivative cumulants, Hurwitz zeta pole cancellation, and
a rigorously summed angular remainder. For l=0, k*J_a'-a*J_a=-k*J_(a+1)
shows that positive roots are those of J_(d/2); its zero is removed exactly.
Thus no singular Robin limit or guessed zero-mode normalization is used.
The checker shares BGEK's general spectral analysis and Arb with the builder,
and reuses tested generic Hurwitz/wire-interval helper components from the
Dirichlet build. It is a separate formula implementation, not a fresh critic.
"""
import argparse,json,pathlib,time
from decimal import Decimal
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.arith.misc import bernoulli,factorial

BITS=600;K=80;M=110;G=120
R=RealBallField(BITS);C=ComplexBallField(BITS)
P=PolynomialRing(QQ,'t');t=P.gen()


@lru_cache(maxsize=None)
def cumulants(nmax,u):
    U=[P(1)];W=[P(1)];D=[P(0)];B=[P(0)]
    for n in range(1,nmax+1):
        prev=U[-1]
        U.append(t*t*(1-t*t)*prev.derivative()/2+((1-5*t*t)*prev).integral()/8)
        W.append(U[n]+t*(t*t-1)*(prev/2+t*prev.derivative())+u*t*prev)
        D.append(U[n]-sum(QQ(k)/n*D[k]*U[n-k] for k in range(1,n)))
        B.append(W[n]-sum(QQ(k)/n*B[k]*W[n-k] for k in range(1,n)))
        assert B[n](1)==D[n](1)+(-1)**(n+1)*u**n/n
    return tuple(B)


def angular(d):
    if d==2:return QQ(1),P(2)
    a=QQ(d-2)/2;h=2*t
    for j in range(1,d-2):h*=t-a+j
    return a,h/factorial(d-2)


def hz(s,a):return C(s).zeta(C(a)).real()


def hzd(s,a):
    if a.denominator()==1:
        m=int(a)
        return C(s).zetaderiv(1).real()+sum(R(k).log()*R(k)**(-s) for k in range(1,m))
    m=int(a-QQ(1)/2)
    base=(R(2)**s-1)*C(s).zetaderiv(1).real()+R(2)**s*R(2).log()*C(s).zeta().real()
    return base+sum(R(QQ(k)+QQ(1)/2).log()*R(QQ(k)+QQ(1)/2)**(-s) for k in range(m))


def remainder(d,start,h,B,u):
    N=d-1;value=R(0)
    for j in range(K):
        q=start+j;v=R(q)
        term=(C(v+1).log_gamma().real()+v-(v+R(QQ(1)/2))*v.log()
              -(2*R.pi()).log()/2-(1+R(u)/v).log())
        term+=sum(R(B[n](1))/v**n for n in range(1,N+1))
        value+=R(h(q))*term
    b=start+K
    # The first N inverse powers cancel the corresponding Stirling terms.
    for k in range((N+1)//2+1,M):
        coeff=bernoulli(2*k)/(ZZ(2*k)*ZZ(2*k-1))
        value+=R(coeff)*sum(R(h[j])*hz(2*k-1-j,b) for j in range(h.degree()+1) if h[j])
    bound=R(abs(bernoulli(2*M)/(ZZ(2*M)*ZZ(2*M-1))))*sum(R(abs(h[j]))*hz(2*M-1-j,b) for j in range(h.degree()+1) if h[j])
    # -log(1+u/v) plus its first N cancelling powers, with |u|<b.
    for n in range(N+1,G+1):
        coeff=(-1)**n*u**n/n
        if coeff:value+=R(coeff)*sum(R(h[j])*hz(n-j,b) for j in range(h.degree()+1) if h[j])
    geom=R(abs(u)**(G+1)/(ZZ(G+1)*(1-abs(u)/b)))*sum(R(abs(h[j]))*hz(G+1-j,b) for j in range(h.degree()+1) if h[j])
    assert bound>=0 and geom>=0 and bound+geom<R(10)**(-150)
    return value+R(0,(bound+geom).upper()),bound,geom


def contour_derivative(d,derivative_only=False):
    a,h=angular(d)
    u=QQ(0) if derivative_only or d==2 else -a
    start=a if derivative_only or d==2 else a+1
    B=cumulants(d-1,u);e=h.list();log2=R(2).log()
    asym=sum(R(e[j])*((log2-1)*hz(-1-j,start)-hzd(-1-j,start)+hzd(-j,start)/2) for j in range(len(e)) if e[j])
    gamma=R.euler_constant()
    for i in range(1,d):
        coeff=B[i](1)
        for j in range(len(e)):
            if not e[j]:continue
            if i-j==1:
                weighted=sum(R(c)*(C(QQ(power)/2).psi().real()+gamma) for power,c in enumerate(B[i].list()) if c)
                asym+=R(e[j])*(R(coeff)*C(start).psi().real()-weighted/2)
            elif coeff:asym-=R(e[j]*coeff)*hz(i-j,start)
    rem,bound,geom=remainder(d,start,h,B,u)
    # Fixed-order Bessel zeta derivative: log(2^nu Gamma(nu+1)/sqrt(2*pi)).
    nu=QQ(d)/2
    radial=R(0) if derivative_only else nu*log2+C(nu+1).log_gamma().real()-(2*R.pi()).log()/2
    return asym+rem+radial,{'asymptotic':str(asym),'angular_remainder':str(rem),
        'stirling_tail_bound':str(bound),'log_tail_bound':str(geom),'radial_l_zero':str(radial),
        'multiplicity_polynomial':str(h),'angular_origin':str(start),'u':str(u)}


def sound(x):return x.is_finite() and R(x.rad())<R(10)**(-110)
def close(x,y):return sound(x) and sound(y) and x.overlaps(y)


def bounds(text):
    text=str(text)
    if '.' not in text and 'e' not in text.lower():q=QQ(text);return q,q
    dec=Decimal(text);parts=dec.as_tuple()
    coefficient=int(''.join(map(str,parts.digits)))*(-1 if parts.sign else 1)
    unit=QQ(10)**parts.exponent;centre=coefficient*unit
    return centre-unit,centre+unit


def encloses(text,expected):
    lo,hi=bounds(text)
    if lo==hi:return close(R(lo),expected)
    return sound(expected) and lo<QQ(expected.lower()) and QQ(expected.upper())<hi


def run(stored=None):
    from generate import BallNeumann,source_derivative
    gen=BallNeumann();details=[];failures=[];computed={}
    interval=-(2*(R(2)/R.pi()).log()*C(0).zeta().real()+2*C(0).zetaderiv(1).real())
    computed[1]=interval
    controls={'interval':close(interval,R(4).log())}
    for d in range(2,7):
        before=time.monotonic();v,components=contour_derivative(d);computed[d]=-v
        details.append({'d':d,'logdet':str(-v),'seconds':time.monotonic()-before,**components})
        print('contour',d,str(-v),flush=True)
    # Independent geometric comparison in KL Cor.2.5, Thms.4.3 and 4.5.
    z=lambda n:C(n).zetaderiv(1).real()
    ld2=-2*z(-1)-QQ(5)/12-R(2).log()/6-R.pi().log()/2
    # DA (12),(14) gives this Dirichlet three-ball effective action, L=2W.
    ld3=2*(QQ(3)/8*z(-2)-z(-1)/4-QQ(1)/16+R(2).log()/24+QQ(7)/64)
    ls3=-2*z(-1)-z(0)
    controls['disk_Dowker_71']=close(computed[2],-2*z(-1)+QQ(7)/12-R(2).log()/6+R.pi().log()/2)
    controls['disk_geometric_ratio']=close(computed[2]-ld2,1+R.pi().log())
    controls['ball3_geometric_ratio']=close(computed[3]-ld3,QQ(3)/8-R(3).log()+ls3)
    controls['small_Robin_eigenvalue']=all(2*(QQ(d-2)/2+1)==d for d in range(2,7))
    entries=list(gen.enumerate());stored_rows=[]
    if stored:
        doc=json.loads(pathlib.Path(stored).read_text());data=doc['Numbers']
        assert list(doc['Parameters'])==list(gen.parameters)
        assert [(str(d),c) for d,rows in data.items() for c in rows]==[(str(p['d']),p['convention']) for p in entries]
    for p in entries:
        expected=computed[p['d']]
        if p['convention']=='det':expected=expected.exp()
        v=R(gen.value(p,100))
        if not close(v,expected):failures.append({'params':p,'produced':str(v),'expected':str(expected)})
        if stored:
            row=data[str(p['d'])][p['convention']];raw=str(row['number'] if isinstance(row,dict) else row)
            from numberdb._compare import digits_of
            if not encloses(raw,expected):failures.append({'params':p,'stored':raw,'expected':str(expected)})
            if p=={'d':1,'convention':'det'}:assert raw=='4'
            else:assert digits_of(raw)>=100
            lo,hi=bounds(raw)
            assert not encloses(str(lo+1 if lo==hi else lo+10*(hi-lo)),expected)
            stored_rows.append({'params':p,'number':raw,'independent_ball':str(expected),'contained':bool(encloses(raw,expected))})
    wrong,_=contour_derivative(3,derivative_only=True)
    negatives={'uncorrected_source_factor_two':all(not close(-R(source_derivative(d,100)),computed[d]) and close(-R(source_derivative(d,100))-R(2).log(),computed[d]) for d in range(3,7)),
        'wrong_sign':not close(-computed[2],computed[2]),
        'wrong_multiplicity':not close(computed[4]/2,computed[4]),
        'derivative_only_radial_equation':not close(-wrong,computed[3]),
        'wrong_zero_mode_sector':not close(computed[3]+R(details[1]['radial_l_zero']),computed[3]),
        'wrong_radius':not close(computed[2]+QQ(5)/3*R(2).log(),computed[2]),
        'nan':not close(R('nan'),computed[2]),'wide':not close(R(0,R(1).upper()),computed[2]),
        'wrong_exact_interval':not close(R(2),R(4))}
    return {'checked_entries':len(entries),'total_entries':len(entries),'failures':failures,
        'known_answer_control':all(controls.values()),'known_controls':{k:bool(v) for k,v in controls.items()},
        'negative_control_rejected':all(negatives.values()),'negative_controls':{k:bool(v) for k,v in negatives.items()},
        'precision_bits':BITS,'K':K,'M':M,'G':G,'mode':'offline' if stored is None else 'stored',
        'dimensions':details,'stored_rows':stored_rows,
        'method':'Exact Neumann l=0 removal followed by general Robin angular contour; no finite-expression oracle',
        'limitations':'Shared BGEK spectral analysis and Arb; independent implementation by this builder, not a critic verdict.'}


if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--stored');p.add_argument('--output',default='check-results.json');a=p.parse_args()
    result=run(a.stored);pathlib.Path(a.output).write_text(json.dumps(result,indent=2))
    print(json.dumps({k:v for k,v in result.items() if k not in ['dimensions','stored_rows']},indent=2))
    raise SystemExit(bool(result['failures']) or not result['known_answer_control'] or not result['negative_control_rejected'])
