import pytest
import torch

from pallet.models.rfdetr import RFDETRDetector
from pallet.experiments.dataset import SampleMeta


@pytest.mark.filterwarnings("ignore:.*pretrain_weights=None.*")
def test_rf_detr_four_channel_forward_loss_and_decode():
    torch.set_num_threads(1)
    detector = RFDETRDetector(resolution=64, pretrained=False)
    images = torch.rand(1, 4, 64, 64)
    batch = {"img": images, "batch_idx": torch.zeros(1, dtype=torch.long),
             "cls": torch.zeros((1, 1)),
             "bboxes": torch.tensor([[0.5, 0.5, 0.2, 0.2]])}
    loss, _ = detector.loss(batch)
    assert torch.isfinite(loss)
    loss.backward()
    assert any(p.grad is not None for p in detector.parameters())
    detector.eval()
    with torch.inference_mode():
        boxes = detector.decode(images, SampleMeta("x", (64, 64), 1, (0, 0)), conf=0.9)
    assert all(len(box) == 4 and 0 <= score <= 1 for box, score in boxes)
