cimport asyncio
import json
import logging
import time
from typing import Dict, Any, Optional, List
from datetime import datetime, timedelta
import re
from collections import defaultdict

from livekit.agents import (
    AutoSubscribe,
    JobContext,
    WorkerOptions,
    cli,
    llm,
    Agent,
    RunContext,
    function_tool,
    get_job_context,
    AgentSession,
)
from livekit.plugins import openai, deepgram, inworld, cartesia
from livekit import rtc, api

from config import settings
from models import Reservation, Order, Customer, MenuItem, VoiceAgentRequest, VoiceAgentResponse
from api_client import api_client
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize plugins



class SpamDetector:
    """Detect spam calls and abuse patterns"""
    
    def __init__(self):
        self.phone_attempts = defaultdict(list)  # phone -> [timestamps]
        self.room_attempts = defaultdict(list)   # room -> [timestamps]
        self.max_attempts_per_hour = settings.max_attempts_per_hour
        self.max_attempts_per_day = settings.max_attempts_per_day
        self.ban_duration_hours = settings.spam_ban_duration_hours
    
    def is_spam_phone(self, phone: str) -> bool:
        """Check if a phone number is spamming"""
        now = time.time()
        hour_ago = now - 3600
        day_ago = now - 86400
        
        # Clean old attempts
        self.phone_attempts[phone] = [t for t in self.phone_attempts[phone] if t > day_ago]
        
        recent_attempts = [t for t in self.phone_attempts[phone] if t > hour_ago]
        daily_attempts = self.phone_attempts[phone]
        
        return (len(recent_attempts) >= self.max_attempts_per_hour or 
                len(daily_attempts) >= self.max_attempts_per_day)
    
    def is_spam_room(self, room_name: str) -> bool:
        """Check if a room is being spammed"""
        now = time.time()
        hour_ago = now - 3600
        
        # Clean old attempts
        self.room_attempts[room_name] = [t for t in self.room_attempts[room_name] if t > hour_ago]
        
        recent_attempts = [t for t in self.room_attempts[room_name] if t > hour_ago]
        return len(recent_attempts) >= self.max_attempts_per_hour
    
    def record_attempt(self, phone: str = None, room_name: str = None):
        """Record an attempt"""
        now = time.time()
        if phone:
            self.phone_attempts[phone].append(now)
        if room_name:
            self.room_attempts[room_name].append(now)


async def hangup_call():
    """Hang up the current call"""
    try:
        ctx = get_job_context()
        if ctx is None:
            logger.warning("Not running in a job context, cannot hangup")
            return
        
        await ctx.api.room.delete_room(
            api.DeleteRoomRequest(
                room=ctx.room.name,
            )
        )
        logger.info(f"Hanging up call for room: {ctx.room.name}")
    except Exception as e:
        logger.error(f"Error hanging up call: {e}")


