"""
Conversation state management for the Voice Agent.

This module tracks conversation history, participant state, and provides
context for the LLM to generate appropriate responses.

Enhanced for Issue #148 - Stream A: Track slide state for 3-participant coordination
"""

import logging
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
from typing import Any

from livekit import rtc

logger = logging.getLogger(__name__)


class ConversationState(Enum):
    """States of the conversation lifecycle."""

    INITIALIZING = "initializing"
    GREETING = "greeting"
    ACTIVE = "active"
    IDLE = "idle"
    ENDED = "ended"


class MessageRole(Enum):
    """Roles for conversation messages."""

    SYSTEM = "system"
    USER = "user"
    ASSISTANT = "assistant"


@dataclass
class ConversationMessage:
    """A single message in the conversation."""

    role: MessageRole
    content: str
    timestamp: datetime = field(default_factory=datetime.now)
    metadata: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        """Convert message to dictionary format for LLM APIs."""
        return {
            "role": self.role.value,
            "content": self.content,
        }


@dataclass
class ParticipantInfo:
    """Information about a room participant."""

    identity: str
    sid: str
    name: str | None = None
    joined_at: datetime = field(default_factory=datetime.now)
    is_speaking: bool = False
    metadata: dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_participant(cls, participant: rtc.Participant) -> "ParticipantInfo":
        """
        Create ParticipantInfo from LiveKit Participant.

        Args:
            participant: LiveKit participant object

        Returns:
            ParticipantInfo: Participant information
        """
        return cls(
            identity=participant.identity,
            sid=participant.sid,
            name=participant.name or participant.identity,
        )


