"""
Conversation handler to ensure proper storage of both user and assistant messages
"""

import logging
from typing import Dict, Any, Optional
from utils.optimized_conversation_memory import optimized_conversation_memory

# Set up logger
logger = logging.getLogger("mango_ai_agent")

class ConversationHandler:
    """Handles conversation storage and retrieval with proper error handling"""
    
    @staticmethod
    def add_user_message(conversation_id: str, content: str) -> bool:
        """
        Add a user message to the conversation
        
        Args:
            conversation_id: The conversation ID
            content: The message content
            
        Returns:
            bool: True if successful, False otherwise
        """
        try:
            optimized_conversation_memory.add_message(
                conversation_id=conversation_id,
                content=content,
                role="user"
            )
            logger.info(f"Added user message to conversation {conversation_id[:8]}")
            return True
        except Exception as e:
            logger.error(f"Error adding user message to conversation {conversation_id[:8]}: {str(e)}")
            return False
    
    @staticmethod
    def add_assistant_message(conversation_id: str, content: str) -> bool:
        """
        Add an assistant message to the conversation
        
        Args:
            conversation_id: The conversation ID
            content: The message content
            
        Returns:
            bool: True if successful, False otherwise
        """
        try:
            optimized_conversation_memory.add_message(
                conversation_id=conversation_id,
                content=content,
                role="assistant"
            )
            logger.info(f"Added assistant message to conversation {conversation_id[:8]}")
            return True
        except Exception as e:
            logger.error(f"Error adding assistant message to conversation {conversation_id[:8]}: {str(e)}")
            return False
    
    @staticmethod
    def get_conversation_history(conversation_id: str) -> str:
        """
        Get the conversation history as a formatted string
        
        Args:
            conversation_id: The conversation ID
            
        Returns:
            str: The formatted conversation history
        """
        try:
            return optimized_conversation_memory.get_context_string(conversation_id)
        except Exception as e:
            logger.error(f"Error getting conversation history for {conversation_id[:8]}: {str(e)}")
            return ""
    
    @staticmethod
    def create_conversation(conversation_id: Optional[str] = None) -> str:
        """
        Create a new conversation
        
        Args:
            conversation_id: Optional conversation ID
            
        Returns:
            str: The conversation ID
        """
        try:
            conversation = optimized_conversation_memory.create_conversation(conversation_id)
            logger.info(f"Created new conversation with ID: {conversation.conversation_id[:8]}")
            return conversation.conversation_id
        except Exception as e:
            logger.error(f"Error creating conversation: {str(e)}")
            # Generate a fallback conversation ID if needed
            import uuid
            fallback_id = conversation_id or str(uuid.uuid4())
            return fallback_id

# Create a singleton instance
conversation_handler = ConversationHandler()
