"""Create a blinded, paired-protocol development pack from two YOLO configurations."""
import json
import random
import sys
from pathlib import Path

from PIL import Image

ROOT=Path(__file__).resolve().parent.parent
sys.path.insert(0,str(ROOT/'research'))
sys.path.insert(0,str(ROOT/'experiments'))
from r5_link_planes import iou
from scan_fields import Stack

OUT=ROOT/'results/r8'
(OUT/'crops').mkdir(parents=True,exist_ok=True)
fields=json.loads((ROOT/'results/diatom-practice-round1.json').read_text())['fields']
full=json.loads((ROOT/'results/r3/predictions-0.05.json').read_text())
tiled=json.loads((ROOT/'results/r3/tiled-yolo.json').read_text())['fields']
population=[]
for prediction in full:
    sample=next(x for x in tiled if x['slide']==prediction['slide'] and x['field']==prediction['field'])
    field=next(x for x in fields if x['slide']==prediction['slide'] and x['field']==prediction['field'])
    a=[x['xyxy'] for x in prediction['boxes']]
    b=[x['xyxy'] for x in sample['tiled_boxes']]
    candidates=sorted(((iou(x,y),i,j) for i,x in enumerate(a) for j,y in enumerate(b) if iou(x,y)>=.5),
                      key=lambda t:(-t[0],t[1],t[2]))
    used_a=set();used_b=set()
    for score,i,j in candidates:
        if i not in used_a and j not in used_b:used_a.add(i);used_b.add(j)
    unmatched=[('full',i,box) for i,box in enumerate(a) if i not in used_a]
    unmatched += [('tiled',i,box) for i,box in enumerate(b) if i not in used_b]
    for gy in range(3):
        for gx in range(3):
            x0,y0=gx*256,gy*256
            disagreements=[]
            for source,index,box in unmatched:
                cx=(box[0]+box[2])/2;cy=(box[1]+box[3])/2
                if x0<=cx<x0+256 and y0<=cy<y0+256:
                    disagreements.append({'source':source,'box_index':index,'box':box})
            population.append({'slide':prediction['slide'],'field':prediction['field'],'z':prediction['z'],
                               'field_origin_xy':field['origin_xy'],'window_xyxy':[x0,y0,x0+256,y0+256],
                               'score':len(disagreements),'unmatched_boxes':disagreements})

seed=20261130
rng=random.Random(seed)
# Random tie-break prevents fixed slide ordering from determining equally scored ranks.
shuffled=population.copy();rng.shuffle(shuffled)
ranked=sorted(shuffled,key=lambda r:-r['score'])
priority=ranked[:8]
random_arm=rng.sample(population,8)
selected=[]
for row in priority+random_arm:
    if not any(row is item for item in selected):selected.append(row)
rng.shuffle(selected)
records=[]
for index,row in enumerate(selected,1):
    field=next(f for f in fields if f['slide']==row['slide'] and f['field']==row['field'])
    with Stack(ROOT/'scans'/row['slide']) as stack:
        full_image=stack.field(row['z'],*field['origin_xy'],768)
    file=f'crops/window-{index:02d}.png'
    full_image.crop(tuple(row['window_xyxy'])).save(OUT/file)
    records.append({'review_id':f'W{index:02d}','image_file':file,**row,
                    'priority_arm':any(row is p for p in priority),'random_arm':any(row is p for p in random_arm)})
manifest={'version':'r8-review-v1','seed':seed,'selection':'top 8 disagreement and 8 uniform sample, overlapping selections reviewed once',
          'unit':'nonoverlapping 256x256 image region within a practice field','universe_windows':len(population),
          'priority_count':8,'random_count':8,'selected_unique_count':len(records),'population':population,'windows':records}
(OUT/'review-manifest.json').write_text(json.dumps(manifest,indent=2))
# Do not expose arm membership, slide name, scores, or model predictions in the blinded UI manifest.
blind={'version':manifest['version'],'windows':[{'review_id':r['review_id'],'image_file':r['image_file']} for r in records]}
(OUT/'review-blinded.json').write_text(json.dumps(blind,indent=2))
print('universe',len(population),'selected unique',len(records),'both arms',sum(r['priority_arm'] and r['random_arm'] for r in records))
print('priority scores',[r['score'] for r in priority])
