"""Offline reproducible checks for T908-F1.

Run: python3 repair-check.py DIRECTORY
DIRECTORY contains before/after-repair documents and snapshots, original
attachments, corrected argument-selection.md, LIReC.py and repair-verify.log.
The numerical bounds are retained checkpoints; repair-verify.log must also
contain the executed fresh full verification and rational-series check.
This is repair evidence, never an independent scientific verdict.
"""
import copy
from fractions import Fraction
import hashlib
import json
from pathlib import Path
import sys


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def run(directory):
    directory = Path(directory)
    load = lambda name: json.loads((directory / name).read_text())
    before, after = load('before-document.json'), load('after-repair-document.json')
    before_snapshot, after_snapshot = load('before-snapshot.json'), load('after-repair-snapshot.json')
    expected = copy.deepcopy(before)
    old_url = expected['Links']['LIReC']['url']
    assert old_url.endswith('#L555-L568')
    expected['Links']['LIReC']['url'] = old_url.replace('#L555-L568', '#L567-L581')
    assert after == expected, 'Unexpected document change'
    old_argument = (directory / 'original-attachments/argument-selection.md').read_bytes()
    new_argument = (directory / 'argument-selection.md').read_bytes()
    assert old_argument.count('calculator.py lines 555–560'.encode()) == 1
    assert new_argument == old_argument.replace('calculator.py lines 555–560'.encode(),
                                               'calculator.py lines 568–573'.encode())
    files = dict(before_snapshot['files'])
    files['argument-selection.md'] = hashlib.sha256(new_argument).hexdigest()
    assert after_snapshot['files'] == files
    for name, checksum in before_snapshot['files'].items():
        assert sha(directory / 'original-attachments' / name) == checksum
    source_hash = sha(directory / 'LIReC.py')
    assert source_hash == '1c32bf0908ab159b3daef4b760255d1fd61e0e497700061cc226c32c6b9b2e4e'
    lines = (directory / 'LIReC.py').read_text().splitlines()
    required = {555: 'cahen constant', 568: 'def epi()', 570: 'gelfond constant',
                573: 'return mp.exp(mp.pi)', 576: 'def G_S()',
                578: 'gelfond schneider constant', 581: 'return mp.power(2, mp.sqrt(2))'}
    for line, snippet in required.items():
        assert snippet in lines[line - 1], (line, snippet)
    assert after['Parameters'] == {} and len(after['Numbers']) == 1
    assert after['Numbers'] == before['Numbers']
    stored = after['Numbers'][0]
    fractional_places = len(stored.split('.')[1])
    radius, center = Fraction(1, 10 ** fractional_places), Fraction(stored)
    checkpoint = load('original-attachments/check-results.json')
    production = load('original-attachments/numerical-evidence.json')
    assert checkpoint['stored'] == production['stored_decimal'] == stored
    lower, upper = Fraction(checkpoint['lower']), Fraction(checkpoint['upper'])
    assert center - radius <= lower < upper <= center + radius
    assert Fraction(production['ball_lower']) <= lower < upper <= Fraction(production['ball_upper'])
    assert upper - lower == Fraction(checkpoint['width']) < Fraction(1, 10 ** 172)
    verification_lines = (directory / 'repair-verify.log').read_text().splitlines()
    results = [json.loads(line.removeprefix('RESULT_JSON='))
               for line in verification_lines if line.startswith('RESULT_JSON=')]
    assert len(results) == 1
    fresh = results[0]
    assert fresh['stored_decimal'] == stored
    assert fresh['generator_verify'] == {'checked': 1, 'matched': 1, 'ok': True}
    assert fresh['failures'] == []
    assert fresh['known_answer_control'] is True and fresh['negative_control_rejected'] is True
    assert fresh['independent_check'] == checkpoint, 'Saved mathematics no longer reproduces'
    audit = load('after-repair-audit.json')
    assert audit['clean'] is True and audit['findings'] == []
    skill = load('repair-skill-verification.json')
    assert skill['all_resources_verified'] is True
    result = {
        'table': 'T908', 'finding': 'T908-F1', 'disposition': 'done',
        'changes': ['Links.LIReC.url: #L555-L568 -> #L567-L581',
                    'argument-selection.md: 555–560 -> 568–573'],
        'exact_document_change_only': True, 'exact_attachment_change_only': True,
        'source_sha256': source_hash, 'source_line_assertions': required,
        'stored_values_retained': True, 'generator_sources_unchanged': True,
        'selection_and_definitions_unchanged': True,
        'audit_clean': True, 'fresh_verify': fresh,
        'saved_checkpoint_reproduced_exactly': True,
        'skill_manifest': skill['manifest'], 'skill_manifest_sha256': skill['manifest_sha256'],
        'skill_bundle_sha256': skill['versions'][0][2],
        'fresh_independent_critique_required': True,
        'reason': 'Links changes the selection fingerprint; repair evidence is not a verdict.',
        'before_revision': before_snapshot['revision'], 'after_revision': after_snapshot['revision'],
        'failures': []}
    (directory / 'repair-results.json').write_text(json.dumps(result, indent=2) + '\n')
    print(json.dumps({name: result[name] for name in
                     ('table', 'finding', 'disposition', 'audit_clean', 'saved_checkpoint_reproduced_exactly',
                      'fresh_independent_critique_required', 'failures')}, indent=2))


if __name__ == '__main__':
    run(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parent)
