"""
External services abstraction layer for BaoLife.

Provides interfaces for external services (like OpenAI conversations),
allowing switching between real API calls (production) and mocks (testing).
"""
import os
from typing import Protocol, Optional, Dict, List


class IConversationService(Protocol):
    """
    Interface for conversation services.

    Defines the contract that all conversation service implementations must follow.
    """

    def get_conversation_response(self, character_name: str, prompt: str,
                                  context: Optional[Dict] = None) -> str:
        """Get a conversation response."""
        ...


class OpenAIConversationService:
    """
    OpenAI conversation service implementation (production).

    Uses the real OpenAI API for generating conversation responses.
    """

    def __init__(self, api_key: Optional[str] = None):
        """
        Initialize OpenAI conversation service.

        Args:
            api_key: Optional API key (uses environment variable if not provided)
        """
        self.api_key = api_key or os.environ.get('OPENAI_API_KEY')

    def get_conversation_response(self, character_name: str, prompt: str,
                                  context: Optional[Dict] = None) -> str:
        """
        Get a conversation response from OpenAI API.

        Args:
            character_name: Name of the character speaking
            prompt: The conversation prompt
            context: Optional context dictionary

        Returns:
            Generated response from OpenAI
        """
        # This is a placeholder for the actual OpenAI integration
        # The real implementation would be in conversationEvents.py
        # For now, we'll provide a simple fallback

        try:
            # Try to import and use existing OpenAI logic if available
            # This would need to be implemented based on existing code
            return f"{character_name} responds to: {prompt}"
        except Exception as e:
            print(f"Error getting OpenAI response: {e}")
            return f"Error generating response for {character_name}"

    def __repr__(self):
        return "OpenAIConversationService()"


def conversation_service_factory(test_mode: Optional[bool] = None) -> IConversationService:
    """
    Factory function to create appropriate conversation service.

    Args:
        test_mode: Force test mode (True) or production mode (False).
                  If None, uses environment variables.

    Returns:
        Conversation service implementation
    """
    # Determine test mode
    if test_mode is None:
        # Check both BAOLIFE_TEST_MODE and USE_MOCK_OPENAI
        test_mode = (
            os.environ.get('BAOLIFE_TEST_MODE', 'false').lower() == 'true' or
            os.environ.get('USE_MOCK_OPENAI', 'false').lower() == 'true'
        )

    if test_mode:
        # Import here to avoid circular dependencies
        from tests.mocks.services_mock import MockConversationService
        return MockConversationService()
    else:
        return OpenAIConversationService()


def get_conversation_service() -> IConversationService:
    """
    Get the current conversation service.

    Returns:
        Conversation service implementation
    """
    return conversation_service_factory()
