"""Generator for T897: Komornik-Loreti bases.

Requires SageMath (or passagemath with Arb/MPFI) and numberdb.
    sage -pip install numberdb
    sage -python generate.py             # read-only complete verification
    sage -python generate.py --publish   # fill an authorized existing draft

M is the greatest allowed digit, not the number of digits. The sequence starts
at n=1; t_n is binary bit-sum parity. Baker--Zou (2023), section 2, (3)-(4),
identifies the least univoque base with the monotone digit-sum root.
Horner evaluation uses Arb balls, exact rational bisection endpoints, and the
nonnegative tail bound M*q**(-N)/(q-1). Both endpoint signs are certified.
At 100 requested digits the working precision is 512 bits; the omitted tail
is bounded by 10**(-135) and the root width by 10**(-112).
No decimal starting value or external numerical data is used.
"""
import argparse
import os
import sys
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.real_mpfi import RealIntervalField

def digit_sequence(M, N):
    t = [n.bit_count() % 2 for n in range(N+1)]
    k = M // 2
    return [k+t[n] if M % 2 else k+t[n]-t[n-1] for n in range(1,N+1)]

@lru_cache(maxsize=None)
def certified_root(M, digits=100):
    M=int(M); digits=int(digits)
    if M < 1: raise ValueError('M must be positive')
    bits=max(512, numberdb.bits(digits,losing=160))
    R=RealBallField(bits); I=RealIntervalField(bits)
    k=M//2
    lo=QQ(3)/2 if M==1 else QQ(k+1)
    hi=QQ(k+2)
    N=32
    tail_goal=QQ(1)/10**(digits+35)
    while not R(M)*R(lo)**(-N)/(R(lo)-1) < R(tail_goal): N*=2
    ds=digit_sequence(M,N)
    assert all(0<=d<=M and isinstance(d,int) for d in ds) and ds[0]>0
    def bounds(q):
        z=1/R(q); s=R(0)
        for d in reversed(ds): s=(s+d)*z
        tail=R(M)*z**N/(R(q)-1)
        return s, s+tail
    assert bounds(lo)[0] > 1 and bounds(hi)[1] < 1
    iterations=0
    while hi-lo > QQ(1)/10**(digits+12):
        mid=(lo+hi)/2
        lower,upper=bounds(mid)
        if lower>1: lo=mid
        elif upper<1: hi=mid
        else: raise ArithmeticError('Insufficient sign precision: increase precision and tail guard')
        iterations+=1
    lower=bounds(lo)[0]-1; upper=bounds(hi)[1]-1
    assert lower>0 and upper<0
    return I(lo,hi), {'M':M,'N':N,'bits':bits,'iterations':iterations,
          'lo':str(lo),'hi':str(hi),'width':str(hi-lo),
          'left_residual':str(lower),'right_residual':str(upper),
          'uniform_tail_bound':str(R(M)*R(lo)**(-N)/(R(lo)-1))}

class KomornikLoreti(numberdb.Generator):
    table=os.environ.get('NUMBERDB_TABLE','T897')
    parameters=('M',)
    type='R'
    digits=100
    rigour='proven'
    def enumerate(self,limit=32):
        for M in range(1,limit+1): yield {'M':M}
    def value(self,params,digits):
        return certified_root(int(params['M']),digits)[0]

if __name__=='__main__':
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--publish',action='store_true')
    args=p.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g=KomornikLoreti()
    if args.publish or os.environ.get('NUMBERDB_PUBLISH')=='1':
        print(g.publish())
    else: print(g.verify(sample=None))
