"""Harmonic central binomial sums, NumberDB T716.

sage -pip install numberdb
sage -python generate.py              # verify every stored entry, read only
sage -python generate.py --publish    # fill the authorized draft, no offer

Use a configured NumberDB API key for the private draft. Requires SageMath or
passagemath with Arb and polynomial arithmetic. Parameter order is (p,v);
H_(2n), n>=1, signed v, no normalization. Default p=1..8 at the four exact
rational arguments listed below. harmonic_sum supports any positive order
at these four arguments. Work bits=bits(digits)+224, series degree=bits+48.
The series/log-moment method adapts the attached public T699 generator,
with a new uniform majorant also covering the hyperbolic boundary. Neither
stored sibling values nor a sibling verdict are used. See computation.md for
proofs and attribution, checks.py for independent numerical evidence.
Session/model declarations are supplied externally, never fixed in this file.
"""
import argparse
import os
import sys
from functools import lru_cache
from math import comb, factorial
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing

ARGUMENTS = ('-1/4', '-1/16', '1/16', '1/4')


def selection(max_order=8):
    for p in range(1, int(max_order)+1):
        for v in ARGUMENTS:
            yield {'p': p, 'v': v}


@lru_cache(maxsize=None)
def prepare(kind, key, digits):
    bits = numberdb.bits(digits, losing=224)
    R = RealBallField(bits)
    assert kind == 'trig'
    a = R.pi()*R(QQ(key))
    assert 0 < QQ(key) <= QQ(1)/2
    return prepare_at(kind, key, digits, R, a)


@lru_cache(maxsize=None)
def hyperbolic_prepare(key, digits):
    R = RealBallField(numberdb.bits(digits, losing=224))
    z, scale = key.split(':')
    z = R(QQ(z))
    a = int(scale)*(z+(1+z*z).sqrt()).log()
    return prepare_at('hyperbolic', key, digits, R, a)


def prepare_at(kind, key, digits, R, a):
    degree = R.precision()+48
    P = PolynomialRing(R, 'w')
    ratio = (a/(2*R.pi()))**2
    rho = R(2)
    assert rho*4*ratio < 1
    c = [R(0)]
    for j in range(1, degree+1):
        x = R(2*j).zeta()*ratio**j/j
        c.append(-x if kind == 'trig' else (-1)**(j+1)*x)
    sine = P([a.log()] + c[1:])
    cosine = P([R(2).log()] + [(4**j-1)*c[j] for j in range(1,degree+1)])
    A = -2*(1-rho*ratio).log()
    B = -2*(1-rho*4*ratio).log()
    return R, a, degree, sine, cosine, A, B


@lru_cache(maxsize=None)
def prepared(kind,key,digits):
    return prepare(kind,key,digits) if kind=='trig' else hyperbolic_prepare(key,digits)


@lru_cache(maxsize=None)
def power(kind,key,digits,which,exponent):
    R,a,N,S,C,A,B = prepared(kind,key,digits)
    if exponent == 0:
        return S.parent().one()
    base = S if which=='sine' else C
    return (power(kind,key,digits,which,exponent-1)*base).truncate(N+1)


@lru_cache(maxsize=None)
def segment(m,n,kind,key,digits):
    """Minus the mixed log integral over [0,a], with its complete tail."""
    r,s = m-1,n-1
    R,a,N,S,C,A,B = prepared(kind,key,digits)
    answer = R(0)
    for i in range(r+1):
        poly = (power(kind,key,digits,'sine',r-i)*power(kind,key,digits,'cosine',s)).truncate(N+1)
        moment = sum((c/R(2*j+1)**(i+1) for j,c in enumerate(poly.list())),R(0))
        answer += comb(r,i)*(-1)**i*factorial(i)*moment
    answer *= -a
    majorant = sum((R(comb(r,i)*factorial(i))*(abs(a.log())+A)**(r-i)
                   for i in range(r+1)),R(0))*(R(2).log()+B)**s
    answer = answer.add_error((a*R(2)**(-N-1)*majorant).upper())
    assert type(answer).__name__ == 'RealBall' and answer.is_finite()
    assert answer.accuracy() >= numberdb.bits(digits+25)
    return answer


@lru_cache(maxsize=None)
def mixed(m,n,kind,key,digits):
    if kind=='hyperbolic':
        return segment(m,n,kind,key,digits)
    t=QQ(key)
    if t <= QQ(1)/2:
        return segment(m,n,kind,str(t),digits)
    full=segment(m,n,kind,'1/2',digits)+segment(n,m,kind,'1/2',digits)
    return full if t==1 else full-segment(n,m,kind,str(1-t),digits)


@lru_cache(maxsize=None)
def harmonic_sum(p,v,digits=100):
    p,digits=int(p),int(digits)
    v=QQ(v)
    if p<1 or str(v) not in ARGUMENTS:
        raise ValueError('Require p>=1 and v in '+str(ARGUMENTS))
    R=RealBallField(numberdb.bits(digits,losing=224))
    z=QQ(1)/2 if abs(v)==QQ(1)/4 else QQ(1)/4
    L=R(2).log() if z==QQ(1)/2 else R(0)
    if v>0:
        kind='trig';theta='1/2' if z==QQ(1)/2 else '1/6'
        twice=str(2*QQ(theta))
    else:
        kind='hyperbolic';theta=str(2*z)+':1';twice=str(2*z)+':2'
    answer=R(0)
    for j in range(1,p+1):
        if L==0 and j<p:
            continue
        inner=mixed(j,2,kind,twice,digits)/2
        inner-=sum((comb(j-1,l-1)*mixed(l,j-l+2,kind,theta,digits)
                    for l in range(1,j+1)),R(0))
        answer+=(-1)**(j-1)*comb(p-1,j-1)*L**(p-j)*inner
    answer/=R(z)*factorial(p-1)
    assert answer.is_finite() and answer.accuracy()>=numberdb.bits(digits+20)
    return answer


class HarmonicCentralBinomialSums(numberdb.Generator):
    table='T716'
    parameters=('p','v')
    type='R'
    digits=100
    rigour='proven'

    def enumerate(self,max_order=8):
        yield from selection(max_order)

    def value(self,params,digits):
        return harmonic_sum(params['p'],params['v'],digits)


if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish',action='store_true')
    args=parser.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
        key=sys.stdin.read().strip()
        if '=' in key and key.split('=',1)[0].isidentifier():
            key=key.split('=',1)[1].strip().strip('\"\'')
        numberdb.configure(api_key=key)
    g=HarmonicCentralBinomialSums()
    report=g.publish(removing=False) if args.publish or os.environ.get('NUMBERDB_PUBLISH')=='1' else g.verify(sample=None)
    print(report)
