"""Measure reversible orientation/focus evidence for possible cross-plane links."""
import json,hashlib,math,collections
from pathlib import Path
import cv2,numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r90';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def features(mask,energy):
 y,x=np.nonzero(mask);angle=None;ratio=None
 if len(x)>=20:
  cov=np.cov(np.stack([x,y]));vals,vec=np.linalg.eigh(cov);ratio=float(vals[-1]/max(float(vals[0]),1e-9))
  if ratio>=1.5:angle=float(np.degrees(np.arctan2(vec[1,-1],vec[0,-1]))%180)
 profile=[float(a[mask].mean()) if mask.any() else 0. for a in energy];return {'axis_deg':angle,'axis_ratio':ratio,'focus_profile':profile}
def evidence(a,b):
 angle=None if a['axis_deg'] is None or b['axis_deg'] is None else min(abs(a['axis_deg']-b['axis_deg']),180-abs(a['axis_deg']-b['axis_deg']));u=np.asarray(a['focus_profile']);v=np.asarray(b['focus_profile']);denom=float(np.linalg.norm(u)*np.linalg.norm(v));cos=float(np.dot(u,v)/denom) if denom>1e-12 else None
 state='abstain_missing_evidence' if angle is None or cos is None else 'compatible_evidence' if angle<=30 and cos>=.8 else 'lower_evidence';return {'axis_difference_deg':angle,'focus_profile_cosine':cos,'triage':state,'semantics':'screening_evidence_not_specimen_identity'}
def main():
 dat=json.loads((R/'results/l77/results.json').read_text());rows=[r for r in dat['scenes'] if r['variant']=='clean'];meta={str((R/x).parent):{(r['pair'],r['condition']):r for r in json.loads((R/x).read_text())['records']} for x in ['results/r89/results.json','results/r89/opaque/results.json']};out=[]
 for row in rows:
  base=Path(row['source']);r=meta[str(base)][row['pair'],row['condition']];z=np.load(base/row['archive']);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=[np.asarray(Image.open(base/x['file']).convert('L')) for x in r['images']];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 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'],'archive':row['archive'],'archive_sha256':row['archive_sha256'],'pair':row['pair'],'split':row['split'],'condition':row['condition'],'candidate_features':fs,'links':links});print(row['split'],row['pair'],row['condition'],len(links),flush=True)
 # Oracle constructed references used solely for adversarial controls, not production inference.
 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']);imgs=[np.asarray(Image.open(R/'results/r89'/x['file']).convert('L')) for x in r['images']];en=[cv2.Laplacian(a,cv2.CV_32F,ksize=3)**2 for a in imgs];controls=[]
 for scenario,sources in [('different_source',[0,1]),('same_source',[0,0])]:
  masks=[z['refs'][0,sources[0]],z['refs'][1,sources[1]]];inter=int((masks[0]&masks[1]).sum());union=int((masks[0]|masks[1]).sum());controls.append({'scenario':scenario,'constructed_source_ids':sources,'mask_iou':inter/union,**evidence(features(masks[0],en),features(masks[1],en))})
 (O/'results.json').write_text(json.dumps({'format':'r90-evidence-v1','protocol_sha256':sha(O/'protocol.json'),'l77_sha256':sha(R/'results/l77/results.json'),'records':out,'oracle_controls':controls},indent=2)+'\n');print('oracle',controls,flush=True)
if __name__=='__main__':main()
