"""Audit additional Gündüz source components and source XML names."""
import ctypes,hashlib,json,os,signal,collections,xml.etree.ElementTree as ET
from pathlib import Path
import cv2,numpy as np
from PIL import Image
from diatom_pilot.mask_component_guard import candidates_from_binary
R=Path(__file__).resolve().parents[1];D=R/'datasets/r80-gunduz';O=R/'results/r112/design/source-audit'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if os.getppid()!=parent:raise RuntimeError('launcher exited')
 cv2.setNumThreads(2);provenance=json.loads((R/'results/r80/source-audit.json').read_text());screen={x['id']:x for x in json.loads((R/'results/r97/source-screen.json').read_text())['records']};out=[]
 for target in provenance['targets']:
  ident=target['id'];ip=D/'images'/f'{ident}.png';mp=D/'masks'/f'{ident}.png';xp=D/'xml'/f'{ident}.xml';assert sha(ip)==target['image_sha256'] and sha(mp)==target['mask_sha256'] and sha(xp)==target['xml_sha256'];root=ET.parse(xp).getroot();objects=[]
  for obj in root.findall('./objects/object'):
   box=[int(obj.findtext('./bbox/'+k)) for k in ('xmin','ymin','xmax','ymax')];objects.append({'source_id':obj.findtext('id'),'name':obj.findtext('name'),'box':box})
  arr=np.asarray(Image.open(mp).convert('L'));assert np.isin(arr,[0,255]).all();matched=candidates_from_binary(arr>0,[v['box'] for v in objects]);rec={'id':ident,'image':str(ip.relative_to(R)),'image_sha256':sha(ip),'mask':str(mp.relative_to(R)),'mask_sha256':sha(mp),'xml':str(xp.relative_to(R)),'xml_sha256':sha(xp),'objects':objects,'structural':matched,'previous_similarity_quarantine':bool(screen[ident]['quarantined']),'prior_r54_training':target['used_for_r54_training']};out.append(rec)
 result={'format':'r112-additional-source-audit-v1','source_audit_sha256':sha(R/'results/r80/source-audit.json'),'similarity_screen_sha256':sha(R/'results/r97/source-screen.json'),'script_sha256':sha(__file__),'license':'CC BY-NC-SA 4.0','warning':'Previously examined images. Matching a connected component to a source box is not an expert-reviewed mask or independent biological sample. Prior screen is incomplete and does not establish absence of duplicates.','records':out};(O/'r80-audit.json').write_text(json.dumps(result,indent=2)+'\n');usable=[r for r in out if r['structural']['status']=='structural_match' and not r['previous_similarity_quarantine']];names=collections.Counter(r['objects'][x['box_index']]['name'] for r in usable for x in r['structural']['instances']);print(json.dumps({'audited_images':len(out),'passing_images':len(usable),'candidate_objects':sum(len(r['structural']['instances']) for r in usable),'prior_quarantined_images':sum(r['previous_similarity_quarantine'] for r in out),'source_taxa':names},indent=2))
if __name__=='__main__':main()
