"""tests/test_trust_router.py — Unit tests for SmartRouter."""
import pytest
from unittest.mock import MagicMock, patch

pytestmark = pytest.mark.unit


def _make_mock_guard(risk=0.3):
    guard = MagicMock()
    guard.is_fitted = True
    guard.predict_risk = MagicMock(return_value=risk)
    return guard


class TestImport:
    def test_import(self):
        from llm_guard.trust.router import SmartRouter
        assert SmartRouter is not None

    def test_import_result(self):
        from llm_guard.trust.router import RouterResult
        assert RouterResult is not None

    def test_import_default_cascade(self):
        from llm_guard.trust.router import DEFAULT_CASCADE
        assert len(DEFAULT_CASCADE) >= 2


class TestInstantiation:
    def test_basic_construction(self):
        from llm_guard.trust.router import SmartRouter
        guard = _make_mock_guard()
        router = SmartRouter(guard)
        assert router.guard is guard

    def test_too_short_cascade_raises(self):
        from llm_guard.trust.router import SmartRouter
        guard = _make_mock_guard()
        with pytest.raises(ValueError):
            SmartRouter(guard, cascade=[{"model": "only-one", "input_cost": 1.0,
                                          "output_cost": 1.0, "tier": "low"}])

    def test_custom_cascade(self):
        from llm_guard.trust.router import SmartRouter
        guard = _make_mock_guard()
        cascade = [
            {"model": "cheap", "input_cost": 0.5, "output_cost": 2.0, "tier": "low"},
            {"model": "expensive", "input_cost": 5.0, "output_cost": 20.0, "tier": "high"},
        ]
        router = SmartRouter(guard, cascade=cascade)
        assert len(router.cascade) == 2


class TestCostStats:
    def test_initial_cost_stats(self):
        from llm_guard.trust.router import SmartRouter
        guard = _make_mock_guard()
        router = SmartRouter(guard)
        stats = router.get_cost_stats()
        assert isinstance(stats, dict)
        assert "total_cost_usd" in stats

    def test_cost_stats_zero_initially(self):
        from llm_guard.trust.router import SmartRouter
        guard = _make_mock_guard()
        router = SmartRouter(guard)
        stats = router.get_cost_stats()
        assert stats["total_cost_usd"] == pytest.approx(0.0)


class TestRouterResult:
    def test_dataclass_creation(self):
        from llm_guard.trust.router import RouterResult
        r = RouterResult(
            answer="Paris",
            model_used="claude-haiku-4-5-20251001",
            confidence="high",
            risk_score=0.2,
        )
        assert r.answer == "Paris"
        assert r.confidence == "high"
        assert not r.was_retried
