"""Tests for util module: _fetch_available_gpu_models."""

from unittest.mock import MagicMock

import pytest

from aiauto.util import _fetch_available_gpu_models


class TestFetchAvailableGpuModels:
    """Test _fetch_available_gpu_models function."""

    def test_returns_model_names_with_underscore(self):
        """GPU flavor names are converted from kebab-case to underscore."""
        mock_stub = MagicMock()
        mock_response = MagicMock()

        flavor1 = MagicMock()
        flavor1.name = "gpu-3090"
        flavor2 = MagicMock()
        flavor2.name = "gpu-4090"
        mock_response.gpu_flavors = [flavor1, flavor2]
        mock_stub.ListGpuFlavors.return_value = mock_response

        result = _fetch_available_gpu_models(mock_stub, (("authorization", "Bearer test"),))

        assert result == {"gpu_3090", "gpu_4090"}

    def test_empty_flavors_returns_empty_set(self):
        """Empty gpu_flavors list returns empty set."""
        mock_stub = MagicMock()
        mock_response = MagicMock()
        mock_response.gpu_flavors = []
        mock_stub.ListGpuFlavors.return_value = mock_response

        result = _fetch_available_gpu_models(mock_stub, (("authorization", "Bearer test"),))

        assert result == set()

    def test_rpc_failure_raises_value_error(self):
        """RPC call failure raises ValueError with descriptive message."""
        mock_stub = MagicMock()
        mock_stub.ListGpuFlavors.side_effect = ConnectionError("network down")

        with pytest.raises(ValueError, match="Failed to fetch available GPU models"):
            _fetch_available_gpu_models(mock_stub, (("authorization", "Bearer test"),))

    def test_name_without_hyphen_unchanged(self):
        """Flavor name without hyphens stays unchanged (just underscores won't apply)."""
        mock_stub = MagicMock()
        mock_response = MagicMock()
        flavor = MagicMock()
        flavor.name = "a100"
        mock_response.gpu_flavors = [flavor]
        mock_stub.ListGpuFlavors.return_value = mock_response

        result = _fetch_available_gpu_models(mock_stub, ())

        assert result == {"a100"}

    def test_metadata_passed_to_rpc_call(self):
        """Verify metadata is passed through to the gRPC call."""
        mock_stub = MagicMock()
        mock_response = MagicMock()
        mock_response.gpu_flavors = []
        mock_stub.ListGpuFlavors.return_value = mock_response

        metadata = (("authorization", "Bearer my-token"), ("x-client-version", "0.3.2"))
        _fetch_available_gpu_models(mock_stub, metadata)

        call_kwargs = mock_stub.ListGpuFlavors.call_args
        assert call_kwargs[1]["metadata"] == metadata
