"""Post-processing, against hand-built tensors. No model, no ORT session.

These are the arithmetic the measured 98.8/98.8 depends on: the top-k selection
rule, the cxcywh -> pixel conversion, the class-slot lookup. A transcription bug
in any of them produces detections that are entirely plausible and entirely
wrong — the shape `docs/runbooks/cctv-detector-tier.md` §5 rule 2 records, where
a class-index fallback scored BUSES as people for a whole run.

Skipped rather than failed without numpy: the wire contract in `test_server.py`
needs no third-party package at all and is the half that must always run.
"""

from __future__ import annotations

import unittest

try:
    import numpy as np

    from trillboards_detector.session import (
        ModelContractError,
        _read_graph_spec,
        _sigmoid,
        postprocess,
    )

    HAVE_NUMPY = True
except ImportError:  # pragma: no cover - exercised only on a bare interpreter
    HAVE_NUMPY = False


def _logits(pairs, num_queries=3, num_classes=91):
    """Build a logit tensor whose sigmoid gives EXACTLY the requested scores."""
    out = np.full((1, num_queries, num_classes), -30.0, dtype=np.float32)
    for (q, c), score in pairs.items():
        out[0, q, c] = np.log(score / (1.0 - score))
    return out


def _boxes(rows, num_queries=3):
    out = np.zeros((1, num_queries, 4), dtype=np.float32)
    for q, box in rows.items():
        out[0, q] = box
    return out


@unittest.skipUnless(HAVE_NUMPY, "numpy is not installed")
class TestPostprocess(unittest.TestCase):
    def test_cxcywh_normalised_becomes_pixels_of_the_submitted_frame(self):
        # Centre of a 640x480 frame, half its width and height.
        batch = postprocess(
            _boxes({0: (0.5, 0.5, 0.5, 0.5)}),
            _logits({(0, 1): 0.9}),
            frame_w=640,
            frame_h=480,
            min_confidence=0.25,
        )
        self.assertEqual(len(batch.detections), 1)
        d = batch.detections[0]
        self.assertEqual(d.label, "person")
        self.assertAlmostEqual(d.confidence, 0.9, places=5)
        self.assertAlmostEqual(d.x, 160.0, places=3)
        self.assertAlmostEqual(d.y, 120.0, places=3)
        self.assertAlmostEqual(d.width, 320.0, places=3)
        self.assertAlmostEqual(d.height, 240.0, places=3)

    def test_a_box_running_off_the_frame_is_clamped_to_it(self):
        batch = postprocess(
            _boxes({0: (0.0, 0.0, 0.5, 0.5)}),  # centred on the top-left corner
            _logits({(0, 1): 0.9}),
            frame_w=100,
            frame_h=100,
            min_confidence=0.25,
        )
        d = batch.detections[0]
        self.assertEqual((d.x, d.y), (0.0, 0.0))
        self.assertAlmostEqual(d.width, 25.0, places=3)
        self.assertAlmostEqual(d.height, 25.0, places=3)

    def test_class_slot_1_is_person_and_slot_3_is_car(self):
        batch = postprocess(
            _boxes({0: (0.5, 0.5, 0.2, 0.2), 1: (0.3, 0.3, 0.2, 0.2)}),
            _logits({(0, 1): 0.9, (1, 3): 0.8}),
            frame_w=200,
            frame_h=200,
            min_confidence=0.25,
        )
        self.assertEqual(sorted(d.label for d in batch.detections), ["car", "person"])

    def test_below_threshold_is_dropped_strictly_greater_than(self):
        """`PostProcess` filters `scores > threshold`. Exactly on the threshold
        is OUT, and that has to match: the operating point in the runbook was
        chosen against this comparison, not a >=."""
        args = (_boxes({0: (0.5, 0.5, 0.2, 0.2)}), _logits({(0, 1): 0.5}), 100, 100)
        self.assertEqual(len(postprocess(*args, min_confidence=0.4).detections), 1)
        self.assertEqual(len(postprocess(*args, min_confidence=0.5).detections), 0)

    def test_an_unnamed_class_slot_is_dropped_and_counted_never_labelled(self):
        """Eleven of the ninety-one slots are COCO id gaps. Slot 12 is one.

        Naming it anything would be exactly the fabrication the runbook forbids,
        and dropping it silently is the failure this whole stack keeps hitting.
        So: dropped, and counted where `/health` publishes it.
        """
        batch = postprocess(
            _boxes({0: (0.5, 0.5, 0.2, 0.2)}),
            _logits({(0, 12): 0.9}),
            frame_w=100,
            frame_h=100,
            min_confidence=0.25,
        )
        self.assertEqual(batch.detections, [])
        self.assertEqual(batch.unnamed_class_dropped, 1)

    def test_a_zero_extent_box_is_dropped_and_counted(self):
        """A box with no width covers no pixels and would make the CLIENT reject
        the entire frame's result. Dropping it costs one artifact; emitting it
        costs every other detection in the frame."""
        batch = postprocess(
            _boxes({0: (0.5, 0.5, 0.0, 0.4), 1: (0.5, 0.5, 0.4, 0.4)}),
            _logits({(0, 1): 0.9, (1, 1): 0.8}),
            frame_w=100,
            frame_h=100,
            min_confidence=0.25,
        )
        self.assertEqual(len(batch.detections), 1)
        self.assertEqual(batch.degenerate_dropped, 1)

    def test_the_class_filter_runs_at_the_service(self):
        args = (
            _boxes({0: (0.5, 0.5, 0.2, 0.2), 1: (0.3, 0.3, 0.2, 0.2)}),
            _logits({(0, 1): 0.9, (1, 3): 0.8}),
            100,
            100,
            0.25,
        )
        self.assertEqual([d.label for d in postprocess(*args, wanted={"car"}).detections], ["car"])
        self.assertEqual(len(postprocess(*args, wanted=None).detections), 2)

    def test_selection_keeps_the_top_300_pairs_before_thresholding(self):
        """`num_select=300` is applied FIRST, exactly as upstream does.

        Thresholding first would return rows the measured arm never saw on a
        busy frame — a difference invisible on an empty one and decisive on a
        crowded one.
        """
        # 400 queries each with one class above the threshold: only 300 survive.
        scores = {(q, 1): 0.9 for q in range(400)}
        batch = postprocess(
            _boxes({q: (0.5, 0.5, 0.2, 0.2) for q in range(400)}, num_queries=400),
            _logits(scores, num_queries=400),
            frame_w=100,
            frame_h=100,
            min_confidence=0.25,
        )
        self.assertEqual(len(batch.detections), 300)

    def test_confidences_are_always_inside_the_unit_interval(self):
        rng = np.random.default_rng(7)
        logits = rng.normal(0.0, 40.0, size=(1, 300, 91)).astype(np.float32)
        boxes = np.abs(rng.normal(0.4, 0.2, size=(1, 300, 4))).astype(np.float32)
        batch = postprocess(boxes, logits, 640, 480, 0.0)
        for d in batch.detections:
            self.assertGreaterEqual(d.confidence, 0.0)
            self.assertLessEqual(d.confidence, 1.0)

    def test_sigmoid_does_not_overflow_on_a_large_negative_logit(self):
        out = _sigmoid(np.array([-800.0, 800.0, 0.0], dtype=np.float32))
        self.assertTrue(np.all(np.isfinite(out)))
        self.assertAlmostEqual(float(out[2]), 0.5, places=6)


