import sympy as sp, re, random
from fractions import Fraction
from math import factorial
import mpmath as mp
mp.mp.dps = 60
x, n, b, t = sp.symbols('x n b t')

def seqterms(sid):
    txt = open(f'/home/user/oeisdata/seq/{sid[:4]}/{sid}.seq').read()
    terms = []
    for l in txt.splitlines():
        if l.startswith(('%S','%T','%U')):
            terms += [int(v) for v in l.split(None,2)[2].split(',') if v.strip()]
        if l.startswith('%O'):
            off = int(l.split()[2].split(',')[0])
    return off, terms

# F = exp(alpha x)*(c0*I0(beta x) + c1*I1(beta x) + c2*I2(beta x)), beta = 2*sqrt(d), b=sqrt(d)
# data: id, d, alpha, (c0,c1,c2) coefficients may contain b, recurrence polys P_j(n)
SEQ = {
 'A098660': dict(d=2, alpha=0, c=(1, 1/b, 0), P=[(n+1),(n-1),-n,(2-n)]),
 'A098519': dict(d=3, alpha=1, c=(0, 1/b, 0), P=[(n-1)*(n+1), -n*(2*n-1), -11*n*(n-1)]),
 'A098660+corrected(extra)': dict(d=2, alpha=0, c=(1, 1/b, 0), P=[(n+1),4*(n-1),-8*n,32*(2-n)]),
 'A098662': dict(d=3, alpha=0, c=(1, 1/b, 0), P=[(n+1), 6*(n-1), -12*n, 72*(2-n)]),
 'A098521': dict(d=2, alpha=1, c=(0, 0, sp.Rational(1,2)), P=[(n+2), -(4*n+3), -3*(2*n+1), (20*n-29), 21*(n-3)]),
}
# NOTE for A098660/A098662: I1(beta x)/sqrt(2 or 3) with beta=2b  -> c1 = 1/b

def to_pair(c):
    """reduce c0 I0 + c1 I1 + c2 I2 to (R0,R1) using I2(z)=I0(z)-(2/z)I1(z), z=2 b x."""
    c0,c1,c2 = [sp.sympify(v) for v in c]
    return (c0 + c2, c1 - c2*2/(2*b*x))

def cx(e): return sp.cancel(sp.together(e))

def Dpair(p, alpha, B):
    R0,R1 = p
    # d/dx I0(Bx)=B I1 ; d/dx I1(Bx)= B I0 - I1/x
    return (cx(alpha*R0 + sp.diff(R0,x) + B*R1),
            cx(alpha*R1 + sp.diff(R1,x) + B*R0 - R1/x))

def Epair(F0, P, alpha, B):
    r = len(P)-1
    tot = (0,0)
    for j,Pj in enumerate(P):
        G = F0
        for _ in range(r-j): G = Dpair(G, alpha, B)
        poly = sp.Poly(sp.expand(Pj.subs(n, t + r) if hasattr(Pj,'subs') else Pj), t)
        coeffs = poly.all_coeffs()[::-1]  # c_k of theta^k
        cur = G
        acc = (0,0)
        for k,ck in enumerate(coeffs):
            acc = (acc[0]+ck*cur[0], acc[1]+ck*cur[1])
            cur = tuple(cx(x*e) if False else cx(x*Dpair(cur,alpha,B)[i]) for i,e in enumerate(cur)) if k < len(coeffs)-1 else cur
        tot = (tot[0]+acc[0], tot[1]+acc[1])
    return tuple(cx(e) for e in tot)

def reduce_b(e, d):
    num, den = sp.fraction(sp.cancel(sp.together(e)))
    num = sp.rem(sp.expand(num), b**2-d, b)
    return sp.expand(num), den

def is_zero(e,d):
    num,_ = reduce_b(e,d)
    return num == 0

def series_F(d, alpha, c, N):
    """exact Fraction coefficients of x^m, m<N, of exp(alpha x)*(c0 I0+c1 I1+c2 I2)(2 b x); c's contain b only via
    1/b for c1 (I1/b rational series). Handled by explicit rational formulas."""
    c0,c1,c2 = [sp.sympify(v) for v in c]
    I0 = [Fraction(0)]*N; I1b=[Fraction(0)]*N; I2=[Fraction(0)]*N   # I1b = I1/b
    for k in range(N):
        if 2*k < N: I0[2*k] = Fraction(d**k, factorial(k)**2)
        if 2*k+1 < N: I1b[2*k+1] = Fraction(d**k, factorial(k)*factorial(k+1))
        if 2*k+2 < N: I2[2*k+2] = Fraction(d**(k+1), factorial(k)*factorial(k+2))
    # c1 is 1/b times rational => c1*I1 = (c1*b)*I1b ; c1*b should be rational
    c1b = sp.nsimplify(sp.simplify(c1*b)); assert not c1b.has(b)
    for cc in (c0,c2): assert not cc.has(b)
    f = lambda q: Fraction(int(sp.Rational(q).p), int(sp.Rational(q).q))
    base = [f(c0)*I0[m] + f(c1b)*I1b[m] + f(c2)*I2[m] for m in range(N)]
    al = f(alpha)
    ex = [al**m/factorial(m) for m in range(N)]
    out = [sum(base[i]*ex[m-i] for i in range(m+1)) for m in range(N)]
    return out

out_lines = []
def pr(*a):
    s = ' '.join(str(v) for v in a); print(s); out_lines.append(s)

