"""LiveKit-based Conversation Agent for AI Virtual Receptionist."""

import asyncio
import json
import logging
from datetime import UTC, datetime
from enum import Enum
from typing import Any, AsyncIterable, Optional

from livekit import rtc
from livekit.rtc import (
    Participant,
    TrackKind,
    Track
)
from livekit.agents import (
    Agent,
    AgentSession,
    ChatContext,
    FunctionTool,
    JobContext,
    ModelSettings,
    WorkerOptions,
    cli,
    function_tool,
    llm,
    AutoSubscribe,
    ConversationItemAddedEvent,
    RoomInputOptions
)
from livekit.agents.stt import SpeechEventType, SpeechEvent
from livekit.plugins import deepgram, openai, silero
from sqlalchemy.orm import Session

from ai_bridge_fastapi.api.routes.helpers import get_business_data_for_call
from ai_bridge_fastapi.api.routes.utils import init_wav_writer
from ai_bridge_fastapi.config import get_settings
from ai_bridge_fastapi.models.call import Conversation
from ai_bridge_fastapi.schemas.business import BusinessContext
from ai_bridge_fastapi.schemas.llm import LLMContext
from ai_bridge_fastapi.services.api_client import DjangoAPIClient
from ai_bridge_fastapi.services.base import (
    BaseLLMService,
)
from ai_bridge_fastapi.services.tools import get_tools
from ai_bridge_fastapi.utils import DataclassJSONEncoder
from ai_bridge_fastapi.database import Session, engine

logger = logging.getLogger(__name__)

settings = get_settings()

class LiveKitVoiceAgent(Agent):
    """LiveKit 1.0 Voice Agent for AI Virtual Receptionist."""
    
    def __init__(
        self,
        business_data: BusinessContext,
        llm_service: BaseLLMService,
        **kwargs
    ):
        """Initialize the voice agent with business context."""
        self.business_data = business_data
        self.llm_service = llm_service
        self.conversation_history: list[dict[str, str]] = []
        self.api_client = DjangoAPIClient(business_id=str(business_data.business_id))
        
        # Build system instructions
        instructions = settings.PROMPT_TEMPLATE
        
        super().__init__(
            instructions=instructions,
            **kwargs
        )
        
    async def stt_node(
        self, audio: AsyncIterable[rtc.AudioFrame], model_settings: ModelSettings
    ) -> Optional[AsyncIterable[SpeechEvent]]:
        async def filtered_audio():
            async for frame in audio:
                # insert custom audio preprocessing here
                yield frame
        
        async for event in Agent.default.stt_node(self, filtered_audio(), model_settings):
            # insert custom text postprocessing here 
            logger.info("STT Event: %s", event)
            yield event

    
    async def llm_node(
        self, chat_ctx: ChatContext, tools: list[FunctionTool], model_settings: ModelSettings
    ):
        """Convert our custom tools to LiveKit format."""
        tools = get_tools()
        check_availability_tool = tools[0]
        book_appointment_tool = tools[1]
        
        llm_check_availability_tool = function_tool(
            self._execute_check_availability,
            name=check_availability_tool.get('name', ''),
            description=check_availability_tool.get('description', ''),
            parameters=check_availability_tool.get('parameters', {}),
        )
        
        llm_book_appointment_tool = function_tool(
            self._execute_book_appointment,
            name=book_appointment_tool.get('name', ''),
            description=book_appointment_tool.get('description', ''),
            parameters=book_appointment_tool.get('parameters', {}),
        )
        
        livekit_tools = [
            llm_check_availability_tool,
            llm_book_appointment_tool,
        ]

        return Agent.default.llm_node(self, chat_ctx, livekit_tools, model_settings)
    
    async def _execute_check_availability(
        self, start_date: str, service_ids: list[int] | None = None
    ) -> dict:
        """Calls the Django API to check for available slots."""
        params = {
            "business_id": self.business_data.business_id,
            "start_date": start_date,
        }
        if service_ids:
            params["service_ids"] = service_ids

        logger.info("--- TOOL: Calling Django to check availability with params: %s ---", params)
        return await self.api_client.check_availability(params)

    async def _execute_book_appointment(self, **kwargs) -> dict:
        """Calls the Django API to book an appointment."""
        payload = {
            "business_id": str(self.business_data.business_id),
            **kwargs,
        }
        # Ensure 'service_ids' is a list, as expected by the serializer
        # Handle if LLM sends 'services' instead of 'service_ids'
        if "services" in payload and "service_ids" not in payload:
            payload["service_ids"] = payload.pop("services")

        if "service_ids" in payload and isinstance(payload["service_ids"], list):
            payload["service_ids"] = [str(sid) for sid in payload["service_ids"]]
        elif "service_id" in payload:
            # Try to recover if LLM sends a single ID instead of a list
            payload["service_ids"] = [str(payload.pop("service_id"))]
        elif "service_ids" not in payload:
            return {"error": "A list of 'service_ids' is required to book an appointment."}

        payload["customer_phone"] = self.business_data.caller_info.phone_number

        logger.info("--- TOOL: Calling Django to book appointment with payload: %s ---", payload)

        return await self.api_client.book_appointment(payload)
    
    async def on_enter(self):
        """Called when the agent enters the conversation."""
        logger.info(f"Agent entered conversation for business {self.business_data.business_id}")
        
        # Generate initial greeting
        business_name = self.business_data.business_name
        greeting = f"Hello! Thank you for calling {business_name}. How can I help you today?"
        
        # Use the session to speak the greeting
        self.session.say(greeting)
    
    async def on_user_turn_completed(self, turn_ctx: llm.ChatContext, new_message: llm.ChatMessage):
        """Called when user finishes speaking."""
        if new_message.content:
            user_text = str(new_message.content[0]) if new_message.content else ""
            self.conversation_history.append({"role": "user", "content": user_text})
            logger.info(f"User speech: {user_text}")


