"""Reproduce T882, the Ramanujan-Soldner constant.

Install SageMath with Arb and numberdb: sage -pip install numberdb
Check the current table: sage -python generate.py
Fill this authorized private draft: sage -python generate.py --publish
The --publish option submits entries only; it never offers or publishes a draft.
Configure credentials and session provenance outside this reusable file.

This named constant has no parameters.
Ei is the real principal-value exponential integral. Its derivative exp(r)/r
is positive for r>0. Strict endpoint signs on [1/4,1/2] and dyadic bisection
therefore enclose its unique positive zero. Exponentiating the entire root
ball propagates uncertainty to mu. The working field has at least 512 bits;
refinement is to 30 decimal guard digits past the requested precision.
DLMF 6.2.8, 6.6.1 and 6.13.1 fix the normalization and zero.
"""
import os
import sys
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField


def enclose(digits=100, working_bits=None):
    bits = max(512, numberdb.bits(digits + 60)) if working_bits is None else working_bits
    field = RealBallField(bits)
    low, high = QQ(1)/4, QQ(1)/2
    left, right = field(low).Ei(), field(high).Ei()
    assert left.is_finite() and right.is_finite() and left < 0 and right > 0
    target = QQ(1)/10**(digits+30)
    iterations = 0
    while high-low > target:
        middle = (low+high)/2
        evaluation = field(middle).Ei()
        assert evaluation.is_finite()
        if evaluation < 0:
            low = middle
        elif evaluation > 0:
            high = middle
        else:
            bits *= 2
            field = RealBallField(bits)
            continue
        iterations += 1
    left, right = field(low).Ei(), field(high).Ei()
    assert left < 0 and right > 0
    root = field(low).union(field(high))
    value = root.exp()
    assert root.is_finite() and value.is_finite() and value > 1
    assert value.rad() > 0 and value.rad().exact_rational() < QQ(1)/10**(digits+25)
    return value, {'working_bits':bits,'iterations':iterations,
                   'root_lower':str(low),'root_upper':str(high),
                   'root_ball':str(root),'root_radius':str(root.rad()),
                   'mu_ball':str(value),'mu_radius':str(value.rad()),
                   'endpoint_Ei_lower':str(left),'endpoint_Ei_upper':str(right),
                   'initial_Ei_lower':str(RealBallField(bits)(QQ(1)/4).Ei()),
                   'initial_Ei_upper':str(RealBallField(bits)(QQ(1)/2).Ei())}


class Soldner(numberdb.Generator):
    table = 'T882'
    parameters = ()
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py',)

    def enumerate(self):
        yield {}

    def value(self, params, digits):
        if params != {}:
            raise ValueError('This constant has no parameters.')
        return enclose(digits)[0]


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        os.environ['NUMBERDB_API_KEY'] = sys.stdin.read().strip()
    generator = Soldner()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Reproduce the certified Ramanujan-Soldner enclosure.')))
    else:
        print(generator.verify(sample=None))
