from types import SimpleNamespace

import pytest

from pallet.experiments import evaluate as metrics
from pallet.experiments.evaluate import _count_matches, _rates, _select_threshold


def test_crowded_scene_matches_best_unused_reference():
    gt = [SimpleNamespace(x=0, y=0, width=10, height=10),
          SimpleNamespace(x=2, y=0, width=10, height=10)]
    # First prediction takes GT 0; second overlaps both, but must take unused GT 1.
    detections = [([0, 0, 10, 10], 0.9), ([1, 0, 11, 10], 0.8)]
    assert _count_matches(detections, gt, 0.25) == (2, 0, 0)
    assert _count_matches(detections + [([0, 0, 10, 10], 0.7)], gt, 0.25) == (2, 1, 0)


def test_undefined_empty_reference_rates_and_validation_threshold():
    assert _rates([{"tp": 0, "fp": 0, "fn": 0}])["recall"] is None
    assert _rates([{"tp": 0, "fp": 1, "fn": 0}])["precision"] == 0
    gt = SimpleNamespace(boxes=[SimpleNamespace(x=0, y=0, width=10, height=10)])
    validation = [(None, gt, None, [([0, 0, 10, 10], 0.6),
                                    ([20, 20, 30, 30], 0.4)])]
    assert _select_threshold(validation) == pytest.approx(0.6)


def test_empty_ground_truth_reports_undefined_ap_and_scene_metrics(monkeypatch):
    record = SimpleNamespace(frame_id="empty", domain="warehouse")
    row = SimpleNamespace(group_id="scene-a", image="empty.png", boxes=[])
    meta = SimpleNamespace(original_size=(10, 10))
    monkeypatch.setattr(metrics, "_collect", lambda *args: [
        (record, row, meta, [([0, 0, 5, 5], 0.9)])])

    class Model:
        def eval(self):
            return self

        def to(self, device):
            return self

    result = metrics.evaluate(Model(), object(), device="cpu", bootstrap_samples=8)
    assert result["AP50_95"] is None
    assert result["recall_at_threshold_iou_0.5"] is None
    assert result["per_frame"][0]["fp"] == 1
    assert result["per_domain"]["warehouse"]["false_positives_per_frame"] == 1
    assert result["bootstrap_ci"]["false_positives_per_frame"] == [1.0, 1.0]