class LiveKitConversationAgent:
    """LiveKit-based conversation agent for AI virtual receptionist."""

    # Response timing constants optimized for receptionist use case
    MAX_RESPONSE_TIME = 10.0  # Maximum time to generate response

    class ResponseType(Enum):
        BUFFERED = 0
        STREAMING = 1

    def __init__(
        self,
        business_data: BusinessContext,
        session: Session,
        max_pending_responses: int = 10,
        response_type: ResponseType | None = None,
        enable_streaming: bool | None = None,
    ):
        """Initialize LiveKit conversation agent.

        Args:
            business_data: Complete business context and call information
            stt_service: Speech-to-text service with integrated VAD
            tts_service: Text-to-speech service
            llm_service: Language model service
            session: Database session for logging
            max_pending_responses: Maximum number of pending responses in queue
            response_type: Enable streaming responses (None = use config default)
        """
        self.business_data = business_data
        self.call_sid = business_data.call_context.twilio_call_sid  # Keep for compatibility
        self.stt_service = deepgram.STT(model="nova-2", api_key=settings.DEEPGRAM_API_KEY)
        self.tts_service = openai.TTS(api_key=settings.OPENAI_API_KEY)
        self.llm_service = openai.LLM(model="gpt-4", api_key=settings.OPENAI_API_KEY)
        self.session = session
        self.api_client = DjangoAPIClient(business_id=str(business_data.business_id))

        self.room: Optional[rtc.Room] = None
        self.participant: Optional[rtc.RemoteParticipant] = None
        self.agent_session: Optional[AgentSession] = None
        self.voice_agent: Optional[LiveKitVoiceAgent] = None
        
        # Response queue for decoupled processing
        self.response_queue = asyncio.Queue(maxsize=max_pending_responses)

        # Conversation state - core responsibility
        self.conversation_history: list[dict[str, str]] = []
        self.is_processing = False
        self.is_calling_tool = False

        # Performance metrics for business operations
        self.metrics = {
            "total_utterances": 0,
            "successful_responses": 0,
            "failed_responses": 0,
            "average_response_time": 0.0,
            "conversation_start_time": datetime.now(UTC),
        }
        
        # Response queue metrics
        self.queue_metrics = {
            "total_responses_queued": 0,
            "responses_dropped": 0,
            "current_queue_size": 0,
            "max_queue_size": 0,
        }


        # Configuration from settings
        self.is_streaming_response = (
            enable_streaming if enable_streaming is not None else settings.ENABLE_LLM_STREAMING
        )
        self.streaming_chunk_size = settings.STREAMING_CHUNK_SIZE
        self.streaming_buffer_timeout = settings.STREAMING_BUFFER_TIMEOUT
        self.streaming_tts_enabled = settings.STREAMING_TTS_ENABLED
        self.streaming_min_response_length = settings.STREAMING_MIN_RESPONSE_LENGTH

        # Utterance buffering for short utterances
        self.utterance_buffering_enabled = settings.UTTERANCE_BUFFERING_ENABLED
        self.min_utterance_word_count = settings.MIN_UTTERANCE_WORD_COUNT
        self.utterance_buffer_timeout = settings.UTTERANCE_BUFFER_TIMEOUT
        self.utterance_buffer: list[str] = []
        self.last_utterance_time = 0.0
        self.utterance_buffer_task: Optional[asyncio.Task] = None

    async def initialize_livekit_session(self, room: rtc.Room) -> AgentSession:
        """Initialize LiveKit 1.0 agent session with custom services.
        
        Args:
            room: LiveKit room instance
            
        Returns:
            Configured AgentSession
        """
        self.room = room
        
        # Convert our custom services to LiveKit format
        livekit_stt = self._create_livekit_stt()
        livekit_tts = self._create_livekit_tts()
        livekit_llm = self._create_livekit_llm()
        livekit_vad = silero.VAD.load()

        # Create voice agent
        self.voice_agent = LiveKitVoiceAgent(
            business_data=self.business_data,
            llm_service=self.llm_service,
        )

        # Create agent session
        self.agent_session = AgentSession(
            stt=livekit_stt,
            llm=livekit_llm,
            tts=livekit_tts,
            vad=livekit_vad,
            allow_interruptions=True,
            min_endpointing_delay=0.4,
            max_endpointing_delay=6.0,
        )
        

        # Set up event handlers
        self.agent_session.on("user_input_transcribed", self._on_user_speech)
        self.agent_session.on("agent_state_changed", self._on_agent_state_changed)
        self.agent_session.on("user_state_changed", self._on_user_state_changed)
        self.agent_session.on("function_tools_executed", self._on_function_calls_finished)
        self.agent_session.on("conversation_item_added", self._on_conversation_item_added)

        return self.agent_session

    def _create_livekit_stt(self):
        """Create LiveKit-compatible STT service."""
        if self.stt_service:
            return self.stt_service
        else:
            # Fallback to Deepgram
            return deepgram.STT(model="nova-2", api_key=settings.DEEPGRAM_API_KEY)

    def _create_livekit_tts(self):
        """Create LiveKit-compatible TTS service."""
        if self.tts_service:
            return self.tts_service
        else:
            # Fallback to OpenAI TTS
            return openai.TTS(api_key=settings.OPENAI_API_KEY)

    def _create_livekit_llm(self):
        """Create LiveKit-compatible LLM service."""
        if self.llm_service:
            return self.llm_service
        else:
            # Fallback to OpenAI
            return openai.LLM(model="gpt-4", api_key=settings.OPENAI_API_KEY)

    def _on_user_speech(self, event):
        """Handle user speech events from LiveKit session."""
        user_text = event.transcript
        logger.info("User speech transcribed: %s", user_text)
        if user_text and user_text.strip():
            self.conversation_history.append({"role": "user", "content": user_text})
            self.metrics["total_utterances"] += 1
            logger.info(f"User speech: {user_text}")

    def _on_agent_state_changed(self, event):
        """Handle agent state changes."""
        logger.info(f"Agent state changed: {event.old_state} -> {event.new_state}")
        if event.new_state == "speaking":
            self.metrics["successful_responses"] += 1
            
    def _on_user_state_changed(self, event):
        """Handle user state changes."""
        logger.info(f"User state changed: {event.old_state} -> {event.new_state}")


    def _on_function_calls_finished(self, event):
        """Handle completion of function calls."""
        logger.info("Function calls completed")
        self.is_calling_tool = False
        
    def _on_conversation_item_added(self, event: ConversationItemAddedEvent):
        """Handle new conversation items added to the session."""
        item = event.item
        content = item.text_content
        role = item.role
        
        logger.info("New conversation item added from %s: %s", role, content)
        
        self.conversation_history.append({"role": role, "content": content})
            

    async def start_conversation(self, room: rtc.Room):
        """Start the conversation in a LiveKit room."""
        session = await self.initialize_livekit_session(room)
        
        # Start the session with the voice agent
        await session.start(
            self.voice_agent, 
            room=room,
            room_input_options=RoomInputOptions(audio_enabled=True, text_enabled=True),
        )
        
        logger.info(f"LiveKit conversation started for business {self.business_data.business_id}")

    async def stop_conversation(self):
        """Stop the conversation and clean up resources."""
        if self.agent_session:
            await self.agent_session.aclose()
            
        # Save conversation to database
        await self._save_conversation()
        
        logger.info(f"LiveKit conversation stopped for business {self.business_data.business_id}")

    def get_conversation_metrics(self) -> dict:
        """Get conversation performance metrics."""
        return {
            **self.metrics,
            "conversation_length": len(self.conversation_history),
            "is_processing": self.is_processing,
            "call_sid": self.call_sid,  # Keep for compatibility
            "conversation_duration": (
                datetime.now(UTC) - self.metrics["conversation_start_time"]
            ).total_seconds(),
            "response_queue_status": {
                "current_size": self.response_queue.qsize(),
                **self.queue_metrics
            },
            "streaming_status": {
                "enabled": self.is_streaming_response,
                "chunk_size": self.streaming_chunk_size,
                "tts_streaming": self.streaming_tts_enabled,
            },
        }

    async def _save_conversation(self):
        """Save conversation log to the database - preserved from original."""
        try:
            logger.info("Saving conversation log for call %s", self.call_sid)
            call_ended_at = datetime.now(UTC)
            call_started_at = self.metrics["conversation_start_time"]
            call_duration_seconds = (call_ended_at - call_started_at).total_seconds()

            # Get service information
            stt_service = "deepgramstt"
            llm_service = "openaillm"
            tts_service = "openaitts"
            # Serialize business_context to handle dataclass objects
            business_context_dict = None
            if self.business_data:
                business_context_dict = json.loads(
                    json.dumps(self.business_data.model_dump(), cls=DataclassJSONEncoder)
                )

            # Get caller phone number safely
            from_number = "unknown"
            if self.business_data.caller_info and self.business_data.caller_info.phone_number:
                from_number = self.business_data.caller_info.phone_number

            conversation_log = Conversation(
                business_id=self.business_data.business_id,
                twilio_call_sid=self.call_sid,
                from_number=from_number,
                to_number=self.business_data.business_phone_number,
                status="completed",
                duration=call_duration_seconds,
                call_started_at=call_started_at,
                call_ended_at=call_ended_at,
                conversation_history=self.conversation_history,
                business_context=business_context_dict,
                prompt_context=getattr(self.llm_service, "system_prompt", None),
                stt_service=stt_service,
                llm_service=llm_service,
                llm_model=self.llm_service.model,
                tts_service=tts_service,
                total_utterances=self.metrics["total_utterances"],
                successful_responses=self.metrics["successful_responses"],
                failed_responses=self.metrics["failed_responses"],
                average_response_time=self.metrics["average_response_time"],
            )

            self.session.add(conversation_log)
            self.session.commit()
            logger.info("Successfully saved conversation log for call %s", self.call_sid)

            # Update call minutes usage after successful conversation save
            try:
                call_duration_minutes = max(1, int(call_duration_seconds / 60))
                from ai_bridge_fastapi.api.routes.helpers import increment_call_minutes_usage

                await increment_call_minutes_usage(
                    self.business_data.business_id, call_duration_minutes
                )
                logger.info(
                    "Updated call minutes usage for business %s: +%d minutes (call duration: %.1fs)",
                    self.business_data.business_id,
                    call_duration_minutes,
                    call_duration_seconds,
                )
            except Exception:
                logger.exception("Failed to update call minutes usage")

        except Exception:
            logger.exception("Failed to save conversation log for call %s", self.call_sid)