class RestaurantVoiceAgent:
    def __init__(self):
        self.restaurant_info = None
        self.menu_items = []
        self.opening_hours = {}
        self.conversation_context = {}
        self.spam_detector = SpamDetector()
        self.last_customer_activity = time.time()
        self.conversation_start_time = time.time()
        self.auto_hangup_delay = settings.auto_hangup_delay
        self.hangup_task = None
        
    async def initialize(self):
        """Initialize the agent with restaurant data"""
        try:
            self.restaurant_info = await api_client.get_restaurant_info()
            self.menu_items = await api_client.get_menu()
            self.opening_hours = await api_client.get_opening_hours()
            logger.info(f"Initialized agent for restaurant: {self.restaurant_info.name}")
        except Exception as e:
            logger.error(f"Failed to initialize agent: {e}")
    
    def get_system_prompt(self) -> str:
        """Generate system prompt for the voice agent"""
        restaurant_name = self.restaurant_info.name if self.restaurant_info else "Our Restaurant"
        phone = self.restaurant_info.phone if self.restaurant_info else "our phone number"
        address = self.restaurant_info.address if self.restaurant_info else "our address"
        email = self.restaurant_info.email if self.restaurant_info else "our email"
        description = self.restaurant_info.description if self.restaurant_info else "Vietnamese cuisine restaurant"
        cuisine_type = self.restaurant_info.cuisine_type if self.restaurant_info else "Vietnamese"
        
        # Format contact information
        contact_info = f"- Phone: {phone}\n- Address: {address}\n- Email: {email}"
        if self.restaurant_info and self.restaurant_info.website:
            contact_info += f"\n- Website: {self.restaurant_info.website}"
        if self.restaurant_info and self.restaurant_info.facebook_url:
            contact_info += f"\n- Facebook: {self.restaurant_info.facebook_url}"
        if self.restaurant_info and self.restaurant_info.instagram_url:
            contact_info += f"\n- Instagram: {self.restaurant_info.instagram_url}"
        
        hours_text = ""
        if self.opening_hours:
            hours_text = "\n".join([f"- {day.title()}: {hours}" for day, hours in self.opening_hours.items()])
        else:
            hours_text = "- Monday-Sunday: 9:00 AM - 10:00 PM"
        
        menu_text = ""
        if self.menu_items:
            categories = {}
            for item in self.menu_items:
                if item.category not in categories:
                    categories[item.category] = []
                categories[item.category].append(f"{item.name} - ${item.price:.2f}")
            
            for category, items in categories.items():
                menu_text += f"\n{category.title()}:\n"
                menu_text += "\n".join([f"- {item}" for item in items[:5]])  # Show max 5 items per category
                if len(items) > 5:
                    menu_text += f"\n- And {len(items) - 5} more items..."
        
        # Format amenities
        amenities_text = ""
        if self.restaurant_info and self.restaurant_info.amenities:
            amenities_list = []
            if self.restaurant_info.amenities.get('wifi', False):
                amenities_list.append("Free Wi-Fi")
            if self.restaurant_info.amenities.get('parking', False):
                amenities_list.append("Parking available")
            if self.restaurant_info.amenities.get('card_payment', False):
                amenities_list.append("Card payments accepted")
            if self.restaurant_info.amenities.get('wheelchair_accessible', False):
                amenities_list.append("Wheelchair accessible")
            if self.restaurant_info.amenities.get('kid_friendly', False):
                amenities_list.append("Kid-friendly")
            if self.restaurant_info.amenities.get('high_chairs', False):
                amenities_list.append("High chairs available")
            if self.restaurant_info.amenities.get('pet_friendly', False):
                amenities_list.append("Pet-friendly")
            
            if amenities_list:
                amenities_text = f"\n\nAMENITIES:\n" + "\n".join([f"- {amenity}" for amenity in amenities_list])
        
        # Check if temporarily closed
        status_note = ""
        if self.restaurant_info and self.restaurant_info.temporarily_closed:
            status_note = "\n\nIMPORTANT: The restaurant is currently temporarily closed. Please inform customers about this and suggest they call back later or check our website for updates."
        
        return f"""You are a friendly and helpful multilingual voice assistant for {restaurant_name}. You can help customers with:

1. Making reservations
2. Taking orders
3. Canceling or updating reservations
4. Providing information about the restaurant

IMPORTANT LANGUAGE INSTRUCTIONS:
- You ONLY speak English and Spanish
- Detect the customer's language from their speech
- Respond in the SAME language the customer uses
- If customer speaks English, respond in English
- If customer speaks Spanish, respond in Spanish
- If customer speaks other languages, politely ask them to speak English or Spanish
- Use appropriate greetings for each language:
  * English: "Hello! Welcome to {restaurant_name}. How can I help you today?"
  * Spanish: "¡Hola! Bienvenido a {restaurant_name}. ¿Cómo puedo ayudarte hoy?"

VIETNAMESE RESTAURANT CONTEXT:
- This is {restaurant_name}, serving authentic {cuisine_type} cuisine
- We specialize in traditional Vietnamese dishes like pho, banh mi, and Vietnamese specialties
- Be knowledgeable about Vietnamese food and help customers understand our authentic dishes
- Recommend popular Vietnamese dishes when customers ask for suggestions

RESTAURANT INFORMATION:
- Name: {restaurant_name}
- Description: {description}
- Cuisine Type: {cuisine_type}

CONTACT INFORMATION:
{contact_info}

Opening Hours:
{hours_text}

Menu Highlights:
{menu_text}{amenities_text}

Guidelines:
- Be warm, friendly, and professional
- Always confirm details before making reservations or orders
- Ask for customer's phone number for reservations and orders
- For reservations, ask for date, time, and party size
- For orders, ask what items they'd like and quantities
- If you don't know something, offer to connect them with staff
- Keep responses concise and conversational
- Use the available tools to perform actions
- Maintain language consistency throughout the conversation

Available tools:
- create_reservation: Make a new reservation
- cancel_reservation: Cancel an existing reservation
- update_reservation: Update reservation details
- create_order: Take a food order
- get_customer_info: Get customer's past orders/reservations
- check_availability: Check if tables are available
- end_call: End the call when customer is done
- thank_you_and_end: Thank customer and end the call

CONVERSATION MANAGEMENT:
- If the customer says "thank you", "goodbye", "bye", or indicates they're done, use thank_you_and_end tool
- Keep conversations focused and efficient{status_note}

Always use these tools when the customer wants to make reservations or orders."""

    async def create_reservation(self, customer_phone: str, date: str, time: str, party_size: int, 
                                customer_name: str = None, special_requests: str = None) -> Dict[str, Any]:
        """Create a new reservation"""
        try:
            # Update customer activity
            self.update_customer_activity()
            
            # Get or create customer
            customer = await api_client.get_or_create_customer(customer_phone, customer_name)
            if not customer:
                return {"error": "Failed to create customer record"}
            
            # Check availability
            is_available = await api_client.check_availability(date, time, party_size)
            if not is_available:
                return {"error": f"Sorry, we don't have availability for {party_size} people on {date} at {time}"}
            
            # Create reservation
            reservation_data = {
                "customer_id": customer.id,
                "restaurant_id": 1,  # Assuming single restaurant
                "date": date,
                "time": time,
                "party_size": party_size,
                "special_requests": special_requests
            }
            
            reservation = await api_client.create_reservation(reservation_data)
            if reservation:
                return {
                    "success": True,
                    "message": f"Great! I've made a reservation for {party_size} people on {date} at {time}. Your reservation ID is {reservation.id}.",
                    "reservation_id": reservation.id
                }
            else:
                return {"error": "Failed to create reservation. Please try again."}
                
        except Exception as e:
            logger.error(f"Error creating reservation: {e}")
            return {"error": "Sorry, there was an error creating your reservation. Please try again."}
    
    async def cancel_reservation(self, customer_phone: str, reservation_id: int = None) -> Dict[str, Any]:
        """Cancel a reservation"""
        try:
            # Update customer activity
            self.update_customer_activity()
            
            # Get customer
            customer = await api_client.get_or_create_customer(customer_phone)
            if not customer:
                return {"error": "Customer not found"}
            
            # Get customer's reservations if no ID provided
            if not reservation_id:
                reservations = await api_client.get_customer_reservations(customer.id)
                if not reservations:
                    return {"error": "No reservations found for this phone number"}
                # Use the most recent reservation
                reservation_id = reservations[0].id
            
            # Cancel reservation
            success = await api_client.cancel_reservation(reservation_id)
            if success:
                return {
                    "success": True,
                    "message": f"Your reservation #{reservation_id} has been cancelled successfully."
                }
            else:
                return {"error": "Failed to cancel reservation. Please try again."}
                
        except Exception as e:
            logger.error(f"Error canceling reservation: {e}")
            return {"error": "Sorry, there was an error canceling your reservation. Please try again."}
    
    async def update_reservation(self, customer_phone: str, reservation_id: int = None, 
                               new_date: str = None, new_time: str = None, new_party_size: int = None) -> Dict[str, Any]:
        """Update a reservation"""
        try:
            # Update customer activity
            self.update_customer_activity()
            # Get customer
            customer = await api_client.get_or_create_customer(customer_phone)
            if not customer:
                return {"error": "Customer not found"}
            
            # Get customer's reservations if no ID provided
            if not reservation_id:
                reservations = await api_client.get_customer_reservations(customer.id)
                if not reservations:
                    return {"error": "No reservations found for this phone number"}
                reservation_id = reservations[0].id
            
            # Prepare updates
            updates = {}
            if new_date:
                updates["date"] = new_date
            if new_time:
                updates["time"] = new_time
            if new_party_size:
                updates["party_size"] = new_party_size
            
            if not updates:
                return {"error": "No updates provided"}
            
            # Update reservation
            success = await api_client.update_reservation(reservation_id, updates)
            if success:
                return {
                    "success": True,
                    "message": f"Your reservation #{reservation_id} has been updated successfully."
                }
            else:
                return {"error": "Failed to update reservation. Please try again."}
                
        except Exception as e:
            logger.error(f"Error updating reservation: {e}")
            return {"error": "Sorry, there was an error updating your reservation. Please try again."}
    
    async def create_order(self, customer_phone: str, items: List[Dict[str, Any]], 
                          order_type: str = "dine_in", special_instructions: str = None) -> Dict[str, Any]:
        """Create a new order"""
        try:
            # Update customer activity
            self.update_customer_activity()
            # Get or create customer
            customer = await api_client.get_or_create_customer(customer_phone)
            if not customer:
                return {"error": "Failed to create customer record"}
            
            # Calculate total amount
            total_amount = 0
            for item in items:
                menu_item = await api_client.get_menu_item(item["menu_item_id"])
                if menu_item:
                    total_amount += menu_item.price * item["quantity"]
            
            # Create order
            order_data = {
                "customer_id": customer.id,
                "restaurant_id": 1,
                "items": items,
                "total_amount": total_amount,
                "order_type": order_type,
                "special_instructions": special_instructions
            }
            
            order = await api_client.create_order(order_data)
            if order:
                return {
                    "success": True,
                    "message": f"Great! I've placed your order. Your order ID is {order.id} and the total is ${total_amount:.2f}.",
                    "order_id": order.id,
                    "total_amount": total_amount
                }
            else:
                return {"error": "Failed to create order. Please try again."}
                
        except Exception as e:
            logger.error(f"Error creating order: {e}")
            return {"error": "Sorry, there was an error placing your order. Please try again."}
    
    async def get_customer_info(self, customer_phone: str) -> Dict[str, Any]:
        """Get customer's past orders and reservations"""
        try:
            # Update customer activity
            self.update_customer_activity()
            customer = await api_client.get_or_create_customer(customer_phone)
            if not customer:
                return {"error": "Customer not found"}
            
            reservations = await api_client.get_customer_reservations(customer.id)
            orders = await api_client.get_customer_orders(customer.id)
            
            return {
                "success": True,
                "customer": customer,
                "reservations": reservations,
                "orders": orders
            }
                
        except Exception as e:
            logger.error(f"Error getting customer info: {e}")
            return {"error": "Sorry, there was an error retrieving your information. Please try again."}
    
    async def check_availability(self, date: str, time: str, party_size: int) -> Dict[str, Any]:
        """Check table availability"""
        try:
            # Update customer activity
            self.update_customer_activity()
            is_available = await api_client.check_availability(date, time, party_size)
            return {
                "success": True,
                "available": is_available,
                "message": f"{'Yes, we have availability' if is_available else 'Sorry, we are fully booked'} for {party_size} people on {date} at {time}."
            }
                
        except Exception as e:
            logger.error(f"Error checking availability: {e}")
            return {"error": "Sorry, there was an error checking availability. Please try again."}
    
    def update_customer_activity(self):
        """Update last customer activity timestamp"""
        self.last_customer_activity = time.time()
        logger.debug(f"Customer activity updated: {self.last_customer_activity}")
    
    def should_auto_hangup(self) -> bool:
        """Check if we should auto hangup due to inactivity"""
        time_since_activity = time.time() - self.last_customer_activity
        return time_since_activity >= self.auto_hangup_delay
    
    async def check_and_hangup_if_needed(self):
        """Check if we should hangup and do it"""
        if self.should_auto_hangup():
            logger.info("Auto hanging up due to customer inactivity")
            await self.end_call_with_thanks()
            return True
        return False
    
    async def end_call_with_thanks(self):
        """End the call with a thank you message"""
        try:
            # Send thank you message
            ctx = get_job_context()
            if ctx:
                await ctx.room.local_participant.publish_data(
                    json.dumps({
                        "type": "message",
                        "text": "Thank you for calling Phở Hương Việt Restaurant. Have a great day!"
                    }).encode(),
                    topic="agent_message"
                )
            
            # Wait a moment for the message to be sent
            await asyncio.sleep(2)
            
            # Hang up
            await hangup_call()
        except Exception as e:
            logger.error(f"Error ending call: {e}")
    
    def is_spam_call(self, phone: str = None, room_name: str = None) -> bool:
        """Check if this is a spam call"""
        if phone and self.spam_detector.is_spam_phone(phone):
            logger.warning(f"Spam detected for phone: {phone}")
            return True
        
        if room_name and self.spam_detector.is_spam_room(room_name):
            logger.warning(f"Spam detected for room: {room_name}")
            return True
        
        return False
    
    def record_call_attempt(self, phone: str = None, room_name: str = None):
        """Record a call attempt for spam detection"""
        self.spam_detector.record_attempt(phone=phone, room_name=room_name)
    
    async def handle_spam_call(self, phone: str = None, room_name: str = None):
        """Handle spam call by hanging up immediately"""
        logger.warning(f"Hanging up spam call - Phone: {phone}, Room: {room_name}")
        
        try:
            ctx = get_job_context()
            if ctx:
                await ctx.room.local_participant.publish_data(
                    json.dumps({
                        "type": "message",
                        "text": "Sorry, we cannot process your request at this time."
                    }).encode(),
                    topic="agent_message"
                )
            
            # Wait briefly then hang up
            await asyncio.sleep(1)
            await hangup_call()
        except Exception as e:
            logger.error(f"Error handling spam call: {e}")
    
    @function_tool
    async def end_call(self, ctx: RunContext):
        """Called when the user wants to end the call"""
        await ctx.wait_for_playout()  # let the agent finish speaking
        await self.end_call_with_thanks()
    
    @function_tool
    async def thank_you_and_end(self, ctx: RunContext):
        """Thank the customer and end the call"""
        await ctx.wait_for_playout()  # let the agent finish speaking
        await self.end_call_with_thanks()


