"""Tests for Google Gemini integration."""

import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch

import pytest

from mindroom.google_gemini import MindRoomGoogleGemini
from mindroom.model_loading import get_model_instance
from src.mindroom.config.main import Config
from src.mindroom.constants import RuntimePaths, resolve_runtime_paths


def _config_with_runtime_paths() -> tuple[Config, RuntimePaths]:
    runtime_root = Path(tempfile.mkdtemp())
    runtime_paths = resolve_runtime_paths(
        config_path=runtime_root / "config.yaml",
        storage_path=runtime_root / "mindroom_data",
        process_env={},
    )
    return Config.validate_with_runtime({}, runtime_paths), runtime_paths


class TestGeminiIntegration:
    """Test Google Gemini model integration."""

    def test_gemini_provider_creates_gemini_instance(self) -> None:
        """Test that 'gemini' provider creates a Gemini instance."""
        config, runtime_paths = _config_with_runtime_paths()
        config.models = {
            "test_model": MagicMock(
                provider="gemini",
                id="gemini-3.6-flash",
                host=None,
            ),
        }

        with patch.dict("os.environ", {"GOOGLE_API_KEY": "test-key"}):
            model = get_model_instance(config, runtime_paths, "test_model")
            assert isinstance(model, MindRoomGoogleGemini)
            assert model.id == "gemini-3.6-flash"
            assert model.provider == "Google"

    def test_google_provider_creates_gemini_instance(self) -> None:
        """Test that 'google' provider also creates a Gemini instance."""
        config, runtime_paths = _config_with_runtime_paths()
        config.models = {
            "test_model": MagicMock(
                provider="google",
                id="gemini-3.5-flash-lite",
                host=None,
            ),
        }

        with patch.dict("os.environ", {"GOOGLE_API_KEY": "test-key"}):
            model = get_model_instance(config, runtime_paths, "test_model")
            assert isinstance(model, MindRoomGoogleGemini)
            assert model.id == "gemini-3.5-flash-lite"
            assert model.provider == "Google"

    def test_gemini_api_key_environment_variable(self) -> None:
        """Test that GOOGLE_API_KEY is set from credentials manager."""
        config, runtime_paths = _config_with_runtime_paths()
        config.models = {
            "test_model": MagicMock(
                provider="gemini",
                id="gemini-3.6-flash",
                host=None,
            ),
        }

        with patch("mindroom.model_loading.get_api_key_for_provider") as mock_get_api_key:
            mock_get_api_key.return_value = "test-google-api-key"
            with patch.dict("os.environ", {}, clear=True):
                get_model_instance(config, runtime_paths, "test_model")
                # Check that the API key was retrieved for gemini
                mock_get_api_key.assert_called_with("gemini", runtime_paths=runtime_paths)

    def test_unsupported_provider_raises_error(self) -> None:
        """Test that unsupported providers raise appropriate errors."""
        config, runtime_paths = _config_with_runtime_paths()
        config.models = {
            "test_model": MagicMock(
                provider="unsupported_provider",
                id="some-model",
                host=None,
            ),
        }

        with pytest.raises(ValueError, match="Unsupported AI provider: unsupported_provider"):
            get_model_instance(config, runtime_paths, "test_model")

    def test_gemini_models_in_config(self) -> None:
        """Test that Gemini models can be configured properly."""
        config, runtime_paths = _config_with_runtime_paths()

        # Test various Gemini model configurations
        gemini_configs = [
            ("gemini", "gemini-3.6-flash"),
            ("gemini", "gemini-3.5-flash-lite"),
            ("google", "gemini-3.1-pro-preview"),
            ("google", "gemini-3.1-flash-image"),
        ]

        for provider, model_id in gemini_configs:
            config.models = {
                "test": MagicMock(
                    provider=provider,
                    id=model_id,
                    host=None,
                ),
            }

            with patch.dict("os.environ", {"GOOGLE_API_KEY": "test-key"}):
                model = get_model_instance(config, runtime_paths, "test")
                assert isinstance(model, MindRoomGoogleGemini)
                assert model.id == model_id
                assert model.provider == "Google"
