"""Regularized Bessel moments for T741.

sage -pip install numberdb
sage -python generate.py                 # preview; never writes by default
sage -python generate.py --publish       # explicitly submit to the private target

Requires SageMath complex Arb integration. Chuang–Yu Corollary 28 converts
finite parts into signed sums of convergent moments. Arb integrates each
combined kernel after t=exp(-u) on (0,1), and directly on (1,A).
All omitted endpoints have explicit absolute bounds in endpoint_bound().
No asymptotic truncation is used by this generator. Cache/checkpoint files are
optional: running without them recomputes the same certified enclosures.
The working precision is 460 bits for 100 decimal digits; integration tolerance
is 2^(-400), with cutoffs exp(-128) and 128. For requested digits above 100,
these numerical controls scale explicitly. Both normalizations are real.
"""
import os,sys,json,math,time
from pathlib import Path
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.complex_arb import ComplexBallField
from sage.rings.real_arb import RealBallField
from sage.rings.rational_field import QQ


def endpoint_bound(n,a,q,R,L,A):
    """Absolute bounds on t in (0,exp(-L)) and (A,infinity).

I0(t)<=exp(t). K0(t)<=E1(t/2)<=log(2/t)+1 for 0<t<=1,
from cosh(u)>=exp(u)/2 in K0's integral. K0(t)<=sqrt(pi/(2t))*exp(-t)
from cosh(u)>=1+u^2/2. Integrate the resulting positive elementary majorants.
"""
    b=n-a;c=n-2*a
    assert c>0 and b%2==0
    small=R(a).exp()*(-(q+1)*R(L)).exp()*sum(
        R(math.comb(b,k)*math.factorial(k))*(R(L)+R(2).log()+1)**(b-k)/R(q+1)**(k+1)
        for k in range(b+1))
    h=q-b//2
    if h<0: large=R(A)**h/R(c)
    else: large=sum(R(math.factorial(h)//math.factorial(h-k))*R(A)**(h-k)/R(c)**(k+1) for k in range(h+1))
    large*=R(-c*A).exp()*(R.pi()/2)**(b//2)
    return small+large


def controls_for(digits):
    return max(460,numberdb.bits(digits,losing=128)),max(400,numberdb.bits(digits,losing=64)),max(128,digits),max(128,digits)


def compute(n,j,digits=100,progress=False):
    m=n//4;q=2*j
    assert n>=4 and n%4==0 and m<=j<=2*m-1
    bits,tolbits,L,A=controls_for(digits)
    C=ComplexBallField(bits);R=RealBallField(bits);pi=C.pi()
    coeff=[(-1)**a*math.comb(2*m,2*a)*pi**(2*a) for a in range(m)]
    def kernel(t,analytic):
        if analytic and not t.real()>0: return C('nan')
        I=t.bessel_I(0);K=t.bessel_K(0)
        return t**q*sum(coeff[a]*I**(2*a)*K**(n-2*a) for a in range(m))
    def low(u,analytic):
        t=(-u).exp();return kernel(t,analytic)*t
    out=C(0);tolerance=R(2)**(-tolbits)
    paths=[(low,list(range(0,L,4))+[L]),(kernel,[1]+list(range(4,A,4))+[A])]
    for fun,points in paths:
        for a,b in zip(points,points[1:]):
            if b<=a: continue
            z=C.integral(fun,a,b,abs_tol=tolerance,rel_tol=tolerance,eval_limit=1000000)
            assert (z.real().is_finite() and z.imag().is_finite()),(n,j,a,b,'nonfinite integration')
            out+=z
            if progress: print('segment',n,j,a,b,'bits',z.real().accuracy(),'radius',z.real().rad(),flush=True)
    error=sum(R(abs(math.comb(2*m,2*a)))*R.pi()**(2*a)*endpoint_bound(n,2*a,q,R,L,A) for a in range(m))
    out=out.real().add_error(error)*R((-1)**(m-1))/R.pi()**(2*m)
    assert out.is_finite() and not (0 in out)
    assert out.accuracy() >= numberdb.bits(digits+5), (n,j,'insufficient certified precision',out.accuracy())
    return out

@lru_cache(None)
def finite_part(n,j,digits=100):
    return compute(n,j,digits)

class RegularizedBesselMoments(numberdb.Generator):
    table='T741'
    parameters=('n','j','normalization')
    type='R';digits=100;rigour='proven'
    files=('generate.py','checks.py','argument-selection.md','numerical-evidence.json','checks-results.json','skill-manifest.json')
    def enumerate(self):
        for m in range(1,5):
            for j in range(m,2*m):
                for normalization in ['bessel','period']:
                    yield {'n':4*m,'j':j,'normalization':normalization}
    def value(self,params,digits):
        n=int(params['n']);j=int(params['j']);normalization=str(params['normalization']);m=n//4
        F=finite_part(n,j,digits)
        if normalization=='bessel': return F
        if normalization=='period': return (-1)**m*2**(n-2*j)*F.parent().pi()**(2*m)*F
        raise ValueError('unknown normalization')

if __name__=='__main__':
    g=RegularizedBesselMoments()
    if '--publish' in sys.argv: g.publish()
    else: g.preview()