# Global agent instance
restaurant_agent = RestaurantVoiceAgent()


async def entrypoint(ctx: JobContext):
    """Main entrypoint for the LiveKit agent"""
    try:
        # Connect to the job context
        await ctx.connect()
        logger.info("Connected to LiveKit job context")
        
        # Check if room is connected before proceeding
        if not ctx.room.isconnected():
            logger.warning("Room is not connected, waiting for connection...")
            # Wait a bit for connection to establish
            await asyncio.sleep(1)
            if not ctx.room.isconnected():
                logger.error("Room connection failed")
                return
        
        logger.info(f"Room connected: {ctx.room.name}")
        
        # Initialize restaurant agent
        await restaurant_agent.initialize()
        
        # Wait for participant to join with timeout
        try:
            await asyncio.wait_for(ctx.wait_for_participant(), timeout=60.0)
        except asyncio.TimeoutError:
            logger.warning("No participant joined within 60 seconds")
            return
        
        # Check if we have participants
        remote_participants = list(ctx.room.remote_participants.values())
        if not remote_participants:
            logger.warning("No remote participants found")
            return
        
        # Get the first participant
        participant = remote_participants[0]
        logger.info(f"Participant joined: {participant.identity}")
        
        # Extract phone number from participant identity if available
        phone_number = None
        if hasattr(participant, 'identity') and participant.identity:
            # Try to extract phone number from identity (format: "phone:+1234567890")
            if participant.identity.startswith('phone:'):
                phone_number = participant.identity[6:]  # Remove "phone:" prefix
        
        # Check for spam
        if restaurant_agent.is_spam_call(phone=phone_number, room_name=ctx.room.name):
            await restaurant_agent.handle_spam_call(phone=phone_number, room_name=ctx.room.name)
            return
        
        # Record this call attempt
        restaurant_agent.record_call_attempt(phone=phone_number, room_name=ctx.room.name)
        
        # Reset activity timer
        restaurant_agent.last_customer_activity = time.time()
        restaurant_agent.conversation_start_time = time.time()
        
        # Create agent session with specific models
        session = AgentSession(
        turn_detection=None,
        llm=openai.LLM(model="gpt-4.1-mini"),
        stt=deepgram.STT(model="nova-3"),wr
        tts=inworld.TTS(model="inworld-tts-1-max"),
        
        user_away_timeout=15.0,  # Auto disconnect after 15 seconds of inactivity
    )
        
        # Create standalone function tools that work with the agent instance
        @function_tool
        async def create_reservation_tool(customer_phone: str, date: str, time: str, party_size: int, 
                                         customer_name: str = None, special_requests: str = None):
            """Create a new reservation"""
            return await restaurant_agent.create_reservation(customer_phone, date, time, party_size, customer_name, special_requests)
        
        @function_tool
        async def cancel_reservation_tool(customer_phone: str, reservation_id: int = None):
            """Cancel a reservation"""
            return await restaurant_agent.cancel_reservation(customer_phone, reservation_id)
        
        @function_tool
        async def update_reservation_tool(customer_phone: str, reservation_id: int = None, 
                                         new_date: str = None, new_time: str = None, new_party_size: int = None):
            """Update a reservation"""
            return await restaurant_agent.update_reservation(customer_phone, reservation_id, new_date, new_time, new_party_size)
        
        @function_tool
        async def create_order_tool(customer_phone: str, items: str, order_type: str = "dine_in", special_instructions: str = None):
            """Create a new order. Items should be a JSON string with menu items and quantities."""
            import json
            try:
                items_list = json.loads(items)
                return await restaurant_agent.create_order(customer_phone, items_list, order_type, special_instructions)
            except json.JSONDecodeError:
                return {"error": "Invalid items format. Please provide a valid JSON string."}
        
        @function_tool
        async def get_customer_info_tool(customer_phone: str):
            """Get customer's past orders and reservations"""
            return await restaurant_agent.get_customer_info(customer_phone)
        
        @function_tool
        async def check_availability_tool(date: str, time: str, party_size: int):
            """Check table availability"""
            return await restaurant_agent.check_availability(date, time, party_size)
        
        @function_tool
        async def end_call_tool():
            """End the call when customer is done"""
            await restaurant_agent.end_call_with_thanks()
            return {"message": "Call ended"}
        
        @function_tool
        async def thank_you_and_end_tool():
            """Thank customer and end the call"""
            await restaurant_agent.end_call_with_thanks()
            return {"message": "Thank you and goodbye!"}
        
        # Create the assistant agent with function tools
        assistant = Agent(
            instructions=restaurant_agent.get_system_prompt(),
            tools=[
                create_reservation_tool,
                cancel_reservation_tool,
                update_reservation_tool,
                create_order_tool,
                get_customer_info_tool,
                check_availability_tool,
                end_call_tool,
                thank_you_and_end_tool,
            ]
        )
        
        # Start auto-hangup monitoring task
        async def monitor_activity():
            while True:
                try:
                    await asyncio.sleep(5)  # Check every 5 seconds
                    
                    # Check if room is still connected
                    if not ctx.room.isconnected():
                        logger.info("Room disconnected, stopping monitoring")
                        break
                    
                    # Check if we should auto hangup
                    if await restaurant_agent.check_and_hangup_if_needed():
                        break
                        
                    # Check if conversation has been going too long
                    conversation_duration = time.time() - restaurant_agent.conversation_start_time
                    if conversation_duration > settings.max_conversation_duration:
                        logger.info("Conversation timeout reached, hanging up")
                        await restaurant_agent.end_call_with_thanks()
                        break
                        
                except asyncio.CancelledError:
                    break
                except Exception as e:
                    logger.error(f"Error in activity monitor: {e}")
        
        # Start the assistant
        await session.start(agent=assistant, room=ctx.room)
        
        # Greet the user
        restaurant_name = restaurant_agent.restaurant_info.name if restaurant_agent.restaurant_info else "Our Restaurant"
        greeting_message = f"Hi, this is {restaurant_name}. How may I help you today?"
        await session.say(greeting_message, allow_interruptions=False)
        
        # Start monitoring task
        monitor_task = asyncio.create_task(monitor_activity())
        
        # Set up event-based waiting for room disconnection
        disconnect_event = asyncio.Event()
        
        @ctx.room.on("disconnected")
        def on_room_disconnect(*args):
            disconnect_event.set()
        
        try:
            # Wait until the room is disconnected
            await disconnect_event.wait()
        finally:
            # Clean up monitoring task
            monitor_task.cancel()
            try:
                await monitor_task
            except asyncio.CancelledError:
                pass
            
            # Properly shutdown the job context
            ctx.shutdown()
            logger.info("Job context shutdown completed")
                
    except Exception as e:
        logger.error(f"Error in entrypoint: {e}")
        # Ensure shutdown even on error
        try:
            ctx.shutdown()
        except Exception as shutdown_error:
            logger.error(f"Error during shutdown: {shutdown_error}")
        raise


