"""Predeclared coarse exact/perceptual comparison to previous polygon-proxy cases."""
import json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from r76_source_audit import hash_crop
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r115';D=R/'datasets/r115-gunduz';Q=R/'results/r112/source-mask-polygon-proxy'
def crop_hashes(rgb,mask):
 y,x=np.nonzero(mask);assert len(x)>0;rgb=rgb[y.min():y.max()+1,x.min():x.max()+1];mask=mask[y.min():y.max()+1,x.min():x.max()+1];return [hash_crop(np.rot90(np.fliplr(rgb) if flip else rgb,k).copy(),np.rot90(np.fliplr(mask) if flip else mask,k).copy()) for flip in (False,True) for k in range(4)]
def main():
 p=json.loads((O/'protocol.json').read_text());assert not (O/'leak-screen.json').exists() and sha(Q/'results.json')==p['prior_polygon_results_sha256'];old=json.loads((Q/'results.json').read_text())['records'];prior=[]
 for x in old:
  rgb=np.asarray(Image.open(Q/x['images']['crop']['file']).convert('RGB'));mask=np.asarray(Image.open(Q/x['images']['reference']['file']).convert('L'))>0;assert sha(Q/x['images']['crop']['file'])==x['images']['crop']['sha256'] and sha(Q/x['images']['reference']['file'])==x['images']['reference']['sha256'];prior.append({'id':x['id'],'hashes':crop_hashes(rgb,mask),'source_sha':x['source_image_sha256']})
 audit=json.loads((O/'annotation-audit.json').read_text());images=json.loads((O/'image-manifest.json').read_text());assert images['annotation_audit_sha256']==sha(O/'annotation-audit.json');meta={x['id']:x for x in audit['records']};selected={x['id']:x for x in audit['selected']};rows=[]
 for img in images['records']:
  ident=img['id'];entry=meta[ident];path=R/img['path'];assert sha(path)==img['sha256'] and sha(D/'masks'/f'{ident}.png')==entry['mask_sha256'];rgb=np.asarray(Image.open(path).convert('RGB'));binary=np.asarray(Image.open(D/'masks'/f'{ident}.png').convert('L'))>0;_,labels=cv2.connectedComponents(binary.astype('uint8'),connectivity=8);mask=labels==selected[ident]['component_label'];assert int(mask.sum())==selected[ident]['component_area'];variants=crop_hashes(rgb,mask);comparisons=[]
  for old in prior:
   distance=min(int(np.count_nonzero(a!=b)) for a in variants for b in old['hashes']);comparisons.append({'previous_case_id':old['id'],'exact_whole_image_sha256':img['sha256']==old['source_sha'],'min_masked_crop_dct_distance':distance})
  quarantine=any(x['exact_whole_image_sha256'] or x['min_masked_crop_dct_distance']<=8 for x in comparisons);rows.append({'id':ident,'quarantined':quarantine,'minimum_crop_distance':min(x['min_masked_crop_dct_distance'] for x in comparisons),'comparisons':comparisons});print('screened',ident,'quarantine',quarantine,flush=True)
 out={'format':'r115-gunduz-leak-screen-v1','protocol_sha256':sha(O/'protocol.json'),'annotation_audit_sha256':sha(O/'annotation-audit.json'),'image_manifest_sha256':sha(O/'image-manifest.json'),'script_sha256':sha(__file__),'records':rows,'warning':'Coarse DCT similarity to the 29 prior polygon-proxy crops and exact whole-file hash only; cannot establish absence of duplicates, related specimens, site or pretraining overlap. Quarantined cases not replaced.'};(O/'leak-screen.json').write_text(json.dumps(out,indent=2)+'\n');print('complete',len(rows),'quarantined',sum(x['quarantined'] for x in rows),flush=True)
if __name__=='__main__':main()