class _FakeIo:
    def __init__(self, name, shape):
        self.name = name
        self.shape = shape


class _FakeSession:
    def __init__(self, inputs, outputs):
        self._inputs = inputs
        self._outputs = outputs

    def get_inputs(self):
        return self._inputs

    def get_outputs(self):
        return self._outputs

    def get_providers(self):
        return ["CPUExecutionProvider"]


@unittest.skipUnless(HAVE_NUMPY, "numpy is not installed")
class TestGraphContract(unittest.TestCase):
    """A graph we cannot label must take the service UNHEALTHY, not relabel boxes.

    An off-by-one on the class axis renames every object in the venue and every
    number stays plausible — the `yolov8_nano` failure with the sign flipped:
    instead of a model offered and never loadable, a model loaded and never
    right.
    """

    GOOD_IN = [_FakeIo("input", [1, 3, 576, 576])]
    GOOD_OUT = [_FakeIo("dets", [1, 300, 4]), _FakeIo("labels", [1, 300, 91])]

    def test_accepts_the_shipped_graph(self):
        spec = _read_graph_spec(_FakeSession(self.GOOD_IN, self.GOOD_OUT))
        self.assertEqual((spec.width, spec.height), (576, 576))
        self.assertEqual(spec.num_classes, 91)
        self.assertEqual(spec.input_name, "input")

    def test_refuses_a_class_axis_the_label_map_does_not_describe(self):
        out = [_FakeIo("dets", [1, 300, 4]), _FakeIo("labels", [1, 300, 80])]
        with self.assertRaisesRegex(ModelContractError, "80 class slots"):
            _read_graph_spec(_FakeSession(self.GOOD_IN, out))

    def test_refuses_a_dynamic_resolution(self):
        """imgsz is one of the two numbers a detector arm is meaningless
        without (§5 rule 1). A dynamic axis means it is not recoverable from
        the artifact at all."""
        dyn = [_FakeIo("input", [1, 3, "height", "width"])]
        with self.assertRaisesRegex(ModelContractError, "fixed input resolution"):
            _read_graph_spec(_FakeSession(dyn, self.GOOD_OUT))

    def test_refuses_unexpected_output_names(self):
        out = [_FakeIo("boxes", [1, 300, 4]), _FakeIo("scores", [1, 300, 91])]
        with self.assertRaisesRegex(ModelContractError, "dets"):
            _read_graph_spec(_FakeSession(self.GOOD_IN, out))

    def test_refuses_a_multi_input_graph(self):
        """An open-vocabulary model would carry a text input. Per the runbook
        those do not survive ONNX export at all — one exported artifact is one
        class list, permanently — so a second input means this is not the model
        the label map belongs to."""
        two = [_FakeIo("images", [1, 3, 576, 576]), _FakeIo("text", [1, 512])]
        with self.assertRaisesRegex(ModelContractError, "one graph input"):
            _read_graph_spec(_FakeSession(two, self.GOOD_OUT))


if __name__ == "__main__":
    unittest.main()
