"""Frozen transformed crop screen against all training and R96 evaluation cases."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from r76_source_audit import hash_crop,hash_image
R=Path(__file__).resolve().parents[1];O=R/'results/r97';D=R/'datasets/r80-gunduz'
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()
def add_crops(refs,ids,rgb,group,name,filesha,path,whole,dst):
 for m,id in zip(refs,ids):
  yy,xx=np.nonzero(m);assert len(xx);crop=rgb[yy.min():yy.max()+1,xx.min():xx.max()+1];mask=m[yy.min():yy.max()+1,xx.min():xx.max()+1];dst.append({'group':group,'name':name,'annotation_id':int(id),'image_sha256':filesha,'image_path':path,'whole_hash':whole,'crop_hash':hash_crop(crop,mask)})
def main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if parent!=os.getppid():raise RuntimeError('Launcher exited')
 p=json.loads((O/'protocol.json').read_text())
 for f,h in p['inputs'].items():assert sha(R/f)==h
 r80=json.loads((R/'results/r80/source-audit.json').read_text())['targets'];base={x['id']:x for x in json.loads((R/'results/r80/baseline.json').read_text())['records']};mf=json.loads((R/'results/r95/partial/training-manifest.json').read_text())['records'];previous=json.loads((R/'results/l79/results.json').read_text())['records'];assert len(r80)==24 and len(mf)==28 and len(previous)==19;references=[]
 for row in mf:
  ip=R/row['full_image'];lp=R/row['full_label'];assert sha(ip)==row['full_image_sha256'] and sha(lp)==row['full_label_sha256'];rgb=np.asarray(Image.open(ip).convert('RGB'));ids=row['full_annotation_ids'];lines=lp.read_text().splitlines();assert len(lines)==len(ids) and rgb.shape==(512,512,3);masks=[]
  for line in lines:
   v=np.asarray([float(x) for x in line.split()]);assert v[0]==0;mask=np.zeros((512,512),np.uint8);cv2.fillPoly(mask,[np.rint(v[1:].reshape(-1,2)*512).astype('int32')],1);masks.append(mask.astype(bool))
  add_crops(masks,ids,rgb,'training',row['stem'],sha(ip),str(ip.relative_to(R)),hash_image(ip),references)
 assert len(references)==47
 for row in previous:
  ip=R/row['source'];ap=R/'results/l79'/row['archive'];assert sha(ip)==row['source_sha256'] and sha(ap)==row['archive_sha256'];im=Image.open(ip).convert('RGB');rgb=np.zeros((512,512,3),np.uint8)
  if row['group']=='real':rgb[64:448]=np.asarray(im.resize((512,384),Image.Resampling.LANCZOS))
  else:rgb=np.asarray(im)
  z=np.load(ap);add_crops(z['refs'],z['refids'].tolist(),rgb,'prior_'+row['group'],row['name'],sha(ip),str(ip.relative_to(R)),hash_image(ip),references)
 assert len(references)==79
 results=[]
 for i,row in enumerate(r80):
  ident=row['id'];ip=D/'images'/f'{ident}.png';mp=D/'masks'/f'{ident}.png';xp=D/'xml'/f'{ident}.xml';assert sha(ip)==row['image_sha256'] and sha(mp)==row['mask_sha256'] and sha(xp)==row['xml_sha256'];rgb=np.asarray(Image.open(ip).convert('RGB'));mask=np.asarray(Image.open(mp).convert('L'))>0;_,cc=cv2.connectedComponents(mask.astype('uint8'),connectivity=8);whole=hash_image(ip);comparisons=[]
  for inst in base[ident]['instances']:
   full=cc==inst['component_label'];yy,xx=np.nonzero(full);assert len(xx)==inst['area'];crop=rgb[yy.min():yy.max()+1,xx.min():xx.max()+1];cm=full[yy.min():yy.max()+1,xx.min():xx.max()+1];variants=[hash_crop(np.rot90(np.fliplr(crop) if flip else crop,k).copy(),np.rot90(np.fliplr(cm) if flip else cm,k).copy()) for flip in (False,True) for k in range(4)]
   for v in references:
    dist=min(int(np.count_nonzero(h!=v['crop_hash'])) for h in variants);same=sha(ip)==v['image_sha256'];comparisons.append({'component_label':inst['component_label'],'reference_group':v['group'],'reference_name':v['name'],'reference_annotation_id':v['annotation_id'],'same_file':same,'whole_dct_distance':int(np.count_nonzero(whole!=v['whole_hash'])),'crop_dct_distance':dist,'flag':same or dist<=8})
  flagged=[x for x in comparisons if x['flag']];results.append({'id':ident,'source_image_sha256':row['image_sha256'],'source_mask_sha256':row['mask_sha256'],'source_xml_sha256':row['xml_sha256'],'used_for_r54_training':row['used_for_r54_training'],'component_count':len(base[ident]['instances']),'minimum_crop_distance':min(x['crop_dct_distance'] for x in comparisons),'quarantined':bool(flagged),'flagged_pairs':flagged,'comparisons':comparisons});print(i+1,ident,'quarantine',bool(flagged),'min',results[-1]['minimum_crop_distance'],flush=True)
 out={'format':'r97-source-screen-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'training_crops':47,'prior_real_crops':16,'prior_synthetic_crops':16,'records':results,'warning':'Coarse image hashes can miss related or duplicate specimens and can flag unrelated similar objects; source file exclusion is not proof of biological independence.'};(O/'source-screen.json').write_text(json.dumps(out,indent=2)+'\n')
if __name__=='__main__':main()
