"""T806: Hausdorff dimensions of finite-alphabet continued-fraction Cantor sets.

Dependencies: SageMath (runtime version recorded in numerical-evidence.json, Python 3.12.3), numberdb (tested 0.1.10).
    sage -pip install numberdb
    sage -python generate.py                 # replay whole-domain certificates
    sage -python generate.py --verify        # also compare every stored entry
    sage -python generate.py --publish       # explicit authorized draft filling
Download generate.py, compute.py and certificates.json to the same directory.
The cached exact rational brackets were certified by positive-polynomial tests,
not by the collocation residual. Candidate construction uses 160 Chebyshev nodes
and 700-bit MPFR; primary certificates use 1400-bit Arb with 8 or 16 closed subintervals and
180 or 200 Taylor terms; default replay uses the separate 1600-bit verifier and a Cauchy bound on the full analytic remainder. The 100-digit
serialized interval must contain the entire bracket. No precision is inferred
from spectral residuals or agreement. check_certificates.py is a separate
reverse-polynomial verifier. See certification.md for the proof and controls.

For an additional alphabet, use compute.candidate(alphabet, approximate_guess)
and compute.certify(certificate); failure supplies no bound. Save the emitted
exact witness and bracket before extending this fixed finite selection.
No credentials or session attribution are embedded in these reusable files.
"""
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
import argparse,json,os,sys
from pathlib import Path

ALPHABETS=[tuple(range(1,a+1)) for a in range(2,11)]+[(2,4,6,8,10),(1,4,9),(2,3,6,9)]
HERE=Path(__file__).resolve().parent

def records():
    data=json.loads((HERE/'certificates.json').read_text())
    return data['certificates'] if isinstance(data,dict) else data

class Dimensions(numberdb.Generator):
    table='T806'
    parameters=('alphabet',)
    type='R'
    digits=100
    rigour='proven'
    files=('generate.py','compute.py','compute-v1.py','certificates.json','check_certificates.py','check_half.py','offline_checks.py','dry_run.py','check.py','certification.md','argument-selection.md','numerical-evidence.json','source-comparisons.json','skill-manifest.json')
    def enumerate(self):
        for alphabet in ALPHABETS:yield {'alphabet':'-'.join(map(str,alphabet))}
    def value(self,params,digits):
        if digits>100:raise ValueError('Archived certificates support the declared 100-digit output only')
        alphabet=tuple(int(v) for v in str(params['alphabet']).split('-'))
        if alphabet not in ALPHABETS:raise ValueError('Not a member of the fixed certified selection')
        cert=next(c for c in records() if tuple(c['alphabet'])==alphabet)
        lo=QQ(cert['lo']);hi=QQ(cert['hi'])
        assert 0<lo<hi<1 and hi-lo==QQ(3)/10**104
        field=RealBallField(500)
        enclosure=field(lo).union(field(hi))
        assert enclosure.is_finite() and enclosure.rad()>0
        return {'number':enclosure,'param-latex':'$\\{'+','.join(map(str,alphabet))+'\\}$'}

def replay():
    from check_certificates import check_one
    certs=records()
    assert [tuple(c['alphabet']) for c in certs]==ALPHABETS
    for c in certs:
        check_one(c)
        print('Certificate replay passed',c['alphabet'],flush=True)

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--verify',action='store_true');p.add_argument('--publish',action='store_true');p.add_argument('--skip-replay',action='store_true',help='Use only after this exact artifact set was replayed and independently checked in this run')
    args=p.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':numberdb.configure(api_key=sys.stdin.read().strip())
    if not args.skip_replay:replay()
    g=Dimensions()
    if args.publish or os.environ.get('NUMBERDB_PUBLISH')=='1':print(g.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill certified finite-alphabet dimension draft'),removing=False))
    elif args.verify:print(g.verify(sample=None))
    else:
        for params in g.enumerate():print(params,g.value(params,100))
