from pathlib import Path
import hashlib
import json
import subprocess

root = Path(__file__).resolve().parent
baseline = json.loads((root/'issues-baseline.json').read_text())
coverage = json.loads((root/'coverage.json').read_text())
expected = {item['id'] for item in baseline['formal']}
covered = {item['id'] for item in coverage['items'] if item.get('kind') == 'formal'}
errors = []
if expected != covered:
    errors.append({'missing': sorted(expected-covered), 'unexpected': sorted(covered-expected)})
for item in coverage['items']:
    for location in item.get('locations', []):
        path = root/location['path']
        if not path.is_file():
            errors.append({'item':item['id'], 'missing_file':location['path']})
            continue
        lines = path.read_text(encoding='utf-8').splitlines()
        number = location.get('line',1)
        if not 1 <= number <= len(lines):
            errors.append({'item':item['id'], 'invalid_line':number})
for name in ['README.md','DESIGN.md','PLAN.md','FIX-LOGIC.md',
             'VERIFICATION.md','IMPLEMENTATION-REPORT.md','fix.patch']:
    if not (root/name).is_file():
        errors.append({'missing_deliverable':name})
check = json.loads((root/'patch-check.json').read_text())
patch_hash = hashlib.sha256((root/'fix.patch').read_bytes()).hexdigest()
if check['apply_check_exit'] or check['patch_sha256'] != patch_hash:
    errors.append({'patch_check':'not current or failed'})
result = {'formal_items':len(expected), 'coverage_items':len(coverage['items']),
          'patch_sha256':patch_hash, 'errors':errors,
          'boundary':'Coverage, paths and applicability only; no project/runtime acceptance.'}
(root/'delivery-check.json').write_text(json.dumps(result,ensure_ascii=False,indent=2))
print(json.dumps(result,ensure_ascii=False))
raise SystemExit(1 if errors else 0)