class ConversationManager:
    """
    Manages conversation state and history.

    This class tracks:
    - Conversation messages (user, assistant, system)
    - Participant information
    - Conversation state (greeting, active, idle, etc.)
    - Context for LLM responses
    """

    def __init__(
        self,
        room_name: str,
        max_history: int = 50,
        idle_timeout_seconds: int = 300,
    ) -> None:
        """
        Initialize conversation manager.

        Args:
            room_name: Name of the LiveKit room
            max_history: Maximum number of messages to keep in history
            idle_timeout_seconds: Seconds of inactivity before marking idle
        """
        self.room_name = room_name
        self.max_history = max_history
        self.idle_timeout_seconds = idle_timeout_seconds

        # Conversation state
        self.state = ConversationState.INITIALIZING
        self.messages: list[ConversationMessage] = []
        self.participants: dict[str, ParticipantInfo] = {}

        # Timestamps
        self.started_at = datetime.now()
        self.last_activity_at = datetime.now()

        # Slide state tracking (Issue #148)
        self.current_slide: int | None = None
        self.total_slides: int | None = None
        self.deck_id: str | None = None

        logger.info(f"ConversationManager initialized for room: {room_name}")

    def add_message(
        self,
        role: MessageRole,
        content: str,
        metadata: dict[str, Any] | None = None,
    ) -> None:
        """
        Add a message to the conversation history.

        Args:
            role: Role of the message sender
            content: Message content
            metadata: Optional metadata for the message
        """
        message = ConversationMessage(
            role=role,
            content=content,
            metadata=metadata or {},
        )

        self.messages.append(message)
        self.last_activity_at = datetime.now()

        # Trim history if needed
        if len(self.messages) > self.max_history:
            # Keep system messages and trim oldest user/assistant messages
            system_messages = [m for m in self.messages if m.role == MessageRole.SYSTEM]
            other_messages = [m for m in self.messages if m.role != MessageRole.SYSTEM]

            # Keep most recent messages
            trimmed_others = other_messages[-(self.max_history - len(system_messages)):]
            self.messages = system_messages + trimmed_others

        logger.debug(f"Added message: {role.value}: {content[:50]}...")

    def add_system_message(self, content: str) -> None:
        """Add a system message to the conversation."""
        self.add_message(MessageRole.SYSTEM, content)

    def add_user_message(self, content: str, metadata: dict[str, Any] | None = None) -> None:
        """Add a user message to the conversation."""
        self.add_message(MessageRole.USER, content, metadata)

    def add_assistant_message(self, content: str, metadata: dict[str, Any] | None = None) -> None:
        """Add an assistant message to the conversation."""
        self.add_message(MessageRole.ASSISTANT, content, metadata)

    def get_messages_for_llm(self, include_system: bool = True) -> list[dict[str, Any]]:
        """
        Get conversation messages formatted for LLM APIs.

        Args:
            include_system: Whether to include system messages

        Returns:
            List of message dictionaries in LLM API format
        """
        messages = self.messages
        if not include_system:
            messages = [m for m in messages if m.role != MessageRole.SYSTEM]

        return [m.to_dict() for m in messages]

    def add_participant(self, participant: rtc.Participant) -> None:
        """
        Add a participant to the conversation.

        Args:
            participant: LiveKit participant object
        """
        info = ParticipantInfo.from_participant(participant)
        self.participants[participant.sid] = info

        logger.info(
            f"Participant joined: {info.name} (sid: {info.sid}, identity: {info.identity})"
        )

        # Add system message about participant joining
        self.add_system_message(f"Participant {info.name} joined the conversation")

    def remove_participant(self, participant_sid: str) -> None:
        """
        Remove a participant from the conversation.

        Args:
            participant_sid: Participant SID to remove
        """
        if participant_sid in self.participants:
            info = self.participants.pop(participant_sid)
            logger.info(f"Participant left: {info.name} (sid: {participant_sid})")

            # Add system message about participant leaving
            self.add_system_message(f"Participant {info.name} left the conversation")

    def set_participant_speaking(self, participant_sid: str, is_speaking: bool) -> None:
        """
        Update participant speaking status.

        Args:
            participant_sid: Participant SID
            is_speaking: Whether participant is currently speaking
        """
        if participant_sid in self.participants:
            self.participants[participant_sid].is_speaking = is_speaking

            if is_speaking:
                self.last_activity_at = datetime.now()

    def set_state(self, state: ConversationState) -> None:
        """
        Update conversation state.

        Args:
            state: New conversation state
        """
        old_state = self.state
        self.state = state
        logger.info(f"Conversation state changed: {old_state.value} -> {state.value}")

    def is_idle(self) -> bool:
        """
        Check if conversation has been idle too long.

        Returns:
            bool: True if conversation is idle
        """
        if self.state == ConversationState.ENDED:
            return False

        idle_seconds = (datetime.now() - self.last_activity_at).total_seconds()
        return idle_seconds > self.idle_timeout_seconds

    def get_active_participants(self) -> list[ParticipantInfo]:
        """
        Get list of active participants (excluding the agent).

        Returns:
            List of active participant information
        """
        return list(self.participants.values())

    def get_conversation_context(self) -> dict[str, Any]:
        """
        Get current conversation context for LLM.

        Returns:
            Dictionary with conversation context
        """
        context = {
            "room_name": self.room_name,
            "state": self.state.value,
            "participant_count": len(self.participants),
            "participants": [
                {
                    "name": p.name,
                    "identity": p.identity,
                    "is_speaking": p.is_speaking,
                }
                for p in self.participants.values()
            ],
            "message_count": len(self.messages),
            "duration_seconds": (datetime.now() - self.started_at).total_seconds(),
            "idle_seconds": (datetime.now() - self.last_activity_at).total_seconds(),
        }

        # Include slide state if available (Issue #148)
        if self.current_slide is not None:
            context["current_slide"] = self.current_slide
        if self.total_slides is not None:
            context["total_slides"] = self.total_slides
        if self.deck_id is not None:
            context["deck_id"] = self.deck_id

        return context

    def get_summary(self) -> str:
        """
        Get a human-readable summary of the conversation.

        Returns:
            String summary of conversation state
        """
        context = self.get_conversation_context()
        duration_minutes = int(context["duration_seconds"] / 60)

        return (
            f"Conversation in room '{self.room_name}' "
            f"({context['state']}, {duration_minutes}m, "
            f"{context['participant_count']} participants, "
            f"{context['message_count']} messages)"
        )

    def update_slide_state(
        self,
        current_slide: int,
        total_slides: int,
        deck_id: str
    ) -> None:
        """
        Update the current slide state from a navigation confirmation.

        This is called when receiving confirmations from the screenshare bot
        to keep the conversation context synchronized with the actual slide state.

        Args:
            current_slide: Current slide number
            total_slides: Total number of slides in the deck
            deck_id: Slide deck identifier

        Part of Issue #148 - Stream A: 3-Participant Coordination
        """
        self.current_slide = current_slide
        self.total_slides = total_slides
        self.deck_id = deck_id

        logger.info(
            f"Slide state updated: {current_slide}/{total_slides} (deck: {deck_id})"
        )

        # Add system message for context
        self.add_system_message(
            f"Now on slide {current_slide} of {total_slides}"
        )

    def get_slide_context(self) -> str | None:
        """
        Get current slide context as a human-readable string.

        Returns:
            Slide context string, or None if no slide state is tracked

        Part of Issue #148 - Stream A: 3-Participant Coordination
        """
        if self.current_slide is not None and self.total_slides is not None:
            return f"Currently on slide {self.current_slide} of {self.total_slides}"
        return None

    def reset(self) -> None:
        """Reset conversation state (for testing or recovery)."""
        self.messages.clear()
        self.participants.clear()
        self.state = ConversationState.INITIALIZING
        self.started_at = datetime.now()
        self.last_activity_at = datetime.now()

        # Reset slide state (Issue #148)
        self.current_slide = None
        self.total_slides = None
        self.deck_id = None

        logger.info("Conversation state reset")
