"""T745: Boyd elliptic L-values, with a rigorous split Mellin enclosure.

Use SageMath with elliptic curves, PARI and Arb. Install the client:
    sage -pip install numberdb
Run:
    sage -python generate.py             # reproduce and compare all stored values
    sage -python generate.py --preview   # compute without writing
    sage -python generate.py --publish   # explicitly fill the authorized draft
The last command submits entries only, never offers or publishes a table.

n is a positive integer other than 9. The default selects every n <= 36.
The two normalization keys are at-two and derivative-at-zero, in that order.
The exact curve is [0,n-24,0,-16*(n-9),0] over QQ. Its arithmetic primitive
L-function retains all bad factors. N and w are the conductor and root number.

For c=2*pi/sqrt(N), split the modular Mellin integral at height 1/sqrt(N):
 S=N*L(2)/(4*pi^2)=sum a_m*(exp(-c*m)*(1/(c*m)+1/(c*m)^2)+w*E1(c*m)).
Here E1(x)=-Ei(-x) is real for positive x. The weight-two Fricke relation is
f(i/(sqrt(N)*y))=w*y^2*f(i*y/sqrt(N)). The omitted absolute tail is at most
 (4/c+2/(c^2*(M+1)))*exp(-c*(M+1))/(1-exp(-c)),
since |a_m|<=d(m)*sqrt(m)<=2*m and E1(x)<=exp(-x)/x.
This is a mathematical enclosure, not an error estimate attached to PARI lfun.
Arb encloses constants, elementary functions, E1, summation and scaling.
The tail is required below 10^(-digits-25); the ball is checked for finiteness,
nonzero sign and at least digits+15 relative decimal digits. Working precision
is numberdb.bits(digits+50, losing=64), in bits. Exact Euler recurrences
reconstruct coefficients from Sage/PARI prime traces on a minimal model.
The installed local-reduction and prime-trace implementations remain trusted
exact dependencies. build_check.py documents additional independent checks.

References: Bertin and Zudilin, doi:10.1007/s40316-016-0068-4, equation (1);
Sutherland, MIT 18.783 Lecture 24 (2023), slides 14-20 (Euler factors and FE).
"""
import os
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.real_arb import RealBallField
from sage.schemes.elliptic_curves.constructor import EllipticCurve
from sage.arith.misc import prime_range

NORMALIZATIONS=('at-two','derivative-at-zero')
SELECTION=tuple(n for n in range(1,37) if n!=9)

def curve(n):
    n=ZZ(n)
    if n<=0 or n==9:raise ValueError('n must be a positive integer other than 9')
    return EllipticCurve(QQ,[0,n-24,0,-16*(n-9),0])

def euler_coefficients(E,M,omit_prime=None):
    """Exact multiplicativity and local degree-one/two Euler recurrences."""
    primes=list(prime_range(M+1))
    traces=E.aplist(M,python_ints=True)
    assert len(traces)==len(primes)
    spf=list(range(M+1))
    for p in primes:
        p=int(p)
        for j in range(p*p,M+1,p):
            if spf[j]==j:spf[j]=p
    a=[0]*(M+1);a[1]=1;local={}
    N=int(E.conductor())
    for p,ap in zip(primes,traces):
        p=int(p);ap=int(ap);powers={1:1};q=p;v0=1;v1=ap
        if p==omit_prime:v1=0
        while q<=M:
            powers[q]=v1
            v0,v1=v1,ap*v1-(p*v0 if N%p else 0)
            if p==omit_prime:v1=0
            q*=p
        local[p]=powers
    for m in range(2,M+1):
        p=spf[m];r=m;q=1
        while r%p==0:r//=p;q*=p
        a[m]=local[p][q]*a[r]
        assert isinstance(a[m],int)
    return a

def mellin(E,digits=100,wrong_sign=False,omit_prime=None,c_multiplier=1):
    B=RealBallField(numberdb.bits(digits+50,losing=64))
    E=E.global_minimal_model();N=int(E.conductor());w=int(E.root_number())
    c=2*B.pi()/B(N).sqrt()*c_multiplier
    target=B(10)**(-digits-25)
    M=max(32,int(((digits+35)*B(10).log()/c).upper()))
    while True:
        tail=(4/c+2/(c*c*(M+1)))*(-c*(M+1)).exp()/(1-(-c).exp())
        if tail<target:break
        M+=32
    a=euler_coefficients(E,M,omit_prime=omit_prime)
    q=(-c).exp();power=B(1);total=B(0);absolute=B(0)
    sign=-w if wrong_sign else w
    for m in range(1,M+1):
        power*=q
        if a[m]:
            x=c*m
            term=a[m]*(power*(1/x+1/(x*x))-sign*(-x).Ei())
            total+=term;absolute+=abs(term)
    total=total.add_error(tail)
    L2=total*(4*B.pi()**2)/N;D=w*total
    for v in [L2,D]:
        assert v.is_finite() and not v.contains_zero()
        assert v.accuracy()>numberdb.bits(digits+15)
    assert L2>0 and (D>0 if w==1 else D<0)
    info={'N':N,'w':w,'M':M,'work_bits':B.precision(),
          'L2_ball':str(L2),'D_ball':str(D),'tail_completed_upper':str(tail.upper()),
          'accuracy_bits':min(int(L2.accuracy()),int(D.accuracy())),
          'cancellation_factor_upper':str((absolute/abs(total)).upper()),
          'relative_radius_L2_upper':str((B(L2.rad())/abs(L2)).upper())}
    return L2,D,info,a

@lru_cache(maxsize=None)
def compute_curve(n,digits):return mellin(curve(n),digits)

class BoydLValues(numberdb.Generator):
    table='T745'
    parameters=('n','normalization')
    type='R'
    digits=100
    rigour='proven'
    files=('generate.py',)
    def enumerate(self):
        for n in SELECTION:
            for normalization in NORMALIZATIONS:
                yield {'n':n,'normalization':normalization}
    def value(self,params,digits):
        mode=params['normalization']
        if mode not in NORMALIZATIONS:raise ValueError('unknown normalization')
        L,D,info,a=compute_curve(int(params['n']),digits)
        return {'number':L if mode=='at-two' else D,
                'param-latex':'$L_n(2)$' if mode=='at-two' else "$L_n'(0)$"}

if __name__=='__main__':
    import sys
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':numberdb.configure(api_key=sys.stdin.read().strip())
    g=BoydLValues()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH')=='1':
        print(g.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill checked elliptic L-values')))
    elif '--preview' in sys.argv:print(g.preview())
    else:print(g.verify(sample=None))
