"""Tests for domestic interconnect adapters (Task1.5 baseline)."""

from __future__ import annotations

import pytest

from sagellm_comm.interconnect import (
    CXLAdapter,
    InterconnectKind,
    RDMAAdapter,
    UBAdapter,
    select_best_available_interconnect,
)


def test_cxl_default_available(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.delenv("SAGELLM_COMM_ENABLE_CXL", raising=False)

    adapter = CXLAdapter()
    assert adapter.is_available() is True

    profile = adapter.profile()
    assert profile.kind == InterconnectKind.CXL
    assert profile.bandwidth_gbps > 0
    assert profile.latency_us > 0


def test_ub_opt_in(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("SAGELLM_COMM_ENABLE_UB", "0")
    adapter = UBAdapter()
    assert adapter.is_available() is False

    monkeypatch.setenv("SAGELLM_COMM_ENABLE_UB", "1")
    assert adapter.is_available() is True
    assert adapter.profile().kind == InterconnectKind.UB


def test_rdma_force_enable(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("SAGELLM_COMM_ENABLE_RDMA", "1")
    adapter = RDMAAdapter()

    assert adapter.is_available() is True
    profile = adapter.profile()
    assert profile.kind == InterconnectKind.RDMA
    assert profile.availability_source == "env:SAGELLM_COMM_ENABLE_RDMA"


def test_selector_prefers_higher_bandwidth(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("SAGELLM_COMM_ENABLE_CXL", "1")
    monkeypatch.setenv("SAGELLM_COMM_ENABLE_UB", "1")
    monkeypatch.delenv("SAGELLM_COMM_ENABLE_RDMA", raising=False)

    profile = select_best_available_interconnect([CXLAdapter(), UBAdapter()])
    assert profile.kind == InterconnectKind.CXL


def test_selector_fail_fast_no_adapter(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setenv("SAGELLM_COMM_ENABLE_CXL", "0")
    monkeypatch.setenv("SAGELLM_COMM_ENABLE_UB", "0")
    monkeypatch.setenv("SAGELLM_COMM_ENABLE_RDMA", "0")

    with pytest.raises(RuntimeError, match="No domestic interconnect adapter is available"):
        select_best_available_interconnect([CXLAdapter(), UBAdapter()])


def test_payload_validation_fail_fast() -> None:
    adapter = CXLAdapter()
    with pytest.raises(ValueError, match="payload_bytes must be > 0"):
        adapter.validate_payload_bytes(0)
