"""T901: Erdős–Borwein constant: reproducible rigorous enclosure.

Requires numberdb and SageMath or passagemath with Arb.
    sage -pip install numberdb
    sage -python generate.py             # verify every stored value, no write
    sage -python generate.py --publish   # fill the assigned private draft

There is no input: enumerate yields one empty mapping and value returns E.
The sum uses every n>=1. Exact powers and rational remainder decisions avoid
float conversion. For the N-term sum S_N, positivity and a geometric series
show 0 < E-S_N <= 2/(2^(N+1)-1): write each term as q^n/(1-q^n), q=1/2,
and bound its denominator below by 1-q^(N+1) for n>N.
Arb includes rounding; adding a ball containing [0,tail] includes truncation.
The tail target is 10^(-digits-20), and the working precision is
numberdb.bits(digits, losing=96). Actual precision and full independent exact
rational divisor-series checks are preserved in the attached evidence.
Source: W. Zudilin, arXiv:1601.02688v2, Section 1, equations (1) and (3).
The constant's name and base-two convention: MathWorld, Erdős–Borwein Constant,
equations (1) and (4). The remainder bound above is derived here.
Credentials and actual engine/model provenance belong in the caller's session.
"""
import argparse
import os
import sys
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


def enclosure(digits=100):
    field = RealBallField(numberdb.bits(digits, losing=96))
    target = QQ(1) / ZZ(10)**(digits+20)
    total = field(0)
    power = ZZ(1)
    n = 0
    while True:
        n += 1
        power *= 2
        total += field(1) / (power-1)
        tail = QQ(2) / (2*power-1)
        if tail <= target:
            break
    answer = total + field(0).union(field(tail))
    if not answer.is_finite() or not answer.lower() > 1:
        raise ArithmeticError('nonfinite or invalid enclosure')
    if answer.accuracy() < numberdb.bits(digits, losing=16):
        raise ArithmeticError('insufficient relative precision')
    return answer, {'terms': n, 'working_bits': int(field.prec()),
                    'relative_accuracy_bits': int(answer.accuracy()),
                    'tail_bound': str(tail), 'native_type': type(answer).__name__}


class ErdosBorweinConstant(numberdb.Generator):
    table = 'T901'
    parameters = ()
    type = 'R'
    digits = 100
    rigour = 'proven'
    files = ('generate.py', 'check_values.py', 'argument-selection.md',
             'numerical-evidence.json', 'skill-manifest.json', 'research.md')

    def enumerate(self):
        yield {}

    def value(self, params, digits):
        if params:
            raise ValueError('the constant has no parameters')
        return enclosure(digits)[0]


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish', action='store_true')
    options = parser.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    generator = ErdosBorweinConstant()
    if options.publish:
        print(generator.publish(overwrite=False))
    else:
        report = generator.verify(sample=None)
        print(report)
        if not report.ok:
            raise SystemExit(1)

if __name__ == '__main__':
    main()
