"""Reproduce Liouville reals in integer bases (T891).

Requires SageMath (or passagemath with MPFI) and the numberdb Python package:
    sage -pip install numberdb
    sage -python generate.py             # compute locally, write nothing
    sage -python generate.py --verify    # compare all stored entries
    sage -python generate.py --publish   # fill the authorized target draft

The parameter b is an integer construction base >= 2. The default selection is
all b=2,...,16, in increasing order. L_b=sum(n>=1, b^(-n!)); position 1 occurs
once. Values are NOT finite rational prefixes. Exact QQ sums and a geometric
majorant enclose the entire infinite tail. MPFI converts both rational endpoints
outward at max(512, numberdb.bits(digits, losing=96)) bits. The exact cutoff is
chosen so the tail is below 10^(-digits-15), including relative guard for these
values. The nonzero interval is serialized with the requested significant
digits; its containment is separately checked. See OEIS A012245 (definition
and arbitrary-base comment) and A092874 (binary example). No source data or
session credentials are needed by the calculation. Attribution is supplied by
the caller's environment on authorized uploads.
"""

import argparse
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_mpfi import RealIntervalField


class LiouvilleReals(numberdb.Generator):
    table = 'T891'
    parameters = ('b',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, limit=16):
        if isinstance(limit, bool) or int(limit) != limit or limit < 2:
            raise ValueError('limit must be an integer at least 2')
        for b in range(2, int(limit) + 1):
            yield {'b': b}

    @staticmethod
    def certificate(b, digits):
        b = ZZ(b)
        if b < 2:
            raise ValueError('the construction base must be an integer >=2')
        n = ZZ(1)
        exponent = ZZ(1)
        partial = QQ(1) / b
        while True:
            next_exponent = exponent * (n + 1)
            # Sum of all integer-position terms from (n+1)! onward.
            tail = QQ(1) / ((b - 1) * b**(next_exponent - 1))
            if tail < QQ(1) / ZZ(10)**(digits + 15):
                return {'n': n, 'exponent': exponent, 'partial': partial,
                        'next_exponent': next_exponent, 'tail': tail}
            n += 1
            exponent = next_exponent
            partial += QQ(1) / b**exponent

    def value(self, params, digits):
        raw = params['b']
        b = ZZ(raw)
        if isinstance(raw, (float, bool)) or str(b) != str(raw).strip():
            raise ValueError('b must be an exact integer identity')
        c = self.certificate(b, digits)
        field = RealIntervalField(max(512, numberdb.bits(digits, losing=96)))
        result = field(c['partial'], c['partial'] + c['tail'])
        if result.is_NaN() or result.lower() >= result.upper():
            raise ArithmeticError('a finite, nonzero-width enclosure is required')
        return result


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    action = parser.add_mutually_exclusive_group()
    action.add_argument('--publish', action='store_true')
    action.add_argument('--verify', action='store_true')
    options = parser.parse_args()
    generator = LiouvilleReals()
    if options.publish:
        print(generator.publish())
    elif options.verify:
        report = generator.verify(sample=None)
        print(report)
        if not report.ok:
            raise SystemExit(1)
    else:
        from numberdb._write import to_text
        for params in generator.enumerate():
            print(params['b'], to_text(generator.value(params, generator.digits), generator.digits))
