"""T849: Dirichlet spectral determinants of Euclidean balls.

Install numberdb in SageMath, then run:
  sage -python generate.py                # offline values, no writes
  sage -python generate.py --verify       # compare all stored entries
  sage -python generate.py --publish      # add values to the authorized draft

The unit ball is in R^d; in d=1 it is (-1,1). A=-Delta with homogeneous
Dirichlet conditions. The spectral zeta counts all angular multiplicities.
logdet=-Z'(0), det=exp(logdet). This implements BGEK hep-th/9505157v1,
equation (2.22), section 4's final Dirichlet formulas, and section 5.
Exact rational coefficients and Arb enclosures are used throughout.
The interval determinant is proved exactly 4 from its spectral zeta.
100 decimal digits are serialized from 429 working bits (96 guard bits).
The default dimension prefix 1..6 includes both parities and all low dimensions;
six is a practical first bound of the explicitly reduced formulas, not a
restriction on the natural family. Both invertible conventions are enumerated.
No credentials or agent provenance are stored here; configure the session.
"""
import argparse
import json
import os
import sys
from functools import lru_cache

import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField


@lru_cache(maxsize=None)
def logdet(d, digits=100):
    """Certified closed expressions; the natural-log sign is explicit."""
    C = ComplexBallField(numberdb.bits(digits, losing=96))
    R = RealBallField(C.precision())
    log2, logpi = R(2).log(), R.pi().log()
    z = lambda n: C(n).zetaderiv(1).real()
    if d == 1:
        return R(4).log()
    if d == 2:
        return -2*z(-1)-QQ(5)/12-log2/6-logpi/2
    if d == 3:
        return QQ(3)/32+log2/12+QQ(3)/4*z(-2)-z(-1)/2
    if d == 4:
        return -QQ(173)/30240-log2/90-z(-3)/3+z(-2)/2-z(-1)/6
    if d == 5:
        return -QQ(47)/9216-QQ(17)/2880*log2+QQ(5)/64*z(-4)-QQ(7)/48*z(-3)+z(-2)/32+z(-1)/48
    if d == 6:
        return QQ(4027)/6486480+log2/756-z(-5)/60+z(-4)/24-z(-2)/24+z(-1)/60
    raise ValueError('Explicit reduced implementation supports d=1,...,6')


class BallDirichlet(numberdb.Generator):
    table = 'T849'
    parameters = ('d', 'convention')
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py', 'checks.py', 'argument-selection.md',
             'research.md', 'skill-manifest.json', 'versions.json',
             'check-results.json', 'numerical-evidence.json',
             'validation-method.md')

    def enumerate(self, limit=6):
        if not 1 <= limit <= 6:
            raise ValueError('The current explicit formulas cover 1<=d<=6')
        for d in range(1, limit+1):
            for convention in ('det', 'logdet'):
                yield {'d': d, 'convention': convention}

    def value(self, params, digits):
        d, convention = int(params['d']), params['convention']
        if convention not in ('det', 'logdet'):
            raise ValueError('convention must be det or logdet')
        if d == 1 and convention == 'det':
            return ZZ(4)
        result = logdet(d, digits)
        return result.exp() if convention == 'det' else result


if __name__ == '__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish',action='store_true')
    parser.add_argument('--verify',action='store_true')
    args=parser.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    gen=BallDirichlet()
    if args.publish or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(gen.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill checked unit-ball determinant values')))
    elif args.verify:
        print(gen.verify(sample=None))
    else:
        for p in gen.enumerate():
            print(p, gen.value(p,gen.digits))
