"""T749: Body-centred cubic lattice Green function.

Install numberdb in SageMath (or modular passagemath with Arb):
    sage -pip install numberdb
    sage -python generate.py                 # verify all stored entries, no writes
    sage -python generate.py --publish       # additive entry upload to T749

Set NUMBERDB_API_KEY privately for this private draft, and supply actual
NUMBERDB_ENGINE / NUMBERDB_MODEL / NUMBERDB_RUN_ID provenance for an upload.
A --publish upload fills the draft; it does not offer or publish it.

For k>=8, W(k)=(2 K(alpha)/pi)^2, alpha=(1-sqrt(1-64/k^2))/2.
K takes the parameter, not the modulus. The rational argument is enclosed
before every transcendental operation. At the edge alpha=1/2 is exact.
Arb at bits(digits)+128 encloses square roots, elliptic K, pi and squaring.
All arguments are real and alpha lies in (0,1/2], where K is real analytic.
At 100 digits the run measured at least 456 relative accuracy bits; the
recorded 100-digit decimal intervals include these narrower balls.
The enumerated 8..32 selection is justified in argument-selection.md.
See numerical-evidence.md and check_green.py for independent checks and bounds.
"""
import argparse
import os
import sys
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField


def green(k, digits=100):
    k = QQ(k)
    if k < 8:
        raise ValueError('A real argument k>=8 is required.')
    R = RealBallField(numberdb.bits(digits, losing=128))
    C = ComplexBallField(R.precision())
    if k == 8:
        alpha = R(QQ(1)/2)
    else:
        alpha = (1-(1-R(QQ(64)/(k*k))).sqrt())/2
    value = ((C(alpha).elliptic_k()*2/C.pi())**2).real()
    if not value.is_finite() or value.accuracy() < numberdb.bits(digits+8):
        raise ArithmeticError('A finite sufficiently narrow enclosure is required.')
    return value


class BCCGreen(numberdb.Generator):
    table = 'T749'
    parameters = ('k',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, stop=32):
        if not isinstance(stop, int) or stop < 8:
            raise ValueError('stop must be an integer >=8')
        for k in range(8, stop+1):
            yield {'k': k}

    def value(self, params, digits):
        return green(params['k'], 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':
        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=BCCGreen()
    if args.publish or os.environ.get('NUMBERDB_PUBLISH')=='1':
        print(g.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill T749 from certified elliptic K enclosures'),
                        assisted_by=os.environ.get('NUMBERDB_ASSISTED_BY','')))
    else:
        print(g.verify(sample=None))
