"""Compare exact byte hashes of new UDE crops against themselves and known local UDE images."""
import collections,hashlib,json
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/diversity-fetch'
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
selection=json.loads((O/'selection.json').read_text());download=json.loads((O/'download-report.json').read_text());assert sha(O/'selection.json')==download['selection_sha256'];new={x['annotation_id']:x for x in selection['rows']};fetched={x['annotation_id']:x for x in download['images']};assert len(new)==len(fetched)==120 and new.keys()==fetched.keys();groups=collections.defaultdict(list)
for ident,r in new.items():
 p=O/r['local_file'];h=sha(p);assert h==fetched[ident]['sha256'];groups[h].append({'kind':'new_development','annotation_id':ident,'slide':r['source_slide'],'path':str(p.relative_to(R))})
old=[]
p=R/'results/pilot/ude-adaptation-within-genus';sel=json.loads((p/'selection.json').read_text());report=json.loads((p/'download-report.json').read_text());oldhash={r['annotation_id']:r['sha256'] for r in report['images']}
for r in sel['rows']:
 path=p/r['local_file'];h=sha(path);assert h==oldhash[r['annotation_id']];old.append((r['annotation_id'],r['source_slide'],path,h))
p=R/'results/r14/prefix';meta=json.loads((p/'reference-manifest.json').read_text())
for r in meta['rows']:
 path=p/r['local_file'];h=sha(path);assert h==r['sha256'];old.append((r['annotation_id'],r['source_slide'],path,h))
p=R/'results/r7';meta=json.loads((p/'reference-manifest.json').read_text())
for r in meta:
 path=p/r['local_file'];h=sha(path);old.append((r['annotation_id'],r['source_slide'],path,h))
for ident,slide,path,h in old:
 if h in groups:groups[h].append({'kind':'prior_ude','annotation_id':ident,'slide':slide,'path':str(path.relative_to(R))})
flagged=[{'sha256':h,'members':members} for h,members in groups.items() if len(members)>1];out={'format':'r112-ude-exact-duplicate-audit-v1','selection_sha256':sha(O/'selection.json'),'download_report_sha256':sha(O/'download-report.json'),'new_images':len(new),'prior_images_checked':len(old),'duplicate_groups':flagged,'warning':'Byte equality only; cropped, recompressed, rotated, related or different images from the same biological sample can go undetected. Biological independence is unknown.'};(O/'duplicate-audit.json').write_text(json.dumps(out,indent=2)+'\n');print('New images:',len(new),'prior images:',len(old),'exact duplicate groups:',len(flagged))
