import hashlib
import json
from pathlib import Path

root = Path('/out/download')
source = Path('/out/source')

def read(name):
    return json.loads((root / name).read_text())

cache = read('cache_validation.json')
suite = read('contract_suite.json')
baseline = read('baseline_failures.json')
target = read('r5_tests.json')
normalize = lambda name: name.split('/')[-1]
assert cache['status'] == 'PASS' and not cache['errors']
assert len(cache['clips']) == 32 and cache['displayed'] == 18045
assert all(x['status'] == 'PASS' and not x['errors'] for x in cache['clips'].values())
assert suite['collected'] == 204 and len(suite['failed']) == 5 and not suite['errors']
assert sorted(map(normalize, suite['failed'])) == sorted(map(normalize, baseline['failures']))
assert not baseline['errors']
assert target == dict(passed=True, tests=18, failures=0, errors=0)
paths = [*sorted((source / 'app/fight_r5').glob('*.py'))]
paths += [source / p for p in ('app/fight_runtime.py', 'app/scenario_parameters.py',
    'app/secure_control.py', 'app/stream_settings.py', 'tests/test_fight_r5.py')]
fingerprints = {str(p.relative_to(source)): hashlib.sha256(p.read_bytes()).hexdigest() for p in paths}
(root / 'source_fingerprints.json').write_text(json.dumps(fingerprints, indent=2) + '\n')
summary = dict(
    status='R5_REQUIRED_PASS_EXISTING_CONTRACT_FAILURES',
    operating_deployment=False, r5_target_tests=target,
    cache_inputs=32, displayed_observations=18045,
    full_r5_trace_inputs=sum(x['full_r5_trace'] for x in cache['clips'].values()),
    normalized_runtime_predicate_and_event_match=True,
    existing_native_bbox_clamp_entries=sum(len(x['canonical_bbox_clips']) for x in cache['clips'].values()),
    source_fingerprint_file='source_fingerprints.json',
    contract_suite=dict(collected=suite['collected'], passed_tests=suite['collected']-len(suite['failed']),
        passing_subtests=27, existing_failures=suite['failed'], new_failures=[]),
    rule_p95_ms_range=[min(x['p95_ms'] for x in cache['clips'].values()),max(x['p95_ms'] for x in cache['clips'].values())],
    verification_elapsed_seconds=sum(x['elapsed'] for x in cache['clips'].values()),
    maxrss_kib=cache['maxrss_kib'],
    limits=['Cached CPU verification is not live throughput or accuracy acceptance.',
        'Actual Web consumer rendering and real Event/media delivery remain untested.',
        'The five unchanged-HEAD contract-test failures remain outside this change.'])
(root / 'final_validation.json').write_text(json.dumps(summary, indent=2) + '\n')
files = sorted(p for p in root.rglob('*') if p.is_file() and p.name != 'SHA256SUMS')
(root / 'SHA256SUMS').write_text(''.join(f'{hashlib.sha256(p.read_bytes()).hexdigest()}  {p.relative_to(root)}\n' for p in files))
print(json.dumps(dict(status=summary['status'], files=len(files), inputs=32, observations=18045)))
