"""Gelfond–Schneider constant, NumberDB table T909.

Dependencies: SageMath or passagemath with real Arb balls, and numberdb.
  sage -pip install numberdb          # install the Python client once
  sage -python generate.py             # read-only verification of every entry
  sage -python generate.py --publish   # fill the authorized target draft
The generator has no parameters and returns one bare positive real ball.
It computes exp(sqrt(2)*log(2)) using propagated rigorous Arb enclosures.
At 100 decimal digits it uses 512 bits (509 measured accuracy bits).
Larger requested precision uses numberdb.bits(digits, losing=160), with a
512-bit minimum; finite output and a 32-bit accuracy margin are required.
Credentials and upload attribution are supplied by the calling environment.
"""
import os
import sys
import numberdb.sage as numberdb
from sage.rings.real_arb import RealBallField


class GelfondSchneider(numberdb.Generator):
    table = os.environ.get('NUMBERDB_TABLE', 'T909')
    parameters = ()
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        yield {}

    def value(self, params, digits):
        if params:
            raise ValueError('This constant has no parameters.')
        field = RealBallField(max(512, numberdb.bits(digits, losing=160)))
        result = (field(2).sqrt() * field(2).log()).exp()
        if not result.is_finite() or result.accuracy() < numberdb.bits(digits, losing=32):
            raise ArithmeticError('The enclosure does not support the requested accuracy.')
        return result


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        key = sys.stdin.read().strip()
        if '=' in key and key.split('=', 1)[0].isupper():
            key = key.split('=', 1)[1].strip().strip('\'"')
        numberdb.configure(api_key=key)
    generator = GelfondSchneider()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE', 'Recompute the positive real constant with rigorous ball bounds')))
    else:
        report = generator.verify(sample=None)
        print(report)
        if not report.ok:
            raise SystemExit(1)
