"""Replay candidate-only evidence and validate source provenance and link retention."""
import json,hashlib
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from r90_evidence import features,evidence
R=Path(__file__).resolve().parents[1];O=R/'results/r90';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();d=json.loads((O/'results.json').read_text());assert d['protocol_sha256']==sha(O/'protocol.json') and d['l77_sha256']==sha(R/'results/l77/results.json') and len(d['records'])==36;l77={(r['source'],r['pair'],r['condition']):r for r in json.loads((R/'results/l77/results.json').read_text())['scenes'] if r['variant']=='clean'};sources={str((R/p).parent):{(r['pair'],r['condition']):r for r in json.loads((R/p).read_text())['records']} for p in ('results/r89/results.json','results/r89/opaque/results.json')}
for r in d['records']:
 l=l77[r['source'],r['pair'],r['condition']];original=sources[r['source']][r['pair'],r['condition']];base=Path(r['source']);p=base/r['archive'];assert sha(p)==r['archive_sha256'];z=np.load(p);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);lookup={str(k):v for k,v in zip(z['ids'],m)};images=[]
 for q in original['images']:assert sha(base/q['file'])==q['sha256'];images.append(np.asarray(Image.open(base/q['file']).convert('L')))
 energy=[cv2.Laplacian(a,cv2.CV_32F,ksize=3)**2 for a in images];fs={v['id']:features(lookup[v['id']],energy) for v in l['nodes']};assert fs==r['candidate_features'] and len(r['links'])==len(l['possible_edges'])
 for link,edge in zip(r['links'],l['possible_edges']):
  assert {k:link[k] for k in edge}==edge;ev=evidence(fs[edge['a']],fs[edge['b']]);assert all(link[k]==v for k,v in ev.items());a=l['candidate_labels'][edge['a']];b=l['candidate_labels'][edge['b']];cat='unassigned_or_ambiguous' if a['class']!='unique' or b['class']!='unique' else 'same_synthetic_source' if a['source']==b['source'] else 'different_synthetic_sources';assert link['diagnostic_reference_category']==cat
r=next(x for x in json.loads((R/'results/r89/results.json').read_text())['records'] if x['pair']==2 and x['condition']=='crossing_split');z=np.load(R/'results/r89'/r['archive']);en=[cv2.Laplacian(np.asarray(Image.open(R/'results/r89'/x['file']).convert('L')),cv2.CV_32F,ksize=3)**2 for x in r['images']]
for control in d['oracle_controls']:
 ids=control['constructed_source_ids'];masks=[z['refs'][0,ids[0]],z['refs'][1,ids[1]]];iou=int((masks[0]&masks[1]).sum())/int((masks[0]|masks[1]).sum());assert control['mask_iou']==iou and all(control[k]==v for k,v in evidence(features(masks[0],en),features(masks[1],en)).items())
print('Verified all 36 source archives, 108 input plane hashes, 630 retained links, candidate evidence and two constructed controls.')
