"""Repair checks for the Landau–Kolmogorov draft, numberdb.org/T500.

Download generate.py, checks.py, check.py and euler-controls.json from the
same table and place them beside this file. With Sage and numberdb installed:

    sage -python repair_checks.py

A private draft needs NUMBERDB_API_KEY. For a piped key set
NUMBERDB_KEY_FROM_STDIN=1. This script reads the live table and sends no edits.
It reruns the attached generator and exact Euler-spline checks, executes the
live Programs snippet, and checks all its values against exact rational powers.
"""
import json
import contextlib
import io
import numberdb.sage as numberdb
from sage.rings.real_arb import RealBallField
from generate import LandauKolmogorov, MAX_N
from checks import run, spline_data, rational_power

result = run(stored=True)
document = numberdb.table('T500')
namespace = {}
with contextlib.redirect_stdout(io.StringIO()) as captured:
    exec(document['Programs']['sage']['code'], namespace)
_, norms = spline_data(MAX_N)
R = RealBallField(512)
count = 0
for params in LandauKolmogorov().enumerate():
    n, k = params['n'], params['k']
    value = namespace['C'](n, k)
    assert value.is_finite() and R(value.rad()) < R(10)**(-110)
    assert (value**n-rational_power(norms, n, k)).contains_zero()
    count += 1
result['live_program_checks'] = count
result['live_program_example_output'] = captured.getvalue().strip()
print(json.dumps(result, indent=2, default=str))
