"""Prepare a tiny single-class YOLO pilot from the R21 public training selection."""
import hashlib
import json
import shutil
from pathlib import Path

ROOT=Path(__file__).resolve().parent.parent
DATA=Path('/tmp/diatom-detector-pilot');OUT=ROOT/'results/r22';OUT.mkdir(exist_ok=True)
manifest=json.loads((ROOT/'results/r21/training-selection.json').read_text())
records=[];g_seen=0
for index,row in enumerate(manifest['selection'],1):
    genus=row['category'].split('_')[0]
    if genus=='Gomphonema':
        g_seen+=1;split='train' if g_seen<=6 else 'val'
    elif genus=='Pinnularia':split='val' if row['filename_family_heuristic']=='Pin_KL' else 'train'
    else:raise ValueError('Unexpected category')
    source=Path('/tmp/diatom-adaptation')/f'{index:02d}.jpg'
    dest=DATA/'images'/split/f'{index:02d}.jpg';dest.parent.mkdir(parents=True,exist_ok=True)
    lab=DATA/'labels'/split/f'{index:02d}.txt';lab.parent.mkdir(parents=True,exist_ok=True)
    shutil.copyfile(source,dest)
    coco=json.loads((Path('/tmp/diatom-mask-coco')/row['annotation_file']).read_text())
    anns=[a for a in coco['annotations'] if a['image_id']==row['image']['id']]
    w,h=row['image']['width'],row['image']['height'];lines=[]
    for a in anns:
        x,y,bw,bh=a['bbox']
        if not (0<=x<x+bw<=w and 0<=y<y+bh<=h):raise ValueError('Invalid COCO box')
        lines.append(f'0 {(x+bw/2)/w:.8f} {(y+bh/2)/h:.8f} {bw/w:.8f} {bh/h:.8f}')
    if not lines:raise ValueError('Selected training image has no labels')
    lab.write_text('\n'.join(lines)+'\n')
    records.append({'local_id':index,'image_file':row['image']['file_name'],'category':row['category'],
                    'family_heuristic':row['filename_family_heuristic'],'split':split,'annotations':len(lines),
                    'image_sha256':hashlib.sha256(source.read_bytes()).hexdigest()})
train={r['image_sha256'] for r in records if r['split']=='train'};val={r['image_sha256'] for r in records if r['split']=='val'}
assert len(train)==12 and len(val)==4 and not train&val
(DATA/'dataset.yaml').write_text(f'path: {DATA}\ntrain: images/train\nval: images/val\nnames:\n  0: diatom_target\n')
(OUT/'data-plan.json').write_text(json.dumps({'source_selection':'/results/r21/training-selection.json',
 'description':'12 train and 4 validation images from two public taxa, grouped only by heuristic filename family; other diatoms may be unlabeled',
 'records':records},indent=2))
print('train',len(train),'val',len(val),'annotation boxes',sum(r['annotations'] for r in records))
