"""Integration tests for GCP Cloud Logging exporter."""

import os
import pytest
from unittest.mock import patch, Mock, MagicMock
from mca_sdk import MCAClient


@pytest.fixture
def mock_gcp_logging():
    """Mock google-cloud-logging for tests."""
    mock_cloud_logging = MagicMock()
    mock_client = Mock()
    mock_logger = Mock()
    mock_client.logger.return_value = mock_logger
    mock_cloud_logging.Client.return_value = mock_client

    with patch.dict("sys.modules", {"google.cloud.logging": mock_cloud_logging}):
        yield mock_cloud_logging, mock_client, mock_logger


class TestGCPLoggingIntegration:
    """Test GCP Cloud Logging integration with MCAClient."""

    def test_gcp_logging_disabled_by_default(self):
        """Test that GCP logging is disabled by default."""
        with patch.dict(
            os.environ,
            {
                "MCA_SERVICE_NAME": "test-service",
                "MCA_MODEL_ID": "test-model",
                "MCA_TEAM_NAME": "test-team",
            },
        ):
            client = MCAClient()
            assert client.config.gcp_logging_enabled is False
            client.shutdown()

    def test_gcp_logging_enabled_via_config(self, mock_gcp_logging):
        """Test enabling GCP logging via configuration."""
        mock_cloud_logging, mock_client, mock_logger = mock_gcp_logging

        with patch.dict(
            os.environ,
            {
                "MCA_SERVICE_NAME": "test-service",
                "MCA_MODEL_ID": "test-model",
                "MCA_TEAM_NAME": "test-team",
                "MCA_GCP_LOGGING_ENABLED": "true",
                "MCA_GCP_PROJECT_ID": "test-project-123",
                "MCA_GCP_LOG_NAME": "test-log",
            },
        ):
            client = MCAClient()
            assert client.config.gcp_logging_enabled is True
            assert client.config.gcp_project_id == "test-project-123"
            assert client.config.gcp_log_name == "test-log"
            client.shutdown()

    def test_gcp_logging_validation_error(self):
        """Test that missing project_id raises ConfigurationError."""
        from mca_sdk.utils.exceptions import ConfigurationError

        with patch.dict(
            os.environ,
            {
                "MCA_SERVICE_NAME": "test-service",
                "MCA_MODEL_ID": "test-model",
                "MCA_TEAM_NAME": "test-team",
                "MCA_GCP_LOGGING_ENABLED": "true",
                # Missing MCA_GCP_PROJECT_ID
            },
        ):
            with pytest.raises(ConfigurationError, match="gcp_project_id is required"):
                MCAClient()

    def test_end_to_end_log_export(self, mock_gcp_logging):
        """Test end-to-end log export with team, model_id, environment metadata."""
        mock_cloud_logging, mock_client, mock_logger = mock_gcp_logging

        with patch.dict(
            os.environ,
            {
                "MCA_SERVICE_NAME": "readmission-model",
                "MCA_MODEL_ID": "mdl-001",
                "MCA_TEAM_NAME": "clinical-ai",
                "MCA_GCP_LOGGING_ENABLED": "true",
                "MCA_GCP_PROJECT_ID": "my-project-123",
                "MCA_GCP_LOG_NAME": "mca-logs",
                "MCA_GCP_RESOURCE_TYPE": "k8s_container",
            },
        ):
            client = MCAClient()

            # Record a prediction to generate logs
            client.record_prediction(latency=0.25, prediction_id="pred-001", model_version="v2.0")

            # Shutdown to flush logs
            client.shutdown()

            # Verify Cloud Logging client was initialized with correct parameters
            mock_cloud_logging.Client.assert_called_once_with(
                project="my-project-123", credentials=None
            )

            # Verify logger was created with correct log name
            mock_client.logger.assert_called_once_with("mca-logs")

            # Verify logs were exported (at least one log_struct call)
            assert mock_logger.log_struct.call_count >= 1

            # Check that logs contain expected metadata
            # (Resource attributes should be in labels with "resource." prefix)
            calls = mock_logger.log_struct.call_args_list

            # At least one call should have resource attributes
            has_service_name = any(
                "resource.service.name" in call[0][0].get("labels", {}) for call in calls
            )
            assert has_service_name, "Logs should include resource.service.name in labels"
