"""
Tests for ModelsClient.
"""

from unittest.mock import MagicMock, patch

import grpc
import pytest

from daisi.clients.models import ModelsClient
from daisi.config import DaisiConfig
from daisi.exceptions import DaisiError


def create_grpc_error(details: str = "Test error") -> grpc.RpcError:
    """Create a mock gRPC error with details method."""
    error = grpc.RpcError()
    error.details = MagicMock(return_value=details)
    return error


class TestModelsClientInitialization:
    """Test ModelsClient initialization."""

    def test_init_with_config(self) -> None:
        """Test initialization with config."""
        config = DaisiConfig(client_key="test-key")
        client = ModelsClient(config)
        assert client.config == config
        assert client._stub is None

    def test_stub_lazy_initialization(self) -> None:
        """Test stub is lazily initialized."""
        config = DaisiConfig(client_key="test-key")
        client = ModelsClient(config)

        with patch.object(client, "_get_channel") as mock_get_channel:
            mock_channel = MagicMock()
            mock_get_channel.return_value = mock_channel

            stub = client.stub
            assert stub is not None
            mock_get_channel.assert_called_once()


class TestModelsClientGetRequiredModels:
    """Test ModelsClient get_required_models method."""

    def test_get_required_models_success(self) -> None:
        """Test getting required models successfully."""
        config = DaisiConfig(client_key="test-key")
        client = ModelsClient(config)

        mock_stub = MagicMock()
        mock_response = MagicMock()
        mock_stub.GetRequiredModels.return_value = mock_response

        client._stub = mock_stub
        result = client.get_required_models()

        assert result == mock_response
        mock_stub.GetRequiredModels.assert_called_once()

    def test_get_required_models_grpc_error(self) -> None:
        """Test get required models with gRPC error."""
        config = DaisiConfig(client_key="test-key")
        client = ModelsClient(config)

        mock_stub = MagicMock()
        mock_stub.GetRequiredModels.side_effect = create_grpc_error()

        client._stub = mock_stub
        with pytest.raises(DaisiError, match="Failed to get required models"):
            client.get_required_models()
