"""Replay frozen triage on pre-existing duplicate and missing-plane variants."""
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();data=json.loads((R/'results/l77/results.json').read_text());rows=[r for r in data['scenes'] if r['variant']!='clean'];sources={str((R/p).parent):{(x['pair'],x['condition']):x for x in json.loads((R/p).read_text())['records']} for p in ['results/r89/results.json','results/r89/opaque/results.json']};out=[]
for row in rows:
 base=Path(row['source']);r=sources[str(base)][row['pair'],row['condition']];path=base/row['archive'];assert sha(path)==row['archive_sha256'];z=np.load(path);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)};energy=[]
 for x in r['images']:
  assert sha(base/x['file'])==x['sha256'];im=np.asarray(Image.open(base/x['file']).convert('L'));energy.append(cv2.Laplacian(im,cv2.CV_32F,ksize=3)**2)
 fs={v['id']:features(lookup[v['id'][5:] if v['id'].startswith('copy:') else v['id']],energy) for v in row['nodes']};links=[]
 for e in row['possible_edges']:
  a=row['candidate_labels'][e['a']];b=row['candidate_labels'][e['b']];category='unassigned_or_ambiguous' if a['class']!='unique' or b['class']!='unique' else 'same_synthetic_source' if a['source']==b['source'] else 'different_synthetic_sources';links.append({**e,**evidence(fs[e['a']],fs[e['b']]),'diagnostic_reference_category':category})
 out.append({'source':row['source'],'pair':row['pair'],'condition':row['condition'],'variant':row['variant'],'split':row['split'],'candidate_features':fs,'links':links})
(O/'variant-results.json').write_text(json.dumps({'format':'r90-variants-v1','protocol_sha256':sha(O/'variant-protocol.json'),'base_protocol_sha256':sha(O/'protocol.json'),'l77_sha256':sha(R/'results/l77/results.json'),'records':out},indent=2)+'\n');print('Processed',len(out),'variants,',sum(len(x['links']) for x in out),'links; retained all links.')
