"""Run the exact before/after Programs examples and check the affected example.

Save before-document.json, proposed-document.json, repair-checkpoint.json,
checks.py and this file together. Run with SageMath 10.9 and numberdb 0.1.10:
    sage -python repair_program_check.py
No website writes, credentials, or full-table numerical rebuild is required.
The checkpoint is attributed saved independent evidence, not a new verdict.
"""
import contextlib
import hashlib
import io
import json
from fractions import Fraction
from pathlib import Path

import numberdb.sage as numberdb
import numberdb as numberdb_package
from sage.rings.rational_field import QQ
from sage.rings.real_mpfr import RealField
from sage.rings.real_mpfi import RealIntervalField
from sage.schemes.elliptic_curves.constructor import EllipticCurve
from sage.env import SAGE_VERSION
import checks

work = Path(__file__).parent
before = json.loads((work / 'before-document.json').read_text())
after = json.loads((work / 'proposed-document.json').read_text())
checkpoint = json.loads((work / 'repair-checkpoint.json').read_text())
outputs = {}
values = {}
for label, document in [('before', before), ('after', after)]:
    namespace = {}
    output = io.StringIO()
    with contextlib.redirect_stdout(output):
        exec(compile(document['Programs']['sage-pairing']['code'], label, 'exec'), namespace)
    outputs[label] = output.getvalue().strip()
    values[label] = namespace['B']

field = RealField(1100)
interval = RealIntervalField(1100)
row = checkpoint['row']
def rational(text):
    value = Fraction(text)
    return QQ(value.numerator) / QQ(value.denominator)

stored = rational(row['stored'])
assert len(row['stored'].split('.')[1]) == 101
ulp = QQ(1) / QQ(10)**101
stored_interval = interval(stored - ulp, stored + ulp)
independent = interval(rational(row['independent']['lower']), rational(row['independent']['upper']))
assert independent.lower() > stored_interval.lower()
assert independent.upper() < stored_interval.upper()
assert independent.absolute_diameter() < field('1e-130')
fixed = values['after']
assert fixed.lower() > independent.lower() and fixed.upper() < independent.upper()
old = values['before']
assert old.lower() > stored_interval.upper() or old.upper() < stored_interval.lower()

curve = EllipticCurve(QQ, [0, 1, 1, -2, 0])
p, q = curve([0, 0]), curve([1, 0])
raw = []
for working in (200, 300):
    bits = numberdb.bits(working)
    value = curve.pari_curve().ellheight(p, q, precision=bits)
    converted = RealField(bits)(value)
    raw.append({'decimal_working': working, 'bits': bits, 'raw_str': str(value),
                'realfield_str': str(converted),
                'converted_error_stored_ulp': str(abs(field(converted)-field(stored))/field(ulp))})
assert raw[0]['raw_str'] == raw[1]['raw_str']
assert raw[0]['raw_str'] == '0.0585226748448790'
local = (checks.local_height(p+q, 1013)-checks.local_height(p, 1013)
         -checks.local_height(q, 1013))/2
assert abs(field(local)-field(fixed.center())) < field('1e-195')
assert local in stored_interval
assert -local not in stored_interval and local/2 not in stored_interval
control_curve = EllipticCurve(QQ, [0, 0, 1, -1, 0])
control = checks.local_height(control_curve([0, 0]), 1013)
assert abs(field(control)-field('0.0511114082399688402358860997569420216')) < field('1e-36')
assert checks.local_height(control_curve(0), 1013) == 0
assert not checks.close(field('NaN'), field(1))
result = {
    'table': 'T773', 'scope': 'Displayed sage-pairing example only; no stored entries changed',
    'versions': {'sage': SAGE_VERSION, 'numberdb': numberdb_package.__version__},
    'skill_manifest_sha256': checkpoint['skill_manifest_sha256'],
    'working': raw, 'example_outputs': outputs,
    'original_error_stored_ulp': str(abs(field(raw[0]['raw_str'])-field(stored))/field(ulp)),
    'fixed_inside_stored_interval': True, 'fixed_inside_saved_independent_enclosure': True,
    'saved_independent_enclosure_inside_stored_interval': True,
    'local_height_pairing': str(local),
    'local_height_difference_from_fixed': str(abs(field(local)-field(fixed.center()))),
    'known_answer_control': True, 'negative_control_rejected': True,
    'negative_controls': ['original short-string result', 'reversed sign', 'half normalization', 'NaN'],
    'failures': [],
    'limitations': 'Agreement remains heuristic. Saved 220-step MPFI enclosure is reused only for unchanged exact curve/point inputs, with its original attribution.',
    'input_hashes': {name: hashlib.sha256((work/name).read_bytes()).hexdigest()
                     for name in ['repair_program_check.py', 'before-document.json',
                                  'proposed-document.json', 'repair-checkpoint.json', 'checks.py']},
}
print('REPAIR_RESULT '+json.dumps(result), flush=True)
