"""Apply frozen structural mask/box rule to preselected public metadata."""
import concurrent.futures,hashlib,json,sys
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
import r46_audit_boxes as boxes
import r46_fetch_cases as source
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r47';SRC=ROOT/'results/r46';TEMP=Path('/tmp/diatom-r47-public');sys.path.insert(0,str(ROOT/'diatom_pilot'))
from mask_component_guard import candidates_from_binary

def main():
 p=json.loads((OUT/'protocol.json').read_text());selection=(OUT/'selection.json').read_bytes();d=json.loads(selection);inv=json.loads((SRC/'inventory.json').read_text());sizes={x['name']:x['bytes'] for x in inv['files']}
 for path,key in [(OUT/'selection.json','selection_sha256'),(SRC/'inventory.json','inventory_sha256'),(ROOT/'diatom_pilot/mask_component_guard.py','guard_sha256'),(Path(boxes.__file__),'box_fetch_sha256'),(Path(source.__file__),'mask_fetch_sha256'),(Path(__file__),'script_sha256')]:
  if hashlib.sha256(path.read_bytes()).hexdigest()!=p[key]:raise ValueError('Frozen input changed: '+key)
 if (OUT/'results.json').exists():raise FileExistsError('Audit already completed')
 TEMP.mkdir(parents=True,exist_ok=True);boxes.TEMP.mkdir(parents=True,exist_ok=True)
 def obtain(ident):
  info=boxes.fetch(ident);name='annotations/'+ident+'.png';path=TEMP/(ident+'.png');data=source.get(name,sizes[name]);
  if path.exists() and path.read_bytes()!=data:raise ValueError('Existing mask differs')
  if not path.exists():path.write_bytes(data)
  return info,path
 received={}
 with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
  futures={executor.submit(obtain,ident):ident for ident in d['selection']}
  for n,future in enumerate(concurrent.futures.as_completed(futures),1):
   info,path=future.result();received[info['id']]=(info,path)
   if n%6==0:print(f'{n}/24 XML/mask pairs verified',flush=True)
 records=[]
 for index,ident in enumerate(d['selection'],1):
  info,path=received[ident];rgb=np.asarray(Image.open(path).convert('RGB'));h,w=rgb.shape[:2]
  if [w,h]!=info['size']:raise ValueError('Mask dimensions disagree')
  is_binary=((rgb==0).all(axis=2)|(rgb==255).all(axis=2))
  if not is_binary.all():result={'status':'ambiguous','reason':'nonbinary_source_mask','instances':[],'nonbinary_pixels':int((~is_binary).sum())}
  elif not info['objects']:result={'status':'ambiguous','reason':'no_boxes','instances':[]}
  else:result=candidates_from_binary((rgb!=0).any(axis=2),[x['box'] for x in info['objects']],minimum_area=20,containment=.98)
  rec={'id':ident,'xml_sha256':info['xml_sha256'],'mask_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'boxes':len(info['objects']),**result};records.append(rec)
  # Display only the source binary mask and source boxes, not instance claims.
  image=Image.fromarray(rgb).convert('RGB');draw=ImageDraw.Draw(image)
  for b in [x['box'] for x in info['objects']]:draw.rectangle(b,outline='#f2ae2e',width=6)
  image.thumbnail((528,396));image.save(OUT/f'case-{index:02d}.png')
  print(f"{index}/24 case {ident}: {result['status']} {result.get('reason') or ''}",flush=True)
 payload={'format':'r47-component-audit-v1','protocol_sha256':hashlib.sha256((OUT/'protocol.json').read_bytes()).hexdigest(),'records':records,
  'warning':'A structural component/box match is not proof of correct boundaries, species identity, exhaustiveness, true overlap status, or biological sample independence.'};(OUT/'results.json').write_text(json.dumps(payload,indent=2)+'\n')
 cards=[]
 for i,r in enumerate(records,1):cards.append(f"<article><h3>Case {i:02d} · {r['status'].replace('_',' ')}</h3><img src=\"case-{i:02d}.png\" alt=\"Source binary mask and annotated boxes\"><p>Boxes: {r['boxes']} · {r['reason'] or 'one-to-one structural match'}.</p></article>")
 page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Binary mask instance audit</title><style>body{font:16px/1.5 system-ui;background:#f3f6ef;color:#203a38}main{max-width:1150px;margin:auto;padding:24px}.notice{background:#fff2d6;padding:14px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:12px}article{background:white;padding:12px}img{width:100%}</style><main><nav><a href="/results/performance/">Performance monitor</a> · <a href="/research/R47.md">Research note</a></nav><h1>Binary mask instance audit</h1><p class="notice">The source binary foreground and object boxes do not inherently specify separate masks at overlaps. A one-to-one component/box correspondence is only a structural candidate, not expert verification or proof of exhaustive labels. Intersecting boxes and other ambiguity are rejected.</p><p>White: source binary mask; gold: source boxes. Results use components of at least 20 pixels and require 98% containment in exactly one non-intersecting box. Smaller components are reported but omitted from candidate instances. <a href="results.json">Audit data</a> · <a href="protocol.json">Frozen protocol</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>. Binary masks are resized and boxes overlaid; derivatives shared noncommercially under the same license.</p><div class="cards">{CARDS}</div></main></html>'''.replace('{CARDS}',''.join(cards));(OUT/'index.html').write_text(page)
 counts={k:sum(x['status']==k for x in records) for k in ('structural_match','ambiguous')};reasons={}
 for r in records:
  if r['reason']:reasons[r['reason']]=reasons.get(r['reason'],0)+1
 note=f'''# R47 · Binary mask and object-box correspondence\n\nSelected 24 public file IDs at random from the inventory, excluding all prior sampled IDs, before retrieving annotations. A fixed conservative rule rejects intersecting object boxes, components shared across boxes, missing components, extra components, and components with less than 98% containment. Components smaller than 20 pixels are reported but ignored for candidate formation. [See the mask/box audit](/results/r47/) and [frozen protocol](/results/r47/protocol.json).\n\n**{counts['structural_match']}/24** cases passed structural correspondence and **{counts['ambiguous']}/24** were ambiguous. Reasons: `{reasons}`. Passing does not establish a correct biological outline, complete labeling, true overlap, or sample independence. A binary mask can merge touching specimens or omit visible objects; intersecting boxes do not prove physical overlap. These 24 IDs were not selected from the prior 64, but their biological sample grouping and potential model training overlap are unknown. Their annotation masks have now been opened for this audit; image pixels were not fetched. Do not treat the audited set as independently blinded without preserving that history.\n\nThe conversion is a potential way to evaluate isolated structural cases without inventing overlap labels. For actual overlapping-instance segmentation, locate a public dataset with independently delineated overlapping instances or later use human review when other local experiments are exhausted. Source: Hüseyin Gündüz, [Diatom Dataset](https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset), CC BY-NC-SA 4.0.\n'''
 (ROOT/'research/R47.md').write_text(note)
 board=ROOT/'research/board.json';b=json.loads(board.read_text())
 for task in b['tasks']:
  if task['id']=='R47':task.update(status='review',summary=f"{counts['structural_match']}/24 new IDs pass strict structural component/box mapping; ambiguity and sample independence remain.",result='/results/r47/',note='R47.md')
 tmp=board.with_suffix('.json.tmp');tmp.write_text(json.dumps(b,indent=2)+'\n');tmp.replace(board);print('Completed binary-mask correspondence audit.',flush=True)
if __name__=='__main__':main()
