from pathlib import Path

import numpy as np
from PIL import Image
import torch

from pallet.annotation import AnnotationSet, Box, FrameAnnotation, Review, record_review
from pallet.data import FrameRecord
from pallet.data.loader import NormalizationStats
from pallet.experiments.dataset import PalletDataset
from pallet.experiments.evaluate import evaluate
from pallet.experiments.train import train_yolo
from pallet.export import export_onnx
from pallet.models import PalletDetector


def test_one_epoch_and_evaluation_contract(tmp_path: Path):
    torch.set_num_threads(1)
    records, frames = [], []
    for idx in range(2):
        depth = tmp_path / f"depth_{idx}.png"
        intensity = tmp_path / f"intensity_{idx}.png"
        Image.fromarray(np.full((32, 48), 1000 + idx, np.uint16)).save(depth)
        Image.fromarray(np.full((32, 48), 100 + idx, np.uint16)).save(intensity)
        frame_id = f"test/{idx}#default"
        anchor = f"synthetic-anchor-{idx}"
        records.append(FrameRecord(frame_id, f"group-{idx}", "default",
                                   {"depth": depth, "intensity": intensity},
                                   sensor_config={"grid": [32, 48], "depth_source": "depth",
                                                  "depth_available": True, "scale_to_mm": 1,
                                                  "rasters_aligned": True},
                                   source_sha256=anchor))
        frame = FrameAnnotation(frame_id, f"group-{idx}", str(depth), 48, 32,
                                source_anchor_hash=anchor,
                                split="train" if idx == 0 else "val")
        record_review(frame, Review("a", "approve"), status="pos",
                      boxes=[Box(10, 6, 24, 18)])
        record_review(frame, Review("b", "approve"))
        frames.append(frame)
    annotations = AnnotationSet(frames)
    stats = NormalizationStats(1000, 100)
    dataset = PalletDataset(records[1:], annotations, stats, size=64)
    assert len(dataset) == 1
    model = PalletDetector(1, pretrained=None)
    metrics = evaluate(model, dataset, device="cpu")
    assert metrics["images"] == 1 and metrics["objects"] == 1
    best = train_yolo(records[:1], records[1:], annotations, stats, tmp_path / "run",
                      pretrained=None, epochs=1, batch_size=1, effective_batch=1,
                      size=64, device="cpu")
    assert best.exists()
    assert (tmp_path / "run" / "last.pt").exists()
    exported = export_onnx(best, tmp_path / "run" / "smoke.onnx")
    assert exported["outputs"][0]["max_absolute_difference"] < 0.003
    rf_best = train_yolo(records[:1], records[1:], annotations, stats, tmp_path / "rf_run",
                         family="rfdetr-small", pretrained=False, epochs=1, batch_size=1,
                         effective_batch=1, size=64, device="cpu")
    assert rf_best.exists()
    rf_exported = export_onnx(rf_best, tmp_path / "rf_run" / "smoke.onnx")
    assert all(item["max_absolute_difference"] < 0.003 for item in rf_exported["outputs"])
    for family in ("yolov8", "yolov8-cspnext"):
        old_best = train_yolo(records[:1], records[1:], annotations, stats, tmp_path / family,
                              family=family, pretrained=None, epochs=1, batch_size=1,
                              effective_batch=1, size=64, device="cpu")
        assert old_best.exists()
