"""Coarse similarity screen between fixed L78 training and L75 evaluation crops."""
import json,hashlib
from pathlib import Path
import numpy as np
from r76_source_audit import hash_crop,hash_image
from l75_run import extract
R=Path(__file__).resolve().parents[1];O=R/'results/l78';sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 sel=json.loads((O/'training-selection.json').read_text());manifest=json.loads((O/'training-image-manifest.json').read_text())['records'];ev=json.loads((R/'results/l75/protocol.json').read_text())['sources'];training=[]
 for r,f in zip(sel['training_sources'],manifest):
  d={'image_path':f['path'],'image_sha256':f['sha256'],'annotation_path':str(R/'datasets/r84-khanom'/r['coco_file']),'annotation_sha256':r['coco_sha256'],'image_id':r['image_id'],'annotation_id':r['annotation_id']};training.append((d,*extract(d)))
 test=[(s,*extract(s)) for s in ev];records=[]
 for i,(a,crop,m) in enumerate(training):
  hc=hash_crop(crop,m);hi=hash_image(R/a['image_path'])
  for j,(b,other,om) in enumerate(test):
   dist=[]
   for flip in (False,True):
    for k in range(4):dist.append(int(np.count_nonzero(hc!=hash_crop(np.rot90(np.fliplr(other) if flip else other,k).copy(),np.rot90(np.fliplr(om) if flip else om,k).copy()))))
   records.append({'train':i,'evaluation':j,'exact_sha256_match':a['image_sha256']==b['image_sha256'],'whole_image_dct_distance':int(np.count_nonzero(hi!=hash_image(R/b['image_path']))),'crop_min_dct_distance_8_orientations':min(dist)})
 report={'format':'l78-source-audit-v1','training_selection_sha256':sha(O/'training-selection.json'),'evaluation_protocol_sha256':sha(R/'results/l75/protocol.json'),'comparisons':records,'warning':'Coarse perceptual hash screen only; low distance suggests examination, high distance does not prove different specimen, source sample, slide, or base-model training independence.'};(O/'source-audit.json').write_text(json.dumps(report,indent=2)+'\n');print('comparisons',len(records),'min whole',min(x['whole_image_dct_distance'] for x in records),'min crop',min(x['crop_min_dct_distance_8_orientations'] for x in records),'crop<=8',sum(x['crop_min_dct_distance_8_orientations']<=8 for x in records))
if __name__=='__main__':main()
