"""
Production-ready Voice Agent for LiveKit.

This module provides the main VoiceAgent class that handles:
- Room connection and lifecycle management
- Audio streaming (TTS/STT/VAD)
- Conversation state management
- Participant event handling
- Error handling and recovery
- Tool function integration (for Stream B)
"""

import logging
from collections.abc import Awaitable, Callable
from typing import Any, Protocol

from livekit import agents, rtc
from livekit.agents import Agent, AgentSession, JobContext
from livekit.plugins import deepgram, silero

from .config import AgentConfig, get_config, setup_logging
from .conversation import (
    ConversationManager,
    ConversationState,
)

logger = logging.getLogger(__name__)


# Tool function protocol for Stream B integration
class ToolFunction(Protocol):
    """
    Protocol for tool functions that the agent can call.

    Tool functions should be async and return a string result.
    They receive the conversation manager for context.
    """

    async def __call__(
        self,
        conversation: ConversationManager,
        **kwargs: Any,
    ) -> str:
        """Execute tool function and return result."""
        ...


class VoiceAgentCore(Agent):
    """
    Core Agent implementation that manages conversation flow.

    This class extends LiveKit's Agent to provide conversation intelligence,
    tool calling, and context management.
    """

    def __init__(
        self,
        config: AgentConfig,
        conversation: ConversationManager,
        tools: dict[str, ToolFunction] | None = None,
    ) -> None:
        """
        Initialize the voice agent core.

        Args:
            config: Agent configuration
            conversation: Conversation manager instance
            tools: Optional dictionary of tool functions for the agent to call
        """
        # System instructions for the agent
        instructions = self._build_system_instructions(config, tools)

        super().__init__(instructions=instructions)

        self.config = config
        self.conversation = conversation
        self._tool_functions = tools or {}

        logger.info("VoiceAgentCore initialized with tools: %s", list(self._tool_functions.keys()))

    def _build_system_instructions(
        self,
        config: AgentConfig,
        tools: dict[str, ToolFunction] | None = None,
    ) -> str:
        """
        Build system instructions for the LLM.

        Args:
            config: Agent configuration
            tools: Available tool functions

        Returns:
            System instructions string
        """
        instructions = [
            "You are a friendly AI voice assistant helping users navigate presentations.",
            "You can answer questions about the content and help users move through slides.",
            "",
            "Guidelines:",
            "- Be conversational and natural in your responses",
            "- Keep responses brief and to the point",
            "- Use casual language appropriate for voice interaction",
            "- If you don't know something, say so honestly",
            "- Avoid repeating information unnecessarily",
        ]

        # Add tool information if available
        if tools:
            instructions.extend([
                "",
                "Available Tools:",
            ])
            for tool_name in tools:
                instructions.append(f"- {tool_name}: Call this tool to perform specific actions")

        return "\n".join(instructions)


