"""T776: signed arithmetic oscillatory parts of Li coefficients.

Requires SageMath >=10.9 (Arb/FLINT real ball polynomials) and numberdb.
  sage -pip install numberdb
  sage -python generate.py                 # compute/check offline, no writes
  sage -python generate.py --publish       # fill the authorized target draft
  sage -python generate.py --verify        # reproduce every stored entry
Default selection: every positive integer order n=1,...,100, with 100
significant decimal digits. --offline prints a resumable production JSON.

We form H(u)=1+u*(zeta(1+u)-1/u) with native pole-deflated ball series,
then C_n=sum_{m=1}^n binomial(n,m)*m*[u^m]log H(u). Coefficients through
degree n are exact formal truncations: later coefficients cannot contribute.
FLINT encloses analytic evaluation and propagated arithmetic error. Working
precision starts at 1024 bits and increases if retained accuracy is inadequate.
The finite cutoff is practical, not the domain of this integer-index family.
No stored coefficients or decimal constants are used as inputs.
Maślanka math/0402168v5 (2.4),(2.6); Coffey math-ph/0505052v1 (12),(13),(52).
"""
import os,sys,json,platform,pathlib,argparse,subprocess
from functools import lru_cache
from math import comb
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.rings.real_arb import RealBallField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.integer_ring import ZZ
from sage.env import SAGE_VERSION

DEFAULT_MAX=100

@lru_cache(maxsize=8)
def compute(nmax=DEFAULT_MAX,digits=100,working_bits=None):
    bits=working_bits or max(1024,numberdb.bits(digits,losing=4*nmax+128))
    while True:
        R=RealBallField(bits); P=PolynomialRing(R,'u');u=P.gen()
        regular=(1+u)._zeta_series(nmax,a=1,deflate=True)
        h=1+u*regular
        logarithm=h._log_series(nmax+1)
        eta=[-ZZ(m)*logarithm[m] for m in range(1,nmax+1)]
        values=[-sum((ZZ(comb(n,m))*eta[m-1] for m in range(1,n+1)),R(0))
                for n in range(1,nmax+1)]
        if all(v.is_finite() and not v.contains_zero() and
               v.accuracy()>=numberdb.bits(digits,losing=64) for v in values):
            return values,eta,bits
        if working_bits:raise ArithmeticError('Insufficient specified working precision')
        bits*=2

class OscillatoryLi(numberdb.Generator):
    table=os.environ.get('NUMBERDB_TABLE','T776')
    parameters=('n',)
    type='R'
    digits=100
    rigour='proven'
    def enumerate(self,nmax=DEFAULT_MAX):
        for n in range(1,nmax+1):yield {'n':n}
    def value(self,params,digits):
        n=int(params['n'])
        if n<1:raise ValueError('n must be a positive integer')
        return compute(max(DEFAULT_MAX,n),digits)[0][n-1]

def offline():
    v,e,b=compute()
    result={'method':'pole-deflated-zeta-log-binomial-v1','working_bits':b,
            'digits':100,'nmax':DEFAULT_MAX,
            'minimum_relative_bits':min(int(x.accuracy()) for x in v),
            'native_types':sorted(set(type(x).__name__ for x in v)),
            'values':[str(x) for x in v], 'eta':[str(x) for x in e],
            'entries':[{'params':{'n':n},'number':to_text(v[n-1],100)} for n in range(1,101)]}
    versions={'sage':SAGE_VERSION,'python':platform.python_version(),'numberdb':numberdb.__version__,
              'native_polynomial':type(PolynomialRing(RealBallField(1024),'u').gen()).__name__}
    try:versions['flint']=subprocess.check_output(['pkg-config','--modversion','flint'],text=True).strip()
    except (OSError,subprocess.SubprocessError):versions['flint']='shared Sage Arb/FLINT; pkg-config unavailable'
    print('VERSIONS_JSON '+json.dumps(versions),flush=True)
    print('PRODUCTION_JSON '+json.dumps(result),flush=True)
    try:
        pathlib.Path(__file__).with_name('production.json').write_text(json.dumps(result,indent=2))
        pathlib.Path(__file__).with_name('versions.json').write_text(json.dumps(versions,indent=2))
    except OSError:pass
    return result

def main():
    p=argparse.ArgumentParser();p.add_argument('--publish',action='store_true');p.add_argument('--verify',action='store_true');p.add_argument('--offline',action='store_true');a=p.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
        token=sys.stdin.read().strip()
        if '=' in token and token.split('=',1)[0].isupper():token=token.split('=',1)[1].strip().strip('\"\'')
        numberdb.configure(api_key=token)
    g=OscillatoryLi()
    if a.publish or os.environ.get('NUMBERDB_PUBLISH')=='1':
        print(g.publish())
    elif a.verify:print(g.verify(sample=None))
    else:offline()
if __name__=='__main__':main()
