"""Label-separated object-proposal audit on public single-taxon box labels."""
import hashlib,json,time
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image,ImageDraw
from ultralytics import YOLO
from ultralytics.models.sam import Predictor
from diatom_pilot.box_matching import box_iou,match_boxes
import r38_synthetic_crossings as base
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r74/baseline'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def starts(n,tile=640,stride=512):
 if n<tile:raise ValueError('Image smaller than tile')
 values=list(range(0,n-tile+1,stride))
 if values[-1]!=n-tile:values.append(n-tile)
 return values
def nms(items,threshold):
 kept=[];aliases=[]
 for q in items:
  match=next((v for v in kept if box_iou(q['box'],v['box'])>=threshold),None)
  if match is None:kept.append(q)
  else:aliases.append({'candidate':q['id'],'kept':match['id']})
 return kept,aliases
def labels(path,w,h):
 result=[]
 for line in path.read_text().splitlines():
  v=line.split()
  if len(v)!=5 or int(v[0])!=0:raise ValueError('Unexpected YOLO label')
  x,y,bw,bh=map(float,v[1:]);x0=(x-bw/2)*w;y0=(y-bh/2)*h;x1=(x+bw/2)*w;y1=(y+bh/2)*h
  if not (0<=x<=1 and 0<=y<=1 and 0<bw<=1 and 0<bh<=1 and -1e-3<=x0<x1<=w+1e-3 and -1e-3<=y0<y1<=h+1e-3):raise ValueError('Invalid normalized box')
  result.append([max(0.,x0),max(0.,y0),min(float(w),x1),min(float(h),y1)])
 return result