class VoiceAgent:
    """
    Production-ready Voice Agent for LiveKit.

    This class manages the complete agent lifecycle including:
    - Configuration and initialization
    - Room connection and participant management
    - Agent session lifecycle
    - Conversation state management
    - Error handling and recovery
    """

    def __init__(
        self,
        config: AgentConfig | None = None,
        tools: dict[str, ToolFunction] | None = None,
    ) -> None:
        """
        Initialize the voice agent.

        Args:
            config: Optional agent configuration. If not provided, loads from environment.
            tools: Optional dictionary of tool functions for the agent to call
        """
        # Load configuration
        self.config = config or get_config()

        # Setup logging
        self.logger = setup_logging(self.config)

        # Store tools for later use
        self.tools = tools or {}

        # Agent session components (initialized in connect)
        self.conversation: ConversationManager | None = None
        self.session: AgentSession | None = None
        self.ctx: JobContext | None = None

        # Event handlers
        self._participant_connected_handlers: list[Callable[[rtc.Participant], Awaitable[None]]] = []
        self._participant_disconnected_handlers: list[Callable[[rtc.Participant], Awaitable[None]]] = []

        self.logger.info("VoiceAgent initialized")
        self.logger.info(f"Available tools: {list(self.tools.keys())}")

    def on_participant_connected(
        self,
        handler: Callable[[rtc.Participant], Awaitable[None]],
    ) -> None:
        """
        Register a handler for participant connection events.

        Args:
            handler: Async function to call when participant connects
        """
        self._participant_connected_handlers.append(handler)

    def on_participant_disconnected(
        self,
        handler: Callable[[rtc.Participant], Awaitable[None]],
    ) -> None:
        """
        Register a handler for participant disconnection events.

        Args:
            handler: Async function to call when participant disconnects
        """
        self._participant_disconnected_handlers.append(handler)

    async def _handle_participant_connected(self, participant: rtc.Participant) -> None:
        """
        Handle participant connection event.

        Args:
            participant: The participant who connected
        """
        if not self.conversation:
            return

        self.logger.info(
            f"Participant connected: {participant.identity} (sid: {participant.sid})"
        )

        # Update conversation state
        self.conversation.add_participant(participant)

        # Call registered handlers
        for handler in self._participant_connected_handlers:
            try:
                await handler(participant)
            except Exception as e:
                self.logger.error(f"Error in participant connected handler: {e}", exc_info=True)

    async def _handle_participant_disconnected(self, participant: rtc.Participant) -> None:
        """
        Handle participant disconnection event.

        Args:
            participant: The participant who disconnected
        """
        if not self.conversation:
            return

        self.logger.info(
            f"Participant disconnected: {participant.identity} (sid: {participant.sid})"
        )

        # Update conversation state
        self.conversation.remove_participant(participant.sid)

        # Call registered handlers
        for handler in self._participant_disconnected_handlers:
            try:
                await handler(participant)
            except Exception as e:
                self.logger.error(f"Error in participant disconnected handler: {e}", exc_info=True)

    async def connect(self, ctx: JobContext) -> None:
        """
        Connect to LiveKit room and start agent session.

        This is the main entry point called by LiveKit when a job is created.

        Args:
            ctx: JobContext from LiveKit containing room and connection info

        Raises:
            Exception: If connection or initialization fails
        """
        # Connect to the LiveKit room
        await ctx.connect()

        self.ctx = ctx
        room_name = ctx.room.name

        try:
            self.logger.info(f"Connecting to room: {room_name}")

            # Initialize conversation manager
            self.conversation = ConversationManager(room_name=room_name)

            # Configure agent session with TTS/STT/LLM
            self.session = AgentSession(
                # Cartesia TTS through LiveKit Inference (uses LiveKit's free credits)
                tts=self.config.tts_model,
                # Deepgram STT
                stt=deepgram.STT(model=self.config.stt_model),
                # OpenAI LLM
                llm=self.config.llm_model,
                # Silero VAD
                vad=silero.VAD.load(),
            )

            self.logger.info("Agent session configured")

            # Register room event handlers with synchronous wrappers
            # (LiveKit .on() requires sync callbacks, so we use asyncio.create_task)
            def participant_connected_wrapper(participant: rtc.Participant) -> None:
                import asyncio
                asyncio.create_task(self._handle_participant_connected(participant))

            def participant_disconnected_wrapper(participant: rtc.Participant) -> None:
                import asyncio
                asyncio.create_task(self._handle_participant_disconnected(participant))

            ctx.room.on("participant_connected", participant_connected_wrapper)
            ctx.room.on("participant_disconnected", participant_disconnected_wrapper)

            # Create agent core with conversation context
            agent_core = VoiceAgentCore(
                config=self.config,
                conversation=self.conversation,
                tools=self.tools,
            )

            # Start the agent session
            await self.session.start(room=ctx.room, agent=agent_core)

            self.logger.info("Agent session started")

            # Update conversation state
            self.conversation.set_state(ConversationState.GREETING)

            # Generate initial greeting
            await self._send_greeting()

            # Update conversation state to active
            self.conversation.set_state(ConversationState.ACTIVE)

            self.logger.info("Agent is now active and listening")

            # Monitor for existing participants
            for participant in ctx.room.remote_participants.values():
                await self._handle_participant_connected(participant)

        except Exception as e:
            self.logger.error(f"Error in agent connect: {e}", exc_info=True)
            if self.conversation:
                self.conversation.set_state(ConversationState.ENDED)
            raise

    async def _send_greeting(self) -> None:
        """
        Send initial greeting to room participants.

        Raises:
            Exception: If greeting generation fails
        """
        if not self.session or not self.conversation:
            raise RuntimeError("Agent not connected")

        self.logger.info("Generating initial greeting")

        try:
            # Add greeting to conversation history
            self.conversation.add_assistant_message(self.config.initial_greeting)

            # Generate greeting speech
            await self.session.generate_reply(
                instructions=f"Say this greeting naturally: {self.config.initial_greeting}"
            )

            self.logger.info("Initial greeting sent")

        except Exception as e:
            self.logger.error(f"Error generating greeting: {e}", exc_info=True)
            raise

    async def send_message(self, message: str) -> None:
        """
        Send a message from the agent to participants.

        Args:
            message: Message content to send

        Raises:
            RuntimeError: If agent is not connected
        """
        if not self.session or not self.conversation:
            raise RuntimeError("Agent not connected")

        self.logger.debug(f"Sending message: {message[:50]}...")

        # Add to conversation history
        self.conversation.add_assistant_message(message)

        # Generate speech
        await self.session.generate_reply(instructions=f"Say this naturally: {message}")

    async def disconnect(self) -> None:
        """
        Disconnect from room and cleanup resources.
        """
        self.logger.info("Disconnecting agent")

        if self.conversation:
            self.conversation.set_state(ConversationState.ENDED)

        # Cleanup handled by LiveKit framework
        self.session = None
        self.conversation = None
        self.ctx = None

        self.logger.info("Agent disconnected")

    def get_conversation_summary(self) -> str | None:
        """
        Get summary of current conversation.

        Returns:
            Conversation summary string, or None if not connected
        """
        if self.conversation:
            return self.conversation.get_summary()
        return None


