"""Audit binary masks against preselected instance boxes; no inferred ground truth."""
import hashlib,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r46';TEMP=Path('/tmp/diatom-r46-public')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 if (OUT/'mask-audit.json').exists():raise FileExistsError('Existing audit')
 selection=(OUT/'case-selection.json').read_bytes();s=json.loads(selection);downloads=json.loads((OUT/'case-download.json').read_text());boxraw=(OUT/'box-audit.json').read_bytes();box=json.loads(boxraw)
 if sha(OUT/'box-audit.json')!=s['box_audit_sha256'] or hashlib.sha256(selection).hexdigest()!=downloads['selection_sha256']:raise ValueError('Evidence mismatch')
 byid={x['id']:x for x in box['records']};bydownload={x['id']:x for x in downloads['records']};records=[]
 for idx,row in enumerate(s['selection'],1):
  ident=row['id'];meta=byid[ident];download=bydownload[ident];imagepath=TEMP/'images'/f'{ident}.png';maskpath=TEMP/'annotations'/f'{ident}.png'
  if meta['xml_sha256']!=row['xml_sha256'] or any(sha(path)!=download['files'][key]['sha256'] for path,key in ((imagepath,'images'),(maskpath,'annotations'))):raise ValueError('Input hash mismatch')
  rgb=np.asarray(Image.open(maskpath).convert('RGB'));h,w=rgb.shape[:2]
  if [w,h]!=meta['size']:raise ValueError('Mask and XML size mismatch')
  binary=((rgb==0).all(axis=2)|(rgb==255).all(axis=2));invalid=int((~binary).sum());mask=(rgb!=0).any(axis=2)
  count,labels,stats,_=cv2.connectedComponentsWithStats(mask.astype('uint8'),connectivity=8);keep=[j for j in range(1,count) if stats[j,cv2.CC_STAT_AREA]>=20]
  support={}
  for component in keep:
   affected=[]
   for i,obj in enumerate(meta['objects']):
    x0,y0,x1,y1=obj['box'];overlap=int((labels[y0:y1,x0:x1]==component).sum())
    if overlap>=20:affected.append({'box_index':i,'pixels_in_box':overlap})
   if affected:support[component]=affected
  shared=[{'component_pixels':int(stats[k,cv2.CC_STAT_AREA]),'box_support':v} for k,v in support.items() if len(v)>1]
  empty_boxes=[]
  for i,obj in enumerate(meta['objects']):
   x0,y0,x1,y1=obj['box'];n=int(mask[y0:y1,x0:x1].sum())
   if not n:empty_boxes.append(i)
  rec={'id':ident,'stratum':row['stratum'],'objects':len(meta['objects']),'overlapping_box_pairs':len(meta['overlapping_box_pairs']),
    'nonbinary_pixels':invalid,'foreground_pixels':int(mask.sum()),'all_components':count-1,'components_at_least_20_pixels':len(keep),
    'shared_component_across_boxes':shared,'boxes_without_foreground':empty_boxes};records.append(rec)
  with Image.open(imagepath) as src:
   img=src.convert('RGBA')
   if img.size!=(w,h):raise ValueError('Image and XML size mismatch')
   layer=Image.new('RGBA',img.size,(0,180,145,0));layer.putalpha(Image.fromarray(mask.astype('uint8')*90));img=Image.alpha_composite(img,layer).convert('RGB');draw=ImageDraw.Draw(img)
   for j,obj in enumerate(meta['objects'],1):draw.rectangle(obj['box'],outline='#f2ae2e',width=5);draw.text((obj['box'][0]+4,obj['box'][1]+4),str(j),fill='#f2ae2e',stroke_width=2,stroke_fill='#111111')
   img.thumbnail((1056,792));img.save(OUT/f'case-{idx:02d}.jpg',quality=87)
  print(f"case {idx}/8 {ident}: {len(meta['objects'])} boxes, {len(shared)} shared-component warnings",flush=True)
 result={'format':'r46-mask-audit-v1','selection_sha256':hashlib.sha256(selection).hexdigest(),'box_audit_sha256':sha(OUT/'box-audit.json'),'download_sha256':sha(OUT/'case-download.json'),
  'component_minimum_pixels':20,'records':records,'warning':'A component intersecting two bounding boxes is only a warning: boxes can include background or parts of nearby objects. Binary masks do not by themselves identify each specimen at an overlap.'}
 (OUT/'mask-audit.json').write_text(json.dumps(result,indent=2)+'\n')
 cards=[]
 for i,r in enumerate(records,1):cards.append(f"<article><h3>Case {i} · {r['stratum'].replace('_',' ')}</h3><img src=\"case-{i:02d}.jpg\" alt=\"Public microscopy field with binary mask and annotated boxes\"><p>{r['objects']} annotated boxes · {r['overlapping_box_pairs']} box-intersection pairs · {len(r['shared_component_across_boxes'])} components intersecting at least two boxes.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Freshwater mask and box audit</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1100px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}article{background:white;padding:12px;margin:12px 0}img{max-width:100%}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R46.md">Research note</a></nav><h1>Freshwater mask and box audit</h1><p class="notice">Eight cases selected using bounding-box metadata: four with intersecting boxes and four multi-object controls. Box intersections and shared mask components are only leads; they do not prove true specimen overlap. Sample independence and complete labeling are not verified.</p><p>Teal: source binary foreground mask. Gold: source specimen boxes. The source binary mask is not an individual label map at overlaps. <a href="mask-audit.json">Audit details</a> · <a href="case-selection.json">Frozen selection</a></p><p>Source: Hüseyin Gündüz, <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Diatom Dataset</a>, <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a>. Images are resized with source mask and boxes overlaid; derivatives are shared under the same license for noncommercial use.</p>{CARDS}</main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 print('Mask-and-box audit complete.',flush=True)
if __name__=='__main__':main()
