"""
Tests for ConversationManager

Tests conversation state management, message history, participant tracking,
and state transitions.

Part of Issue #144 - Stream C: Testing & Validation
"""

from datetime import datetime, timedelta

from voice_agent_livekit.conversation import (
    ConversationManager,
    ConversationMessage,
    ConversationState,
    MessageRole,
    ParticipantInfo,
)


class TestConversationMessage:
    """Tests for ConversationMessage dataclass"""

    def test_message_creation(self):
        """Test creating a conversation message"""
        msg = ConversationMessage(
            role=MessageRole.USER,
            content="Hello",
        )
        assert msg.role == MessageRole.USER
        assert msg.content == "Hello"
        assert isinstance(msg.timestamp, datetime)
        assert msg.metadata == {}

    def test_message_to_dict(self):
        """Test converting message to dict for LLM API"""
        msg = ConversationMessage(
            role=MessageRole.ASSISTANT,
            content="Hi there!",
        )
        result = msg.to_dict()
        assert result == {
            "role": "assistant",
            "content": "Hi there!",
        }

    def test_message_with_metadata(self):
        """Test message with metadata"""
        metadata = {"confidence": 0.95, "source": "api"}
        msg = ConversationMessage(
            role=MessageRole.SYSTEM,
            content="System message",
            metadata=metadata,
        )
        assert msg.metadata == metadata


class TestParticipantInfo:
    """Tests for ParticipantInfo dataclass"""

    def test_participant_creation(self):
        """Test creating participant info"""
        info = ParticipantInfo(
            identity="user123",
            sid="sid123",
            name="Test User",
        )
        assert info.identity == "user123"
        assert info.sid == "sid123"
        assert info.name == "Test User"
        assert info.is_speaking is False
        assert isinstance(info.joined_at, datetime)

    def test_from_participant(self, mock_participant):
        """Test creating ParticipantInfo from LiveKit participant"""
        info = ParticipantInfo.from_participant(mock_participant)
        assert info.identity == mock_participant.identity
        assert info.sid == mock_participant.sid
        assert info.name == mock_participant.name


