import numpy as np
import torch

from pallet.experiments.dataset import (SampleMeta, augment_sensor, collate_pallet,
                                        letterbox_float, restore_boxes)
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


def test_letterbox_masks_and_box_inverse():
    image = np.zeros((96, 240, 4), np.float32)
    image[..., :2] = 0.5
    image[..., 2:] = 1
    image[:, :8, 2:] = 0
    output, scale, padding = letterbox_float(image, 640)
    assert output.shape == (4, 640, 640)
    assert torch.all(output[:2, :, :padding[0]] == 0)
    assert torch.all(output[:, 0, :] == 0)
    xyxy = np.array([[40, 20, 100, 70]], dtype=np.float32)
    projected = xyxy * scale + np.array([padding[0], padding[1], padding[0], padding[1]])
    recovered = restore_boxes(projected, SampleMeta("x", (96, 240), scale, padding))
    np.testing.assert_allclose(recovered, xyxy, atol=0.01)


def test_collate_handles_empty_negatives():
    image = torch.zeros((4, 64, 64))
    batch = collate_pallet([
        (image, torch.tensor([[0.5, 0.5, 0.2, 0.2]]), SampleMeta("a", (64, 64), 1, (0, 0))),
        (image, torch.empty((0, 4)), SampleMeta("b", (64, 64), 1, (0, 0))),
    ])
    assert batch["img"].shape == (2, 4, 64, 64)
    assert batch["batch_idx"].tolist() == [0]
    assert batch["bboxes"].shape == (1, 4)


def test_disputed_without_adjudication_is_not_training_data():
    frame = FrameAnnotation("f", "g", "dummy.png", 32, 32,
                            source_anchor_hash="synthetic-anchor", split="train")
    record_review(frame, Review("a", "needs_work"), status="pos",
                  boxes=[Box(2, 2, 10, 10)])
    record_review(frame, Review("b", "approve"))
    dataset = PalletDataset([FrameRecord("f", "g", "default", {},
                                         source_sha256="synthetic-anchor")],
                            AnnotationSet([frame]), NormalizationStats(1, 1), size=32)
    assert len(dataset) == 0


def test_augmentation_preserves_missing_signal_mask():
    np.random.seed(42)
    image = np.ones((32, 48, 4), dtype=np.float32)
    image[4:8, 5:12, 2] = 0
    image[8:10, 4:9, 3] = 0
    output = augment_sensor(image)
    assert output.shape == image.shape
    assert np.all(output[..., 0][output[..., 2] == 0] == 0)
    assert np.all(output[..., 1][output[..., 3] == 0] == 0)
    assert np.isfinite(output).all()


def test_mosaic_repositions_boxes_with_tiles(monkeypatch):
    dataset = PalletDataset.__new__(PalletDataset)
    dataset.rows = [None] * 4
    dataset.size = 64
    dataset.mosaic = True
    dataset._read_one = lambda index, tile_size: (
        torch.ones((4, tile_size, tile_size)),
        torch.tensor([[0.5, 0.5, 0.25, 0.25]]),
        SampleMeta(str(index), (tile_size, tile_size), 1, (0, 0)),
    )
    monkeypatch.setattr(np.random, "random", lambda: 0.0)
    monkeypatch.setattr(np.random, "choice", lambda *args, **kwargs: np.array([1, 2, 3]))
    image, boxes, _ = dataset[0]
    assert image.shape == (4, 64, 64)
    np.testing.assert_allclose(boxes[:, :2].numpy(),
                               [[0.25, 0.25], [0.75, 0.25], [0.25, 0.75], [0.75, 0.75]])
