"""
Frontend integration module to connect the enhanced response generator with the frontend router
"""

import asyncio
from typing import Dict, Any, Optional

from utils.enhanced_response_generator import enhanced_response_generator
from utils.appointment_state import is_in_appointment_flow, update_appointment_flow
from utils.appointment_scheduler import check_and_schedule_if_ready
from utils.logger import Logger, app_logger

class FrontendIntegration:
    """Integration class to connect the enhanced response generator with the frontend router"""
    
    def __init__(self, logger: Optional[Logger] = None):
        """Initialize the frontend integration"""
        self.logger = logger or app_logger
    
    async def process_message(
        self, 
        message: str, 
        conversation_id: str,
        retrieved_info: Any,
        conversation_history: str = "",
        is_new_conversation: bool = False
    ) -> Dict[str, Any]:
        """
        Process a message using the enhanced response generator
        
        Args:
            message: The user's message
            conversation_id: The conversation ID
            retrieved_info: Retrieved information from the knowledge base
            conversation_history: Previous conversation history
            is_new_conversation: Flag indicating if this is a new conversation
            
        Returns:
            Dict[str, Any]: The generated response with sources
        """
        self.logger.info(f"Processing message for conversation {conversation_id}")
        
        # Check if we're in an appointment flow
        if is_in_appointment_flow(conversation_id):
            self.logger.info(f"In appointment flow for conversation {conversation_id}")
            
            # Extract information from the message if we're in an appointment flow
            # This will be handled by the enhanced_response_generator
            pass
        
        # Generate response using the enhanced response generator
        try:
            response = await enhanced_response_generator.generate_response(
                query=message,
                results=retrieved_info,
                conversation_history=conversation_history,
                is_new_conversation=is_new_conversation,
                conversation_id=conversation_id
            )
            
            self.logger.info(f"Generated response for conversation {conversation_id}")
            return response
            
        except Exception as e:
            self.logger.error(f"Error generating response: {str(e)}")
            return {
                "response": "I'm sorry, I encountered an error while processing your request. Please try again.",
                "sources": []
            }

# Create a singleton instance
frontend_integration = FrontendIntegration()