random.seed(12345)
NT = 60
summary = {}
for sid, S in SEQ.items():
    d, alpha, c, P = S['d'], S['alpha'], S['c'], S['P']
    r = len(P)-1
    pr('='*70); pr(sid, ' d=',d,' alpha=',alpha,' order r=',r)
    off, terms = seqterms(sid[:7])
    ser = series_F(d, alpha, c, NT)
    a = [ser[m]*factorial(m) for m in range(NT)]
    ok_int = all(v.denominator==1 for v in a)
    a = [int(v) for v in a]
    # cross-check explicit series vs sympy series of besseli (low order)
    bs = 2*sp.sqrt(d)
    Fs = sp.exp(alpha*x)*(sp.sympify(c[0])*sp.besseli(0,bs*x) + sp.sympify(c[1]).subs(b,sp.sqrt(d))*sp.besseli(1,bs*x) + sp.sympify(c[2])*sp.besseli(2,bs*x))
    sser = sp.series(Fs, x, 0, 10).removeO()
    chk = all(sp.simplify(sser.coeff(x,m)*factorial(m) - a[m])==0 for m in range(10))
    pr('series coefficients integer:', ok_int, '; first 10 terms agree with sympy series of besseli:', chk)
    # (a) compare with OEIS (offset: a(off) is first listed term)
    # OEIS offset 0 for all of these (first term = a(0)); handle generally
    oeis_a = {off+i: v for i,v in enumerate(terms)}
    mism = [k for k,v in oeis_a.items() if a[k] != v]
    pr(f'(a) OEIS offset={off}, {len(terms)} terms compared; mismatches: {mism}')
    if mism: pr('STOP: mismatch'); continue
    # E in closed form
    F0 = to_pair(c)
    F0 = tuple(cx(e) for e in F0)
    B = 2*b
    E0,E1 = Epair(F0, P, alpha, B)
    # reduce modulo b^2=d
    def tidy(e):
        num,den = reduce_b(e,d)
        e2 = sp.cancel(num/den)
        e2 = e2.subs(b, sp.sqrt(d))
        return sp.simplify(sp.radsimp(e2))
    R0 = tidy(E0); R1 = tidy(E1)
    pr('R0 =', R0); pr('R1 =', R1)
    zero = is_zero(E0,d) and is_zero(E1,d)
    pr('E == 0 (R0==R1==0)?', zero)
    # (b) instances on exact terms
    fails = []
    for N_ in range(r, 40):
        val = sum(sp.Rational(sp.sympify(P[j]).subs(n,N_)) * a[N_-j] for j in range(r+1))
        if val != 0: fails.append((N_, int(val)))
    pr('(b) instances n=%d..39 failing:'%r, fails)
    # prediction from E: coefficients of x^m/m! in E = exp(alpha x)(R0 I0 + R1 I1)
    if zero:
        pred = []
    else:
        # exact series of closed form with explicit Bessel series (Laurent allowed)
        M = 40 - r + 4
        I0s = sum(sp.Rational(d**k, factorial(k)**2)*x**(2*k) for k in range(M))
        I1s = sum(sp.sqrt(d)*sp.Rational(d**k, factorial(k)*factorial(k+1))*x**(2*k+1) for k in range(M))
        Ecl = sp.exp(alpha*x)*(R0*I0s+R1*I1s)
        Es = sp.series(sp.expand(Ecl), x, 0, M-2).removeO()
        pred = [(m+r, sp.simplify(Es.coeff(x,m)*factorial(m))) for m in range(0, 40-r) if sp.simplify(Es.coeff(x,m))!=0]
        pr('   E series (negative powers present?):', [k for k in range(-5,0) if sp.simplify(Es.coeff(x,k))!=0])
    pr('   predicted failing n (value of instance):', pred)
    pr('   failing set matches prediction:', [f[0] for f in fails]==[p[0] for p in pred] and all(sp.simplify(f[1]-p[1])==0 for f,p in zip(fails,pred)))
    # (c) numeric check, unsimplified E vs closed form
    thet = lambda e: x*sp.diff(e,x)
    Eun = 0
    for j,Pj in enumerate(P):
        G = sp.diff(Fs, x, r-j) if r-j>0 else Fs
        poly = sp.Poly(sp.expand(sp.sympify(Pj).subs(n,t+r)), t).all_coeffs()[::-1]
        cur = G; 
        for k,ck in enumerate(poly):
            Eun += ck*cur
            if k < len(poly)-1: cur = thet(cur)
    Ecl = sp.exp(alpha*x)*(R0*sp.besseli(0,bs*x)+R1*sp.besseli(1,bs*x))
    mx = mp.mpf(0)
    for _ in range(5):
        pt = sp.Rational(random.randint(1,499), 1000) + sp.Rational(random.randint(1,999),10**6)
        v1 = sp.N(Eun.subs(x,pt), 60); v2 = sp.N(Ecl.subs(x,pt), 60)
        res = abs(mp.mpf(str(v1))-mp.mpf(str(v2)))
        mx = max(mx,res)
        pr('   x=%s  E_unsimplified=%s  closed=%s  resid=%s'%(sp.N(pt,8), mp.nstr(mp.mpf(str(v1)),12), mp.nstr(mp.mpf(str(v2)),12), mp.nstr(res,5)))
    pr('(c) max residual over 5 points:', mp.nstr(mx,5))
    summary[sid] = (zero, fails)
pr('='*70); pr('SUMMARY'); 
for k,v in summary.items(): pr(k, 'E==0' if v[0] else 'E!=0', 'failing instances n<40:', [f[0] for f in v[1]])
open('/home/user/oeisproofs/egf_bessel_B_output.txt','w').write('\n'.join(out_lines)+'\n')
