"""Audit source-proposal votes in every development scene without treating them as truth."""
import collections,ctypes,json,os,signal,time
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.weak_scene_dataset import WeakSceneDataset,DEFAULT_MANIFESTS,digest
R=Path(__file__).resolve().parents[1];O=R/'results/r112/mask-uncertainty';parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if parent!=os.getppid():raise RuntimeError('launcher exited')
ds=WeakSceneDataset(include_mask_variants=True);selected={0,1,2,3,240,241,242,243,420,421,422,423,580,581,582,583,724,725,726,727};rows=[];totals=collections.Counter();start=time.monotonic()
for i in range(len(ds)):
 s=ds[i];votes=s['weak_mask_vote_count'];assert s['unknown_region'].all();entries=[]
 for j,x in enumerate(s['instances']):
  hist=np.bincount(votes[j].ravel(),minlength=4);nonzero=int(hist[1:].sum());entries.append({'annotation_id':x['annotation_id'],'source_species':x['source_species'],'proposal_vote_pixels_1_2_3':[int(v) for v in hist[1:]],'union_pixels':nonzero,'unanimous_fraction_of_union':float(hist[3]/nonzero) if nonzero else None,'center_in_frame_fraction':x['in_frame_fraction']});totals['instances']+=1
  for n in (1,2,3):totals[f'vote_{n}_instance_pixels']+=int(hist[n])
  totals['instances_with_disagreement']+=int(hist[1]+hist[2]>0);totals['empty_proposal_union']+=int(nonzero==0)
 row={'scene_id':s['scene_id'],'manifest':str(Path(s['manifest']).relative_to(R)),'instances':entries}
 if i in selected:
  image=s['image'];v=votes[0];rgb=np.repeat(image[:,:,None],3,axis=2).astype(np.float32);color=np.zeros_like(rgb);color[v==3]=[0,220,180];color[(v>0)&(v<3)]=[255,170,30];mask=v>0;rgb[mask]=.45*rgb[mask]+.55*color[mask];pane=Image.new('RGB',(780,420),'white');d=ImageDraw.Draw(pane);pane.paste(Image.fromarray(image).convert('RGB').resize((380,380)),(5,30));pane.paste(Image.fromarray(rgb.astype(np.uint8)).resize((380,380)),(395,30));d.text((6,5),'Scene',fill='#183b37');d.text((395,5),'First insertion: teal 3 votes, amber 1–2',fill='#183b37');name=f'{i:04d}-votes.jpg';pane.save(O/name,quality=90);row['comparison_image']=name
 rows.append(row)
 if (i+1)%100==0:print(i+1,'/',len(ds),'scenes, seconds',round(time.monotonic()-start,1),flush=True)
result={'format':'r112-mask-vote-audit-v1','manifests':{str(x.relative_to(R)):digest(x) for x in DEFAULT_MANIFESTS},'reader_sha256':digest(R/'diatom_pilot/weak_scene_dataset.py'),'script_sha256':digest(Path(__file__)),'scenes':len(ds),'totals':dict(totals),'warning':'Three correlated prompt predictions from one model. Vote agreement is not correctness or calibrated uncertainty. Full Academy background remains unknown and visibility is undefined; pixel counts sum across instances and can overlap.','records':rows};(O/'results.json').write_text(json.dumps(result,indent=2)+'\n');print('done',dict(totals),flush=True)
