"""T752: Values of the secondary zeta function.

Requirements: SageMath, numberdb, a C compiler, FLINT public headers/library.
Keep flint-secondary_zeta.c, secondary_zeta.h and secondary_bridge.c alongside
this file; they are attached with this generator. The first two files are
unmodified FLINT sources downloaded on 2026-11-18, with LGPL notices retained.
The installed older FLINT supplies the underlying Arb arithmetic and zeros.

    sage -pip install numberdb
    sage -python generate.py                 # preview, no writes
    sage -python generate.py --publish       # additive entry submission

The spectral variable is alpha=(rho-1/2)/i over every upper-half-plane zero,
with multiplicity and principal powers. No global RH assumption is used.
FLINT evaluates the Arias de Reyna decomposition with explicit remainder
bounds. Its certified finite zero prefix lies below the verified RH height;
the uncomputed tail is bounded without RH. Nonpositive even orders are exact
rationals from Voros, Tables 4 and 6, with E_n defined by sech(x).

Default coverage: s=0, then +2,-2,+3,+4,-4,...,+20,-20,+21,...,+50.
The positive orders are whole integer moment families of both parities;
negative even orders are intrinsic continued values. The bounds 50 and 20
are practical finite extents, not restrictions of the mathematical domain.
The working precision starts at bits(digits)+128 and increases if needed;
100-digit results must retain at least bits(digits)+24 relative-accuracy bits.
The actual measured precisions and verification evidence are attached.

Compilation only writes a temporary local library. Credentials and model
provenance belong in the caller's environment, never in this source.
"""
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.combinat.combinat import euler_number
from sage.env import SAGE_LOCAL
import ctypes
import math
import os
from pathlib import Path
import shlex
import subprocess
import tempfile

_ROOT = Path(__file__).resolve().parent
_NATIVE = None
_TEMP = None
EVIDENCE = {}


def native():
    global _NATIVE, _TEMP
    if _NATIVE is not None:
        return _NATIVE
    _TEMP = tempfile.TemporaryDirectory(prefix='numberdb-secondary-')
    output = str(Path(_TEMP.name) / 'secondary_zeta.so')
    prefix = Path(os.environ.get('FLINT_ROOT', SAGE_LOCAL))
    if (prefix/'include/flint/acb.h').exists():
        flags = ['-I'+str(prefix/'include/flint'), '-I'+str(prefix/'include'),
                 '-L'+str(prefix/'lib'), '-Wl,-rpath,'+str(prefix/'lib'), '-lflint']
    else:
        probe = subprocess.run(['pkg-config', '--cflags', '--libs', 'flint'],
                               capture_output=True, text=True, check=True)
        flags = shlex.split(probe.stdout)
        includedir = subprocess.run(['pkg-config', '--variable=includedir', 'flint'],
                                    capture_output=True,text=True,check=True).stdout.strip()
        flags = ['-I'+str(Path(includedir)/'flint')] + flags
    command = [os.environ.get('CC','cc'), '-shared', '-fPIC', '-O2',
               '-I'+str(_ROOT), str(_ROOT/'flint-secondary_zeta.c'),
               str(_ROOT/'secondary_bridge.c'), '-o', output] + flags + ['-lm']
    subprocess.run(command, check=True, capture_output=True, text=True)
    library = ctypes.CDLL(output)
    library.numberdb_secondary_eval.argtypes = [ctypes.c_long]*3
    library.numberdb_secondary_eval.restype = ctypes.c_void_p
    library.numberdb_secondary_free.argtypes = [ctypes.c_void_p]
    library.numberdb_flint_version.restype = ctypes.c_char_p
    _NATIVE = library
    return library


def secondary_value(s, digits=100):
    s = int(s)
    if s == 1 or (s < 0 and s % 2):
        raise ValueError('The selected integer order is a pole, not a value.')
    if s <= 0:
        n = -s//2
        return QQ((-1)**n * (8-euler_number(2*n))) / (2**(2*n+3))
    target = numberdb.bits(digits, losing=24)
    precision = numberdb.bits(digits, losing=128)
    lib = native()
    while precision <= 8*target:
        pointer = lib.numberdb_secondary_eval(s, precision, math.ceil(precision*math.log10(2))+20)
        try:
            text = ctypes.string_at(pointer).decode('ascii')
        finally:
            lib.numberdb_secondary_free(pointer)
        if text == 'invalid':
            raise ArithmeticError('FLINT returned a nonfinite or nonreal result.')
        accuracy, written = text.split('\n',1)
        if int(accuracy) >= target:
            value = RealBallField(precision)(written)
            if not value.is_finite() or not (value.rad() < abs(value).lower() * (QQ(1)/2**(target-4))):
                raise ArithmeticError('Parsed enclosure lost required precision.')
            EVIDENCE[str(s)] = {'working_bits':precision,'native_relative_accuracy_bits':int(accuracy),
                                 'parsed_relative_radius':str(value.rad()/abs(value).lower()),
                                 'native_enclosure':written,'flint_version':lib.numberdb_flint_version().decode()}
            return value
        precision += max(128, target-int(accuracy)+64)
    raise ArithmeticError('The precision budget did not establish the requested digits.')


class SecondaryZeta(numberdb.Generator):
    table = 'T752'
    parameters = ['s']
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py', 'flint-secondary_zeta.c', 'secondary_zeta.h', 'secondary_bridge.c')

    def enumerate(self):
        yield {'s':0}
        for s in range(2,51):
            yield {'s':s}
            if s <= 20 and s % 2 == 0:
                yield {'s':-s}

    def value(self, params, digits):
        return secondary_value(params['s'], digits)


if __name__ == '__main__':
    import sys
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    generator = SecondaryZeta()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        generator.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill secondary-zeta values'))
    else:
        generator.preview()
