"""Pinned official RF-DETR-Seg training; one process and GPU per comparison run."""
from __future__ import annotations

import gc
import importlib.metadata
import json
import os
from pathlib import Path
import time

from pallet.instance_segmentation_seed import digest, event, read_json, save, verify_dataset, RESOLUTION


def model_class(kind):
    from rfdetr import RFDETRSegSmall, RFDETRSegMedium
    return {'small': RFDETRSegSmall, 'medium': RFDETRSegMedium}[kind]


def train_one(ctx, kind):
    import torch
    from rfdetr.assets.model_weights import ModelWeights
    if importlib.metadata.version('rfdetr')!='1.11.0': raise ValueError('Training requires rfdetr==1.11.0')
    torch.set_num_threads(4)
    dataset = verify_dataset(ctx)
    out = ctx['output']/'training'/kind
    done = out/'completion.json'
    if done.exists():
        receipt = read_json(done)
        if receipt['task_hash']!=ctx['binding']['task_hash'] or digest(out/receipt['checkpoint'])!=receipt['checkpoint_sha256']:
            raise ValueError('Completed training model changed')
        return receipt
    out.mkdir(parents=True, exist_ok=True)
    device = getattr(ctx['args'], 'device_'+kind)
    torch.cuda.set_device(torch.device(device))
    config = {'task_hash':ctx['binding']['task_hash'], 'kind':kind, 'device':device,
              'epochs':ctx['args'].epochs, 'resolution':RESOLUTION, 'seed':ctx['args'].seed,
              'lr':1e-4, 'lr_encoder':1e-5, 'effective_batch':8, 'patience':30,
              'dataset_sha256':digest(ctx['output']/'dataset_manifest.json'),
              'training_source_sha256':digest(__file__),
              'cuda_device_order':os.environ.get('CUDA_DEVICE_ORDER'),
              'gpu_total_memory_bytes':torch.cuda.get_device_properties(torch.device(device)).total_memory,
              'dependencies':{n:importlib.metadata.version(n) for n in
                              ['rfdetr','torch','torchvision','pytorch-lightning','torchmetrics','numpy']}}
    save(out/'run_config.json', config)
    started = time.monotonic()
    cls = model_class(kind)
    batch = 2
    while True:
        model = cls(num_classes=1, resolution=RESOLUTION, device=device, gradient_checkpointing=True,
                    compile=False)
        asset = ModelWeights.from_filename(f'rf-detr-seg-{kind}.pt')
        weights = Path(model.model_config.pretrain_weights)
        save(out/'pretraining.json', {'url':asset.url, 'file':str(weights), 'sha256':digest(weights),
                                   'published_md5':asset.md5_hash})
        try:
            model.train(dataset_dir=str(ctx['output']/'dataset'), output_dir=str(out),
                epochs=ctx['args'].epochs, batch_size=batch, grad_accum_steps=8//batch,
                eval_batch_size=1, device='cuda', devices=device.split(':')[-1]+',', lr=1e-4, lr_encoder=1e-5,
                seed=ctx['args'].seed, num_workers=0, multi_scale=False, expanded_scales=False,
                scale_jitter=False, use_ema=True, early_stopping=True, early_stopping_patience=30,
                early_stopping_use_ema=True, early_stopping_min_delta=.001,
                run_test=False, tensorboard=False, wandb=False, progress_bar=None,
                checkpoint_interval=50, compute_val_loss=True, class_names=['pallet'],
                square_resize_div_64=True, aug_config=None, eval_masks_head_resolution=False,
                resume=str(out/'last.ckpt') if (out/'last.ckpt').exists() else '')
            break
        except torch.cuda.OutOfMemoryError:
            if batch==1: raise
            event('training_oom_retry', model=kind, previous_batch=batch, new_batch=1, grad_accum_steps=8)
            batch=1
            del model; gc.collect(); torch.cuda.empty_cache()
    best = out/'checkpoint_best_total.pth'
    if not best.exists(): raise ValueError('Official training did not produce a best checkpoint')
    # Explicit constructor settings are required for the pinned 1.11 checkpoint format.
    del model; gc.collect(); torch.cuda.empty_cache()
    loaded = cls(num_classes=1, resolution=RESOLUTION, device=device, pretrain_weights=str(best), compile=False)
    if not hasattr(loaded.model.model, 'segmentation_head'): event('reload', model=kind, checkpoint=str(best))
    payload = torch.load(best, map_location='cpu', weights_only=False)
    epochs_trained = int(payload.get('epoch', -1))+1
    receipt = {**config, 'state':'complete', 'batch_size':batch, 'grad_accum_steps':8//batch,
               'checkpoint':best.name, 'checkpoint_sha256':digest(best),
               'checkpoint_epoch':epochs_trained, 'elapsed_seconds':time.monotonic()-started,
               'peak_cuda_memory_bytes':torch.cuda.max_memory_allocated(torch.device(device)),
               'weights_reloaded':True, 'metrics_csv_sha256':digest(out/'metrics.csv')}
    save(done, receipt); event('train_complete', model=kind, elapsed_seconds=receipt['elapsed_seconds'], batch_size=batch)
    del loaded; gc.collect(); torch.cuda.empty_cache()
    return receipt


def train(ctx):
    kinds = ['small','medium'] if ctx['args'].model=='both' else [ctx['args'].model]
    for kind in kinds: train_one(ctx, kind)
