"""Audit exact and coarse perceptual overlap across fixed R44 and R76 inputs."""
import json,hashlib,itertools
from pathlib import Path
import numpy as np
import r76_source_audit as percept
R=Path(__file__).resolve().parents[1];O=R/'results/r78';IM=Path('/tmp/diatom-r44-menne/images')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 selection=json.loads((R/'results/r44/selection.json').read_text())['selection'];download={x['id']:x for x in json.loads((R/'results/r44/download-report.json').read_text())['images']};synth=json.loads((R/'results/r76/results.json').read_text())['records'];rows=[]
 for q in selection:
  path=IM/q['local_file'];digest=sha(path);assert digest==download[q['id']]['sha256'];rows.append({'group':'menne','id':str(q['id']),'slide':q['slide'],'xy':q['xy'],'path':str(path),'sha256':digest,'hash':percept.hash_image(path)})
 for q in synth:
  path=Path(q['scene_rgb_path']);digest=sha(path);assert digest==q['scene_rgb_sha256'];rows.append({'group':'synthetic','id':f"{q['pair']}-{q['condition']}",'path':str(path),'sha256':digest,'hash':percept.hash_image(path)})
 comparisons=[]
 for a,b in itertools.combinations(rows,2):
  distance=int(np.count_nonzero(a['hash']!=b['hash']));exact=a['sha256']==b['sha256'];spatial=False
  if a['group']==b['group']=='menne' and a['slide']==b['slide']:
   spatial=abs(a['xy'][0]-b['xy'][0])<512 and abs(a['xy'][1]-b['xy'][1])<512
  if exact or distance<=8 or spatial:comparisons.append({'a':a['group']+':'+a['id'],'b':b['group']+':'+b['id'],'exact_sha256':exact,'whole_image_dct_distance':distance,'possible_same_slide_spatial_overlap':spatial})
 data={'format':'r78-source-audit-v1','inputs':[{k:v for k,v in q.items() if k!='hash'} for q in rows],'flagged_pairs':comparisons,'screen':'Exact file SHA256; whole-frame 63-bit grayscale DCT pHash distance <=8; and overlapping 512px slide coordinates for same-slide Menne images. Screening thresholds are not proof of identity or independence; field overlap, resampling, specimen relationships and model-training overlap may be missed.'};(O/'source-audit.json').write_text(json.dumps(data,indent=2)+'\n');print('sources',len(rows),'flagged pairs',len(comparisons));print(comparisons[:12])
if __name__=='__main__':main()