wav_writer = None

async def entrypoint(ctx: JobContext):
    """LiveKit agent entry point."""
    
    logger.info("Starting LiveKit agent")
    
    @ctx.room.on("track_subscribed")
    def on_track_subscribed(track: rtc.RemoteTrack):
        print(f"Subscribed to track: {track.name}")

        asyncio.create_task(process_track(track))

    async def process_track(track: rtc.RemoteTrack):
        stt = deepgram.STT(model="nova-3")
        stt_stream = stt.stream()
        audio_stream = rtc.AudioStream(track)

        async with asyncio.TaskGroup() as tg:
            # Create task for processing STT stream
            stt_task = tg.create_task(process_stt_stream(stt_stream))

            # Process audio stream
            async for audio_event in audio_stream:
                stt_stream.push_frame(audio_event.frame)

            # Indicates the end of the audio stream
            stt_stream.end_input()

            # Wait for STT processing to complete
            await stt_task

    async def process_stt_stream(stream: AsyncIterable[SpeechEvent]):
        try:
            async for event in stream:
                if event.type == SpeechEventType.FINAL_TRANSCRIPT:
                    print(f"Final transcript: {event.alternatives[0].text}")
                elif event.type == SpeechEventType.INTERIM_TRANSCRIPT:
                    print(f"Interim transcript: {event.alternatives[0].text}")
                elif event.type == SpeechEventType.START_OF_SPEECH:
                    print("Start of speech")
                elif event.type == SpeechEventType.END_OF_SPEECH:
                    if event.alternatives:
                        print("End of speech", event.alternatives[0].text)
        finally:
            await stream.aclose()

    await ctx.connect(auto_subscribe=AutoSubscribe.AUDIO_ONLY)
    
    # Wait for participant to join
    participant = await ctx.wait_for_participant()
    
    try:
        json_metadata = participant.metadata or "{}"
        
        logger.info("Decoding participant metadata %s", json_metadata)
        participant_metadata = json.loads(json_metadata)
    except json.JSONDecodeError:
        logger.error("Failed to decode participant metadata, using defaults")
        participant_metadata = {
            "call_sid": "unknown",
            "caller_phone": "unknown",
            "to_number": "unknown"
        }
    
    with Session(engine) as session:
        
        call_sid = participant_metadata.get("call_sid", "unknown")
        caller_phone = participant_metadata.get("caller_phone", "unknown")  
        to_number = participant_metadata.get("to_number", "unknown")
        
        business_context = await get_business_data_for_call(
            session=session,
            call_sid=call_sid,
            caller_phone=caller_phone,
            to_number=to_number,
        )
        
        conversation_agent = LiveKitConversationAgent(
            business_data=business_context,
            session=session,
        )
        
        
        ctx.add_shutdown_callback(conversation_agent.stop_conversation)
    
    # Start conversation
    await conversation_agent.start_conversation(ctx.room)
    
    # Keep the agent running
    await asyncio.sleep(float('inf'))


if __name__ == "__main__":
    cli.run_app(WorkerOptions(entrypoint_fnc=entrypoint))