class TestConversationManager:
    """Tests for ConversationManager class"""

    def test_initialization(self):
        """Test conversation manager initialization"""
        conv = ConversationManager(
            room_name="test_room",
            max_history=100,
            idle_timeout_seconds=600,
        )
        assert conv.room_name == "test_room"
        assert conv.max_history == 100
        assert conv.idle_timeout_seconds == 600
        assert conv.state == ConversationState.INITIALIZING
        assert len(conv.messages) == 0
        assert len(conv.participants) == 0

    def test_add_message(self):
        """Test adding messages to conversation"""
        conv = ConversationManager("test_room")

        conv.add_message(MessageRole.USER, "Hello")
        assert len(conv.messages) == 1
        assert conv.messages[0].role == MessageRole.USER
        assert conv.messages[0].content == "Hello"

    def test_add_system_message(self):
        """Test convenience method for system messages"""
        conv = ConversationManager("test_room")
        conv.add_system_message("System initialized")

        assert len(conv.messages) == 1
        assert conv.messages[0].role == MessageRole.SYSTEM
        assert conv.messages[0].content == "System initialized"

    def test_add_user_message(self):
        """Test convenience method for user messages"""
        conv = ConversationManager("test_room")
        metadata = {"timestamp": "2024-01-01"}
        conv.add_user_message("User question", metadata=metadata)

        assert len(conv.messages) == 1
        assert conv.messages[0].role == MessageRole.USER
        assert conv.messages[0].content == "User question"
        assert conv.messages[0].metadata == metadata

    def test_add_assistant_message(self):
        """Test convenience method for assistant messages"""
        conv = ConversationManager("test_room")
        conv.add_assistant_message("Assistant response")

        assert len(conv.messages) == 1
        assert conv.messages[0].role == MessageRole.ASSISTANT
        assert conv.messages[0].content == "Assistant response"

    def test_message_history_trimming(self):
        """Test that message history is trimmed when exceeding max_history"""
        conv = ConversationManager("test_room", max_history=5)

        # Add system message
        conv.add_system_message("System message")

        # Add more messages than max_history
        for i in range(10):
            conv.add_user_message(f"Message {i}")

        # Should keep system message + most recent 4 user messages
        assert len(conv.messages) <= 5

        # System message should be preserved
        system_messages = [m for m in conv.messages if m.role == MessageRole.SYSTEM]
        assert len(system_messages) == 1

        # Most recent messages should be kept
        user_messages = [m for m in conv.messages if m.role == MessageRole.USER]
        assert "Message 9" in [m.content for m in user_messages]

    def test_get_messages_for_llm(self):
        """Test formatting messages for LLM API"""
        conv = ConversationManager("test_room")
        conv.add_system_message("You are helpful")
        conv.add_user_message("Hello")
        conv.add_assistant_message("Hi!")

        messages = conv.get_messages_for_llm()
        assert len(messages) == 3
        assert messages[0] == {"role": "system", "content": "You are helpful"}
        assert messages[1] == {"role": "user", "content": "Hello"}
        assert messages[2] == {"role": "assistant", "content": "Hi!"}

    def test_get_messages_for_llm_exclude_system(self):
        """Test getting messages without system messages"""
        conv = ConversationManager("test_room")
        conv.add_system_message("System")
        conv.add_user_message("Hello")
        conv.add_assistant_message("Hi!")

        messages = conv.get_messages_for_llm(include_system=False)
        assert len(messages) == 2
        assert all(m["role"] != "system" for m in messages)

    def test_add_participant(self, mock_participant):
        """Test adding a participant"""
        conv = ConversationManager("test_room")
        conv.add_participant(mock_participant)

        assert mock_participant.sid in conv.participants
        assert conv.participants[mock_participant.sid].identity == mock_participant.identity

        # Should add system message about participant joining
        system_messages = [m for m in conv.messages if m.role == MessageRole.SYSTEM]
        assert len(system_messages) == 1
        assert "joined" in system_messages[0].content.lower()

    def test_remove_participant(self, mock_participant):
        """Test removing a participant"""
        conv = ConversationManager("test_room")
        conv.add_participant(mock_participant)
        assert mock_participant.sid in conv.participants

        conv.remove_participant(mock_participant.sid)
        assert mock_participant.sid not in conv.participants

        # Should add system message about participant leaving
        system_messages = [m for m in conv.messages if m.role == MessageRole.SYSTEM]
        assert len(system_messages) == 2  # Join + Leave
        assert "left" in system_messages[-1].content.lower()

    def test_remove_nonexistent_participant(self):
        """Test removing participant that doesn't exist"""
        conv = ConversationManager("test_room")
        # Should not raise error
        conv.remove_participant("nonexistent_sid")

    def test_set_participant_speaking(self, mock_participant):
        """Test updating participant speaking status"""
        conv = ConversationManager("test_room")
        conv.add_participant(mock_participant)

        conv.set_participant_speaking(mock_participant.sid, True)
        assert conv.participants[mock_participant.sid].is_speaking is True

        # Should update last_activity_at
        old_activity = conv.last_activity_at
        conv.set_participant_speaking(mock_participant.sid, True)
        assert conv.last_activity_at >= old_activity

    def test_set_participant_speaking_nonexistent(self):
        """Test setting speaking status for nonexistent participant"""
        conv = ConversationManager("test_room")
        # Should not raise error
        conv.set_participant_speaking("nonexistent_sid", True)

    def test_set_state(self):
        """Test changing conversation state"""
        conv = ConversationManager("test_room")
        assert conv.state == ConversationState.INITIALIZING

        conv.set_state(ConversationState.GREETING)
        assert conv.state == ConversationState.GREETING

        conv.set_state(ConversationState.ACTIVE)
        assert conv.state == ConversationState.ACTIVE

    def test_is_idle(self):
        """Test checking if conversation is idle"""
        conv = ConversationManager("test_room", idle_timeout_seconds=1)

        # Should not be idle initially
        assert conv.is_idle() is False

        # Manually set last activity to past
        conv.last_activity_at = datetime.now() - timedelta(seconds=2)
        assert conv.is_idle() is True

        # Activity should reset idle state
        conv.add_user_message("Active message")
        assert conv.is_idle() is False

    def test_is_idle_when_ended(self):
        """Test that ended conversations are not marked as idle"""
        conv = ConversationManager("test_room", idle_timeout_seconds=1)
        conv.last_activity_at = datetime.now() - timedelta(seconds=2)
        conv.set_state(ConversationState.ENDED)

        # Ended conversations should not be considered idle
        assert conv.is_idle() is False

    def test_get_active_participants(self, mock_participant):
        """Test getting list of active participants"""
        conv = ConversationManager("test_room")
        assert len(conv.get_active_participants()) == 0

        conv.add_participant(mock_participant)
        participants = conv.get_active_participants()
        assert len(participants) == 1
        assert participants[0].sid == mock_participant.sid

    def test_get_conversation_context(self, mock_participant):
        """Test getting conversation context"""
        conv = ConversationManager("test_room")
        conv.add_participant(mock_participant)
        conv.add_user_message("Hello")
        conv.set_state(ConversationState.ACTIVE)

        context = conv.get_conversation_context()

        assert context["room_name"] == "test_room"
        assert context["state"] == "active"
        assert context["participant_count"] == 1
        # add_participant adds a system message, so we have 2 messages total
        assert context["message_count"] == 2
        assert "duration_seconds" in context
        assert "idle_seconds" in context
        assert len(context["participants"]) == 1
        assert context["participants"][0]["identity"] == mock_participant.identity

    def test_get_summary(self):
        """Test getting conversation summary"""
        conv = ConversationManager("test_room")
        conv.set_state(ConversationState.ACTIVE)
        conv.add_user_message("Test")

        summary = conv.get_summary()
        assert "test_room" in summary
        assert "active" in summary
        assert "0 participants" in summary or "participants" in summary
        assert "messages" in summary

    def test_reset(self, mock_participant):
        """Test resetting conversation state"""
        conv = ConversationManager("test_room")
        conv.add_participant(mock_participant)
        conv.add_user_message("Test message")
        conv.set_state(ConversationState.ACTIVE)

        conv.reset()

        assert len(conv.messages) == 0
        assert len(conv.participants) == 0
        assert conv.state == ConversationState.INITIALIZING

    def test_last_activity_updates(self):
        """Test that last_activity_at updates with messages"""
        conv = ConversationManager("test_room")
        initial_time = conv.last_activity_at

        # Small delay to ensure time difference
        import time
        time.sleep(0.01)

        conv.add_user_message("Activity")
        assert conv.last_activity_at > initial_time

    def test_multiple_participants(self):
        """Test managing multiple participants"""
        from tests.conftest import MockParticipant

        conv = ConversationManager("test_room")

        p1 = MockParticipant(identity="user1", sid="sid1")
        p2 = MockParticipant(identity="user2", sid="sid2")
        p3 = MockParticipant(identity="user3", sid="sid3")

        conv.add_participant(p1)
        conv.add_participant(p2)
        conv.add_participant(p3)

        assert len(conv.participants) == 3
        assert len(conv.get_active_participants()) == 3

        conv.remove_participant("sid2")
        assert len(conv.participants) == 2
        assert "sid2" not in conv.participants

    def test_conversation_state_enum(self):
        """Test all conversation states are valid"""
        states = [
            ConversationState.INITIALIZING,
            ConversationState.GREETING,
            ConversationState.ACTIVE,
            ConversationState.IDLE,
            ConversationState.ENDED,
        ]

        for state in states:
            conv = ConversationManager("test_room")
            conv.set_state(state)
            assert conv.state == state