async def test_mode():
    """Test mode for development - simulates a voice agent session without LiveKit"""
    print("🧪 Running voice agent in test mode...")
    
    # Initialize the restaurant agent
    await restaurant_agent.initialize()
    
    print(f"✅ Restaurant agent initialized for: {restaurant_agent.restaurant_info.name if restaurant_agent.restaurant_info else 'Unknown Restaurant'}")
    print(f"📋 Menu items loaded: {len(restaurant_agent.menu_items)}")
    print(f"🕒 Opening hours: {restaurant_agent.opening_hours}")
    
    # Test some functions
    print("\n🔧 Testing agent functions...")
    
    # Test reservation creation
    try:
        result = await restaurant_agent.create_reservation(
            customer_phone="+1234567890",
            date="2024-01-15",
            time="19:00",
            party_size=4,
            customer_name="Test Customer"
        )
        print(f"✅ Reservation test: {result.get('success', False)}")
    except Exception as e:
        print(f"❌ Reservation test failed: {e}")
    
    # Test menu retrieval
    try:
        menu_result = await restaurant_agent.get_customer_info("+1234567890")
        print(f"✅ Customer info test: {menu_result.get('success', False)}")
    except Exception as e:
        print(f"❌ Customer info test failed: {e}")
    
    print("\n🎉 Test mode completed!")
    print("💡 To use the voice agent with LiveKit, deploy it as a worker to your LiveKit server")


if __name__ == "__main__":
    import sys
    
    # Check if running in test mode
    if len(sys.argv) > 1 and sys.argv[1] == "--test":
        asyncio.run(test_mode())
    else:
        # Normal LiveKit worker mode
        cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
