"""Train a bounded single-class detector pilot using explicitly preselected public data."""
import hashlib
import json
import time
from pathlib import Path

import torch
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
checkpoint_path=Path('/tmp/diatom-detector.pt')
allow=[DetectionModel,Conv,C2f,Bottleneck,SPPF,Concat,Detect,DFL,Sequential,Conv2d,BatchNorm2d,SiLU,ModuleList,Identity,MaxPool2d,Upsample,set]
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();model.ckpt={'model':model.model}
torch.set_num_threads(4);start=time.monotonic()
params={'data':'/tmp/diatom-detector-pilot/dataset.yaml','epochs':3,'imgsz':512,'batch':4,'device':'cpu','workers':0,
        'optimizer':'AdamW','lr0':1e-4,'freeze':10,'mosaic':0.,'mixup':0.,'amp':False,'seed':20261202,
        'project':'/tmp/diatom-r22','name':'pilot','exist_ok':True,'plots':False,'val':True,'verbose':False}
model.train(**params)
run=Path('/tmp/diatom-r22/pilot');checkpoint=run/'weights/best.pt'
if not checkpoint.is_file():raise RuntimeError('Training did not write best checkpoint')
out={'parameters':params,'base_checkpoint_sha256':hashlib.sha256(checkpoint_path.read_bytes()).hexdigest(),
     'adapted_checkpoint_sha256':hashlib.sha256(checkpoint.read_bytes()).hexdigest(),
     'adapted_checkpoint_path':str(checkpoint),'elapsed_seconds':time.monotonic()-start,
     'warning':'Development pilot on 12 train / 4 validation public images of two taxa; sample independence and complete labels unverified.'}
(ROOT/'results/r22/training-run.json').write_text(json.dumps(out,indent=2))
print('saved',checkpoint,'seconds',round(out['elapsed_seconds'],2),flush=True)
