"""End-to-end RT-DETR test against the real mirror.

Downloads weights at the pinned SHA, resolves device auto → cuda/mps/cpu,
runs inference on a small synthetic RGB image, and asserts shape invariants
on the returned `DetectionResult`.

Model quality is NOT tested here — a solid-color synthetic image legitimately
has zero detections. This test proves the pipeline runs; accuracy regression
testing would belong in a separate benchmark suite outside v0.1 scope.
"""

from __future__ import annotations

import numpy as np
import pytest
import torch
from PIL import Image

import acaua

REPO_ID = "CondadosAI/rtdetr_r50vd"


def _synthetic_rgb(h: int = 128, w: int = 128) -> Image.Image:
    arr = np.stack(
        [
            np.full((h, w), 120, dtype=np.uint8),
            np.full((h, w), 100, dtype=np.uint8),
            np.full((h, w), 115, dtype=np.uint8),  # R-B diff=5, under BGR threshold
        ],
        axis=-1,
    )
    return Image.fromarray(arr, mode="RGB")


@pytest.fixture(scope="module")
def model() -> acaua.Model:
    return acaua.Model.from_pretrained(REPO_ID)


@pytest.mark.e2e
class TestLoad:
    def test_repo_id_stored(self, model: acaua.Model) -> None:
        assert model.repo_id == REPO_ID

    def test_device_resolved(self, model: acaua.Model) -> None:
        assert isinstance(model.device, torch.device)


@pytest.mark.e2e
class TestPredict:
    def test_single_image_returns_detection_result(self, model: acaua.Model) -> None:
        out = model.predict(_synthetic_rgb())
        assert isinstance(out, acaua.DetectionResult)
        assert out.boxes.ndim == 2 and out.boxes.shape[-1] == 4
        assert out.labels.ndim == 1
        assert out.scores.ndim == 1

    def test_batch_returns_list(self, model: acaua.Model) -> None:
        out = model.predict([_synthetic_rgb(), _synthetic_rgb()], batch_size=2)
        assert isinstance(out, list)
        assert len(out) == 2
        assert all(isinstance(r, acaua.DetectionResult) for r in out)

    def test_supervision_conversion(self, model: acaua.Model) -> None:
        import supervision as sv

        out = model.predict(_synthetic_rgb())
        assert isinstance(out, acaua.DetectionResult)
        det = out.to_supervision()
        assert isinstance(det, sv.Detections)

    def test_tensor_dtypes(self, model: acaua.Model) -> None:
        out = model.predict(_synthetic_rgb())
        assert isinstance(out, acaua.DetectionResult)
        assert out.boxes.dtype == torch.float32
        assert out.labels.dtype == torch.int64
        assert out.scores.dtype == torch.float32
