"""Preselected native-pixel survey of 12 previously unpreviewed scan files."""
import csv
import hashlib
import json
import random
import re
import sys
import time
from pathlib import Path

import numpy as np
import torch
from PIL import Image,ImageDraw,ImageFont,ImageOps
from ultralytics import YOLO
from ultralytics.nn.tasks import DetectionModel
from ultralytics.nn.modules import Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL
from torch.nn import Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample

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

inventory=list(csv.DictReader((ROOT/'results/scan-inventory.csv').open(newline='')))
html=(ROOT/'results/field-review.html').read_text()
prior=json.loads(re.search(r'<script type="application/json" id="data">(.*?)</script>',html,re.S).group(1))
seen={r['name'] for r in prior}
eligible=sorted((r for r in inventory if r['filename'] not in seen and int(r['bytes'])>=1_000_000_000),key=lambda r:r['filename'])
rng=random.Random(20261201);selected=rng.sample(eligible,12)
# Select every coordinate and plane before running any model.
plan=[]
for row in selected:
    w,h,depth=(int(row[k]) for k in ('width_px','height_px','z_planes'))
    plan.append({'slide':row['filename'],'origin_xy':[rng.randrange(w-767),rng.randrange(h-767)],'z':depth//2})
torch.set_num_threads(4)
allow=[DetectionModel,Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL,Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample,set]
checkpoint_path=Path('/tmp/diatom-detector.pt')
with torch.serialization.safe_globals(allow):ckpt=torch.load(checkpoint_path,map_location='cpu',weights_only=True)
model=YOLO('yolov8n.yaml',task='detect');model.model=ckpt['model'].float()
font=ImageFont.truetype('DejaVuSans.ttf',15);sheet=Image.new('RGB',(1050,len(plan)*410),'#f8f8f2');draw=ImageDraw.Draw(sheet)
out=ROOT/'results/r3/scan-survey';out.mkdir(exist_ok=True)
records=[]
for i,item in enumerate(plan):
    with Stack(ROOT/'scans'/item['slide']) as stack:
        assert item['origin_xy'][0]+768<=stack.width and item['origin_xy'][1]+768<=stack.height and item['z']<stack.depth
        image=stack.field(item['z'],*item['origin_xy'],768)
    raw=out/f'field-{i+1:02d}.png';image.save(raw)
    def predict(im,size):
        pred=model.predict(np.asarray(im.convert('RGB')),imgsz=size,conf=.05,device='cpu',verbose=False)[0]
        return pred.boxes.xyxy.cpu().tolist(),pred.boxes.conf.cpu().tolist()
    started=time.monotonic();boxes,conf=predict(image,768);tile_candidates=[]
    for y in (0,256,384):
        for x in (0,256,384):
            tb,tc=predict(image.crop((x,y,x+384,y+384)),640)
            for b,c in zip(tb,tc):tile_candidates.append({'xyxy':[b[0]+x,b[1]+y,b[2]+x,b[3]+y],'confidence':c,'tile_origin':[x,y]})
    kept=[]
    for v in sorted(tile_candidates,key=lambda d:-d['confidence']):
        if all(iou(v['xyxy'],q['xyxy'])<.5 for q in kept):kept.append(v)
    result={**item,'image':raw.name,'full_field':[{'xyxy':b,'confidence':c} for b,c in zip(boxes,conf)],
            'tile_candidates':tile_candidates,'tile_kept':kept,'elapsed_seconds_including_ten_inferences':time.monotonic()-started}
    records.append(result)
    for col,(label,predictions) in enumerate((('Full field',result['full_field']),('Tiles + NMS',kept))):
        im=ImageOps.autocontrast(image,cutoff=.25).convert('RGB');d=ImageDraw.Draw(im)
        for r in predictions:d.rectangle(r['xyxy'],outline='#00d6ad',width=3)
        x=col*480+8;y=i*410+35
        sheet.paste(im.resize((360,360)),(x,y))
        draw.text((x,i*410+7),f"{i+1:02d} {item['slide'][:9]} · {label} · {len(predictions)} boxes",font=font,fill='#193b36')
    print(i+1,item['slide'][:9],item['origin_xy'],'z',item['z'],'full',len(boxes),'tiled',len(kept),flush=True)
sheet.save(out/'survey.jpg',quality=90)
(out/'survey.json').write_text(json.dumps({'selection_seed':20261201,'eligible_scan_count':len(eligible),
 'selection':'12 distinct scan files excluded from prior field-review; one uniformly sampled XY window per scan, middle indexed plane',
 'model_sha256':hashlib.sha256(checkpoint_path.read_bytes()).hexdigest(),'confidence_threshold':.05,
 'field_size':768,'tile_size':384,'tile_input_size':640,'tile_origins':[0,256,384],
 'global_tile_nms_iou':.5,'fields':records},indent=2))
