"""Recheck unchanged Estrada-index precision for the T545 caption repair.

Download this file, generate.py, checks.py and check.py from T545. Run:
    sage -python repair_check.py
A private draft requires NUMBERDB_API_KEY. Alternatively pass an API document:
    sage -python repair_check.py document.json
No writes occur. This reuses the builder's two algorithms, not a new critique.
"""
import hashlib
import json
from pathlib import Path
import sys
import numberdb.sage as numberdb
from sage.env import SAGE_VERSION
from checks import (B, RIF, walk_interval, tight_overlap, contains_written,
                    number_of)
from generate import EstradaIndices, estrada

if len(sys.argv)>1:
    document=json.loads(Path(sys.argv[1]).read_text())
elif Path(__file__).with_name('document-before.json').exists():
    document=json.loads(Path(__file__).with_name('document-before.json').read_text())
else:
    document=numberdb.table('T545')
controls=[]
for key,expected in [('A_',B(1).exp()+B(-1).exp()),
                     ('Bw',B(2).exp()+2*B(-1).exp()),('B?',B(3))]:
    lo,hi,terms=walk_interval(key)
    tight_overlap(RIF(lo,hi),expected)
    assert not RIF(lo,hi).overlaps(RIF(expected+1))
    controls.append({'g':key,'passed':True})
keys=[p['g'] for p in EstradaIndices().enumerate()]
assert list(document['Numbers'])==keys
rows=[]
for key in keys:
    text=number_of(document['Numbers'][key])
    lo,hi,terms=walk_interval(key)
    value=estrada(key,100)
    tight_overlap(value,RIF(lo,hi))
    contains_written(text,lo,hi)
    spectral=RIF(value)
    contains_written(text,spectral.lower().exact_rational(),spectral.upper().exact_rational())
    rows.append({'g':key,'number':text,'walk_lower':str(lo),'walk_upper':str(hi),
                 'walk_terms':terms,'spectral_accuracy_bits':int(value.accuracy()),
                 'both_enclosures_within_written_interval':True})
skill='e37efb7e2ededf6c1d7134c673f152f648f26e0267c556aebdf3ec65765d8b4c'
print(json.dumps({'table':'T545','rows_checked':len(rows),'controls':controls,
 'sage':SAGE_VERSION,'python':sys.version,'numberdb':numberdb.__version__,
 'scope':'Reused builder exact rational closed-walk and algebraic-spectrum Arb algorithms; no numerical changes or new critique verdict.',
 'skill_manifest':'agents/runs/20261027T110139Z-repair-skills/manifest.json',
 'skill_manifest_sha256':'468f5191d13df1eaecac71d659cc26682a40378c5982ce84143ed004d1933cc7',
 'skill_sha256':{'local':skill,'live':skill},
 'source_sha256':{name:hashlib.sha256(Path(__file__).with_name(name).read_bytes()).hexdigest() for name in ('generate.py','checks.py','check.py')},
 'min_spectral_accuracy_bits':min(r['spectral_accuracy_bits'] for r in rows),
 'max_walk_terms':max(r['walk_terms'] for r in rows),'entries':rows},indent=2))
