"""Tests for llmhosts.version -- version info and tier detection."""

from __future__ import annotations

from unittest.mock import patch

from llmhosts.version import detect_tier, get_version_info


class TestGetVersionInfo:
    def test_returns_required_keys(self) -> None:
        info = get_version_info()
        assert "version" in info
        assert "python" in info
        assert "tier" in info
        assert "platform" in info

    def test_version_is_string(self) -> None:
        info = get_version_info()
        assert isinstance(info["version"], str)
        assert len(info["version"]) > 0

    def test_python_version_present(self) -> None:
        info = get_version_info()
        assert "3." in info["python"]  # Python 3.x

    def test_tier_is_valid(self) -> None:
        info = get_version_info()
        assert info["tier"] in ("core", "smart", "full")

    def test_platform_not_empty(self) -> None:
        info = get_version_info()
        assert len(info["platform"]) > 0


class TestDetectTier:
    def test_core_when_no_faiss(self) -> None:
        with patch.dict("sys.modules", {"faiss": None, "onnxruntime": None}):

            def raise_import(name, *args, **kwargs):
                raise ImportError(f"No module {name}")

            with patch("builtins.__import__", side_effect=raise_import):
                # The function tries import faiss then onnxruntime
                result = detect_tier()
                assert result in ("core", "smart", "full")  # depends on actual env

    def test_full_when_torch_available(self) -> None:
        # Mock both faiss and onnxruntime available, then torch available
        import types

        fake_faiss = types.ModuleType("faiss")
        fake_onnx = types.ModuleType("onnxruntime")
        fake_torch = types.ModuleType("torch")

        with (
            patch.dict("sys.modules", {"faiss": fake_faiss, "onnxruntime": fake_onnx, "torch": fake_torch}),
        ):
            result = detect_tier()
            assert result == "full"

    def test_smart_when_faiss_no_torch(self) -> None:
        import types

        fake_faiss = types.ModuleType("faiss")
        fake_onnx = types.ModuleType("onnxruntime")

        original_import = __builtins__.__import__ if hasattr(__builtins__, "__import__") else __import__

        def selective_import(name, *args, **kwargs):
            if name == "torch":
                raise ImportError("No module torch")
            return original_import(name, *args, **kwargs)

        with (
            patch.dict("sys.modules", {"faiss": fake_faiss, "onnxruntime": fake_onnx}),
            patch("builtins.__import__", side_effect=selective_import),
        ):
            result = detect_tier()
            assert result == "smart"