async def entrypoint(ctx: JobContext) -> None:
    """
    Main entry point for LiveKit agent.

    This function is called when a new job (room connection) is created.
    It creates a VoiceAgent instance and connects it to the room.

    Args:
        ctx: JobContext from LiveKit
    """
    logger.info(f"Agent entrypoint called for room: {ctx.room.name}")

    try:
        # Import tools
        from .tools import (
            generate_deck_tool,
            go_to_slide_tool,
            next_slide_tool,
            previous_slide_tool,
        )

        # Register tools for the agent
        tools = {
            "generate_deck": generate_deck_tool,
            "next_slide": next_slide_tool,
            "previous_slide": previous_slide_tool,
            "go_to_slide": go_to_slide_tool,
        }

        # Create agent instance with tools
        agent = VoiceAgent(tools=tools)

        # Connect to room and start agent
        await agent.connect(ctx)

        # Keep running until disconnected
        # (LiveKit handles the lifecycle)

    except Exception as e:
        logger.error(f"Error in agent entrypoint: {e}", exc_info=True)
        raise


def run_agent(
    room_name: str | None = None,
    config: AgentConfig | None = None,
) -> None:
    """
    Run the voice agent.

    This is a convenience function for running the agent directly.
    For production, use the LiveKit CLI with the entrypoint function.

    Args:
        room_name: Optional room name to join
        config: Optional agent configuration
    """
    # Load config if not provided
    if config is None:
        config = get_config()

    # Setup logging
    logger = setup_logging(config)

    logger.info("Starting Voice Agent")
    logger.info(f"LiveKit URL: {config.livekit_url}")
    logger.info(f"Room name: {room_name or config.livekit_room_name or 'auto-generated'}")

    # Run using LiveKit's CLI runner
    agents.cli.run_app(
        agents.WorkerOptions(
            entrypoint_fnc=entrypoint,
        )
    )


# Expose main entry point
__all__ = [
    "VoiceAgent",
    "VoiceAgentCore",
    "ToolFunction",
    "entrypoint",
    "run_agent",
]