def outline(image,refs,pred):
 im=image.copy();draw=ImageDraw.Draw(im)
 for box in refs:draw.rectangle(box,outline='#00a975',width=8)
 for q in pred:draw.rectangle(q['box'],outline='#e04c3d',width=5)
 return im.resize((640,640),Image.Resampling.LANCZOS)
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for f in p['inputs']:
  if sha(f['path'])!=f['sha256']:raise ValueError('Frozen input changed '+f['path'])
 if (OUT/'results.json').exists():raise FileExistsError('Preserve result')
 torch.set_num_threads(4);detector=YOLO(str(base.DETECTOR));sel=json.loads((ROOT/'results/r74/pair-selection.json').read_text());records=[]
 for idx,row in enumerate(sel['pairs'],1):
  started=time.monotonic();ip=ROOT/'results/r74/sources'/f'{idx:02d}-image.jpg';lp=ROOT/'results/r74/sources'/f'{idx:02d}-label.txt';image=Image.open(ip).convert('RGB');w,h=image.size
  if (w,h)!=(2400,2400):raise ValueError('Unexpected tile dimensions')
  rgb=np.asarray(image);bgr=cv2.cvtColor(rgb,cv2.COLOR_RGB2BGR)
  # All boxes and masks are generated before opening this scene's labels.
  t=time.monotonic();full=detector.predict(bgr,imgsz=640,conf=.05,device='cpu',verbose=False)[0];fullboxes=[]
  if full.boxes is not None:
   for j,(bb,q) in enumerate(zip(full.boxes.xyxy.cpu().numpy(),full.boxes.conf.cpu().numpy())):fullboxes.append({'id':f'full-{j}','box':[float(v) for v in bb],'confidence':float(q)})
  fullboxes.sort(key=lambda q:-q['confidence']);fullkept,fullalias=nms(fullboxes,.5);full_seconds=time.monotonic()-t;t=time.monotonic();tileboxes=[];origins=[]
  for y in starts(h):
   for x in starts(w):
    crop=bgr[y:y+640,x:x+640];output=detector.predict(crop,imgsz=640,conf=.05,device='cpu',verbose=False)[0];origins.append([x,y])
    if output.boxes is not None:
     for j,(bb,q) in enumerate(zip(output.boxes.xyxy.cpu().numpy(),output.boxes.conf.cpu().numpy())):
      tileboxes.append({'id':f't{x}-{y}-{j}','box':[float(bb[0]+x),float(bb[1]+y),float(bb[2]+x),float(bb[3]+y)],'local_box':[float(v) for v in bb],'origin':[x,y],'confidence':float(q)})
  tileboxes.sort(key=lambda q:-q['confidence']);tilekept,tilealias=nms(tileboxes,.5);tile_seconds=time.monotonic()-t;sam=[];t=time.monotonic()
  for j,q in enumerate(tilekept[:8],1):
   x,y=q['origin'];tile=bgr[y:y+640,x:x+640];model=Predictor(overrides={'model':str(base.SAM),'task':'segment','mode':'predict','imgsz':640,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});model.set_image(tile);out=model(bboxes=[q['local_box']],verbose=False)[0]
   if out.masks is None or len(out.masks.data)!=1:raise ValueError('Unexpected SAM response')
   mask=out.masks.data.cpu().numpy()[0].astype(bool)
   if mask.shape!=(640,640):raise ValueError('Unexpected mask shape')
   maskfile=f'field-{idx:02d}-mask-{j:02d}.png';Image.fromarray(mask.astype('uint8')*255).save(OUT/maskfile);panel=Image.fromarray(cv2.cvtColor(tile,cv2.COLOR_BGR2RGB)).convert('RGBA');lay=Image.new('RGBA',panel.size,'#00b886');lay.putalpha(Image.fromarray(mask.astype('uint8')*105));preview=Image.alpha_composite(panel,lay).convert('RGB');previewfile=f'field-{idx:02d}-mask-{j:02d}.jpg';preview.resize((320,320),Image.Resampling.LANCZOS).save(OUT/previewfile,quality=88);sam.append({'candidate_id':q['id'],'origin':[x,y],'local_box':q['local_box'],'mask':maskfile,'mask_sha256':sha(OUT/maskfile),'preview':previewfile,'preview_sha256':sha(OUT/previewfile),'area':int(mask.sum())})
  sam_seconds=time.monotonic()-t;refs=labels(lp,w,h);scores={}
  for name,items in [('full',fullkept),('tiled',tilekept)]:scores[name]={str(th):match_boxes(refs,[q['box'] for q in items],th) for th in (.3,.5)}
  imagefile=f'field-{idx:02d}.jpg';panel=Image.new('RGB',(1920,680),'white');draw=ImageDraw.Draw(panel)
  for col,(title,im) in enumerate([('Published boxes',outline(image,refs,[])),('Full-image predictions',outline(image,refs,fullkept)),('Tiled predictions',outline(image,refs,tilekept))]):panel.paste(im,(col*640,40));draw.text((col*640+8,8),title,fill='#203a38')
  panel.save(OUT/imagefile,quality=88);rec={'index':idx,'site':row['site'],'stem':row['stem'],'size':[w,h],'target_boxes':refs,'full_raw':fullboxes,'full_kept_ids':[q['id'] for q in fullkept],'full_aliases':fullalias,'tile_origins':origins,'tiled_raw':tileboxes,'tiled_kept_ids':[q['id'] for q in tilekept],'tiled_aliases':tilealias,'scores':scores,'sam_candidates':sam,'timing':{'full_seconds':round(full_seconds,3),'tiled_seconds':round(tile_seconds,3),'sam_top8_seconds':round(sam_seconds,3),'total_seconds':round(time.monotonic()-started,3)},'image':imagefile,'image_sha256':sha(OUT/imagefile)};records.append(rec);print(f"{idx}/9 {row['site']} refs={len(refs)} full={scores['full']['0.5']['matched']} tiled={scores['tiled']['0.5']['matched']} tile_boxes={len(tilekept)} sam={len(sam)}",flush=True)
 (OUT/'results.json').write_text(json.dumps({'format':'r74-fossil-box-baseline-v1','protocol_sha256':sha(OUT/'protocol.json'),'records':records,'warning':'Nine fixed tiles from 3 sites, only Eucampia antarctica boxes labeled. Detection recall only on published labels, not instance mask accuracy, complete-label false positives, freshwater generalization, or human performance. Tile and biological independence, model training overlap unknown.'},indent=2)+'\n')
if __name__=='__main__':main()
