"""Reproduce the Erdős–Tenenbaum–Ford constant for NumberDB T878.

Requires SageMath (or passagemath with real Arb) and numberdb.
    sage -pip install numberdb
    sage -python generate.py                 # compute locally; no writes
    sage -python generate.py --verify        # check every stored entry
    sage -python generate.py --publish       # fill the authorized draft only

The single entry has no parameters. Natural real logarithms are evaluated
with Arb balls; the nested logarithm and division propagate their input
uncertainty. At 100 decimal digits use 512 working bits, which leaves over
150 decimal digits in the computed enclosure despite cancellation.
The returned ball, rather than a fixed-precision approximation, supports
proven rigour. independent_check.py uses exact rational bounded series.
Credentials and session provenance belong in the caller's environment.
"""
import argparse
import os
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.rings.real_arb import RealBallField


class ETFConstant(numberdb.Generator):
    table = 'T878'
    parameters = ()
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        yield {}

    def value(self, params, digits):
        if params:
            raise ValueError('This constant has no free parameters.')
        field = RealBallField(max(512, numberdb.bits(digits, losing=160)))
        log_two = field(2).log()
        result = field(1) - (field(1) + log_two.log()) / log_two
        if not result.is_finite() or result.rad() <= 0:
            raise ArithmeticError('Expected a finite, nonzero-width Arb ball.')
        if result.accuracy() < numberdb.bits(digits, losing=10):
            raise ArithmeticError('Insufficient relative accuracy.')
        return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    actions = parser.add_mutually_exclusive_group()
    actions.add_argument('--publish', action='store_true')
    actions.add_argument('--verify', action='store_true')
    opts = parser.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        import sys
        os.environ['NUMBERDB_API_KEY'] = sys.stdin.read().strip()
    gen = ETFConstant()
    if opts.publish or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(gen.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE', ''), removing=False))
    elif opts.verify:
        print(gen.verify(sample=None))
    else:
        print(to_text(gen.value({}, gen.digits), gen.digits))
