"""
Appointment guidance module to provide better user guidance during the appointment scheduling flow
"""

from typing import Dict, Any, List, Optional
from utils.appointment_state import get_appointment_state

def get_appointment_guidance(conversation_id: str, missing_fields: List[str]) -> Dict[str, Any]:
    """
    Get guidance for the appointment flow based on missing fields
    
    Args:
        conversation_id: The conversation ID
        missing_fields: List of missing fields
        
    Returns:
        Dict[str, Any]: Guidance information including prompts and next steps
    """
    state = get_appointment_state(conversation_id)
    if not state:
        return {
            "status": "error",
            "message": "No appointment state found.",
            "prompt": "Would you like to schedule an appointment? I'll need your name, email, and phone number.",
            "collected_info": [],
            "needed_info": ["name", "email", "phone"]
        }
        
    extracted_info = state.get("extracted_info", {})
    
    # Determine what information we already have
    collected_info = []
    if "name" in extracted_info and extracted_info["name"]:
        collected_info.append(f"Name: {extracted_info['name']}")
    if "email" in extracted_info and extracted_info["email"]:
        collected_info.append(f"Email: {extracted_info['email']}")
    if "phone" in extracted_info and extracted_info["phone"]:
        collected_info.append(f"Phone: {extracted_info['phone']}")
    if "topic" in extracted_info and extracted_info["topic"]:
        collected_info.append(f"Topic: {extracted_info['topic']}")
    if "preferred_date" in extracted_info and extracted_info["preferred_date"]:
        collected_info.append(f"Preferred date: {extracted_info['preferred_date']}")
    if "preferred_time" in extracted_info and extracted_info["preferred_time"]:
        collected_info.append(f"Preferred time: {extracted_info['preferred_time']}")
    
    # Determine what information we still need
    needed_info = []
    for field in missing_fields:
        if field == "name":
            needed_info.append("Your name")
        elif field == "email":
            needed_info.append("Your email address")
        elif field == "phone":
            needed_info.append("Your phone number")
        elif field == "topic":
            needed_info.append("Meeting topic")
    
    # Generate appropriate guidance
    # If no missing fields, appointment is ready to schedule
    if not missing_fields:
        # Import here to avoid circular imports
        from utils.appointment_scheduler import check_and_schedule_if_ready
        import logging
        from datetime import datetime
        
        logger = logging.getLogger("mango_ai_agent")
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
        
        # Log that we're triggering the scheduling
        logger.info(f"[{timestamp}] GUIDANCE MODULE - All information collected, triggering appointment scheduling for {conversation_id}")
        
        # Explicitly call the scheduling function
        try:
            scheduling_result = check_and_schedule_if_ready(conversation_id)
            logger.info(f"[{timestamp}] GUIDANCE SCHEDULING RESULT: {scheduling_result}")
            
            if scheduling_result and scheduling_result.get("success"):
                # Appointment was successfully scheduled
                appointment_id = scheduling_result.get("appointment_id")
                return {
                    "status": "complete",
                    "message": f"Great news! Your appointment has been scheduled. Your appointment ID is {appointment_id}.",
                    "prompt": "",
                    "collected_info": collected_info,
                    "needed_info": [],
                    "scheduled": True,
                    "appointment_id": appointment_id
                }
            else:
                # There was an error scheduling the appointment
                error = scheduling_result.get("error") if scheduling_result else "Unknown error"
                logger.error(f"[{timestamp}] GUIDANCE ERROR scheduling appointment: {error}")
        except Exception as e:
            logger.error(f"[{timestamp}] GUIDANCE EXCEPTION in scheduling: {str(e)}")
            logger.error(f"[{timestamp}] TRACEBACK: {__import__('traceback').format_exc()}")
        
        # Default response if scheduling fails
        return {
            "status": "complete",
            "message": "Thank you! I have all the information needed to schedule your appointment.",
            "prompt": "",
            "collected_info": collected_info,
            "needed_info": []
        }
    else:
        # Still need more information
        if len(missing_fields) == 1:
            # Only one field missing
            field = missing_fields[0]
            if field == "name":
                prompt = "Could you please tell me your name?"
            elif field == "email":
                prompt = "Could you please provide your email address so we can send you confirmation details?"
            elif field == "phone":
                prompt = "Could you also share your phone number so our team can reach you if needed?"
            elif field == "topic":
                prompt = "What would you like to discuss in this meeting?"
            else:
                prompt = f"Could you please provide your {field}?"
                
            return {
                "status": "in_progress",
                "message": f"Almost there! I just need one more piece of information: {needed_info[0]}.",
                "prompt": prompt,
                "collected_info": collected_info,
                "needed_info": needed_info
            }
        else:
            # Multiple fields missing
            # Create a more structured and clear message
            message_parts = []
            
            # First, acknowledge what we already have
            if collected_info:
                message_parts.append("Thank you for providing:")
                for info in collected_info:
                    message_parts.append(f"✓ {info}")
                message_parts.append("")
            
            # Then clearly state what's still needed
            message_parts.append("I still need the following to schedule your appointment:")
            for info in needed_info:
                message_parts.append(f"➤ {info}")
            
            return {
                "status": "in_progress",
                "message": "\n".join(message_parts),
                "prompt": f"Could you please provide your {missing_fields[0]}?",
                "collected_info": collected_info,
                "needed_info": needed_info
            }

def generate_appointment_summary(conversation_id: str) -> str:
    """
    Generate a summary of the appointment information
    
    Args:
        conversation_id: The conversation ID
        
    Returns:
        str: Summary of the appointment information
    """
    state = get_appointment_state(conversation_id)
    if not state:
        return "No appointment information found."
        
    extracted_info = state.get("extracted_info", {})
    
    summary = "Here's a summary of your appointment details:\n\n"
    
    if "name" in extracted_info and extracted_info["name"]:
        summary += f"- Name: {extracted_info['name']}\n"
    if "email" in extracted_info and extracted_info["email"]:
        summary += f"- Email: {extracted_info['email']}\n"
    if "phone" in extracted_info and extracted_info["phone"]:
        summary += f"- Phone: {extracted_info['phone']}\n"
    if "topic" in extracted_info and extracted_info["topic"]:
        summary += f"- Topic: {extracted_info['topic']}\n"
    if "preferred_date" in extracted_info and extracted_info["preferred_date"]:
        summary += f"- Preferred date: {extracted_info['preferred_date']}\n"
    if "preferred_time" in extracted_info and extracted_info["preferred_time"]:
        summary += f"- Preferred time: {extracted_info['preferred_time']}\n"
    
    if state.get("appointment_id"):
        summary += f"\nAppointment ID: {state['appointment_id']}\n"
        summary += "Our team will contact you soon to confirm the details."
    
    return summary
