"""Check T697's unchanged mpmath snippet before repairing its Programs structure.
Run with SageMath: sage -python check_program.py
Keep document.json and skill-manifest.json alongside this file.
This validation uses fixed-precision agreement, not certified quadrature.
"""
import hashlib
import json
from pathlib import Path
from decimal import Decimal
import platform
import mpmath as mp
import numberdb.sage as numberdb
from sage.version import version as sage_version

root=Path(__file__).resolve().parent
document=json.loads((root/'document.json').read_text())
program=document['Programs']['mpmath']
if isinstance(program,dict):
    program=program['code']
namespace={}
exec(compile(program,'T697 Programs.mpmath','exec'),namespace)
compute=namespace['log_sine']

def number(n,k,t):
    entry=document['Numbers'][str(n)][str(k)][t]
    return str(entry['number'] if isinstance(entry,dict) else entry)

checks=[]
mp.mp.dps=210
# Nonzero elementary controls detect missing factors or the leading minus sign.
for n,k,t in [(3,2,'1/3'),(4,3,'1')]:
    value=compute(n,k,t,180)
    expected=-(mp.pi*mp.mpf(t))**n/n
    error=abs(value-expected)/max(1,abs(expected))
    assert error<mp.mpf('1e-175')
    checks.append({'control':[n,k,t],'relative_error':mp.nstr(error,12)})
for n,k,t,formula in [(2,0,'1/2',mp.catalan), (3,0,'1',-mp.pi**3/12), (4,0,'1',3*mp.pi*mp.zeta(3)/2), (4,0,'5/6',None)]:
    stored=number(n,k,t)
    ulp=mp.mpf(10)**Decimal(stored).as_tuple().exponent
    low=compute(n,k,t,130)
    high=compute(n,k,t,180)
    distance=abs(high-mp.mpf(stored))/ulp
    agreement=abs(high-low)/max(1,abs(high))
    assert mp.isfinite(high) and distance<1 and agreement<mp.mpf('1e-120')
    # The same comparison must reject a deliberate ten-last-place error.
    assert abs(high-(mp.mpf(stored)+10*ulp))/ulp>1
    result={'params':{'n':n,'k':k,'t':t},'stored':stored,'distance_in_last_places':mp.nstr(distance,20),'relative_precision_agreement':mp.nstr(agreement,12)}
    if formula is not None:
        discrepancy=abs(high-formula)/max(1,abs(formula))
        assert discrepancy<mp.mpf('1e-170')
        result['closed_form_relative_error']=mp.nstr(discrepancy,12)
    checks.append(result)
zero=compute(2,0,'1',180)
assert number(2,0,'1')=='0' and abs(zero)<mp.mpf('1e-175')
checks.append({'params':{'n':2,'k':0,'t':'1'},'exact_stored_zero':True,'quadrature_residual':mp.nstr(zero,12),'limitation':'The residual checks the snippet; it does not establish exactness.'})
manifest_bytes=(root/'skill-manifest.json').read_bytes()
print(json.dumps({'table':'T697','skill_manifest':'agents/runs/20261109T222649Z-repair-skills/manifest.json','skill_manifest_sha256':hashlib.sha256(manifest_bytes).hexdigest(),'skill_versions':json.loads(manifest_bytes)['versions'],'versions':{'python':platform.python_version(),'Sage':sage_version,'mpmath':mp.__version__},'program_code_sha256':hashlib.sha256(program.encode()).hexdigest(),'checks':checks,'new_values':False,'limitations':'This checks the unchanged snippet and selected existing values. No all-row recertification was required for the Programs structure repair.'},indent=2))
