"""
Tests for VoiceAgent and VoiceAgentCore

Tests agent initialization, lifecycle management, event handling,
and integration with conversation management.

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

from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from voice_agent_livekit.agent import (
    VoiceAgent,
    VoiceAgentCore,
)
from voice_agent_livekit.conversation import (
    ConversationManager,
    ConversationState,
)


class TestVoiceAgentCore:
    """Tests for VoiceAgentCore class"""

    def test_initialization_without_tools(self, mock_config):
        """Test creating agent core without tools"""
        conversation = ConversationManager("test_room")
        agent = VoiceAgentCore(
            config=mock_config,
            conversation=conversation,
        )

        assert agent.config == mock_config
        assert agent.conversation == conversation
        assert agent._tool_functions == {}
        assert isinstance(agent.instructions, str)

    def test_initialization_with_tools(self, mock_config):
        """Test creating agent core with tools"""
        conversation = ConversationManager("test_room")

        async def test_tool(conversation, **kwargs):
            return "Tool result"

        tools = {"test_tool": test_tool}

        agent = VoiceAgentCore(
            config=mock_config,
            conversation=conversation,
            tools=tools,
        )

        assert agent._tool_functions == tools
        assert len(agent._tool_functions) == 1
        assert "test_tool" in agent._tool_functions

    def test_build_system_instructions_basic(self, mock_config):
        """Test building basic system instructions"""
        conversation = ConversationManager("test_room")
        agent = VoiceAgentCore(
            config=mock_config,
            conversation=conversation,
        )

        instructions = agent.instructions
        assert "AI voice assistant" in instructions
        assert "presentation" in instructions.lower()
        assert "conversational" in instructions.lower()

    def test_build_system_instructions_with_tools(self, mock_config):
        """Test system instructions include tool information"""
        conversation = ConversationManager("test_room")

        async def navigate_tool(conversation, **kwargs):
            return "Navigate"

        async def generate_tool(conversation, **kwargs):
            return "Generate"

        tools = {
            "navigate_slide": navigate_tool,
            "generate_slide": generate_tool,
        }

        agent = VoiceAgentCore(
            config=mock_config,
            conversation=conversation,
            tools=tools,
        )

        instructions = agent.instructions
        assert "Available Tools" in instructions or "Tools" in instructions.lower()
        assert "navigate_slide" in instructions
        assert "generate_slide" in instructions


class TestVoiceAgent:
    """Tests for VoiceAgent class"""

    def test_initialization_without_config(self):
        """Test agent initialization with default config from environment"""
        with patch("voice_agent_livekit.agent.get_config") as mock_get_config, \
             patch("voice_agent_livekit.agent.setup_logging") as mock_setup_logging:

            mock_config = MagicMock()
            mock_get_config.return_value = mock_config
            mock_logger = MagicMock()
            mock_setup_logging.return_value = mock_logger

            agent = VoiceAgent()

            mock_get_config.assert_called_once()
            mock_setup_logging.assert_called_once_with(mock_config)
            assert agent.config == mock_config
            assert agent.conversation is None
            assert agent.session is None
            assert agent.ctx is None

    def test_initialization_with_config(self, mock_config):
        """Test agent initialization with provided config"""
        with patch("voice_agent_livekit.agent.setup_logging") as mock_setup_logging:
            mock_logger = MagicMock()
            mock_setup_logging.return_value = mock_logger

            agent = VoiceAgent(config=mock_config)

            assert agent.config == mock_config
            mock_setup_logging.assert_called_once_with(mock_config)

    def test_initialization_with_tools(self, mock_config):
        """Test agent initialization with tools"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            async def test_tool(**kwargs):
                return "result"

            tools = {"test_tool": test_tool}
            agent = VoiceAgent(config=mock_config, tools=tools)

            assert agent.tools == tools

    def test_on_participant_connected_registration(self, mock_config):
        """Test registering participant connected handler"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)

            async def handler(participant):
                pass

            agent.on_participant_connected(handler)
            assert handler in agent._participant_connected_handlers

    def test_on_participant_disconnected_registration(self, mock_config):
        """Test registering participant disconnected handler"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)

            async def handler(participant):
                pass

            agent.on_participant_disconnected(handler)
            assert handler in agent._participant_disconnected_handlers

    @pytest.mark.asyncio
    async def test_handle_participant_connected(self, mock_config, mock_participant):
        """Test handling participant connection"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)
            agent.conversation = ConversationManager("test_room")

            handler_called = False

            async def test_handler(participant):
                nonlocal handler_called
                handler_called = True

            agent.on_participant_connected(test_handler)

            await agent._handle_participant_connected(mock_participant)

            # Check conversation was updated
            assert mock_participant.sid in agent.conversation.participants

            # Check handler was called
            assert handler_called is True

    @pytest.mark.asyncio
    async def test_handle_participant_connected_no_conversation(
        self, mock_config, mock_participant
    ):
        """Test handling participant connection when conversation is None"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)
            # conversation is None

            # Should not raise error
            await agent._handle_participant_connected(mock_participant)

    @pytest.mark.asyncio
    async def test_handle_participant_disconnected(self, mock_config, mock_participant):
        """Test handling participant disconnection"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)
            agent.conversation = ConversationManager("test_room")
            agent.conversation.add_participant(mock_participant)

            handler_called = False

            async def test_handler(participant):
                nonlocal handler_called
                handler_called = True

            agent.on_participant_disconnected(test_handler)

            await agent._handle_participant_disconnected(mock_participant)

            # Check conversation was updated
            assert mock_participant.sid not in agent.conversation.participants

            # Check handler was called
            assert handler_called is True

    @pytest.mark.asyncio
    async def test_handle_participant_handler_error(self, mock_config, mock_participant):
        """Test that handler errors don't break participant handling"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)
            agent.conversation = ConversationManager("test_room")

            async def failing_handler(participant):
                raise ValueError("Handler error")

            agent.on_participant_connected(failing_handler)

            # Should not raise error
            await agent._handle_participant_connected(mock_participant)

            # Conversation should still be updated
            assert mock_participant.sid in agent.conversation.participants

    @pytest.mark.asyncio
    async def test_connect(self, mock_config, mock_job_context):
        """Test connecting agent to room"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)

            await agent.connect(mock_job_context)

            # Check agent state
            assert agent.ctx == mock_job_context
            assert agent.conversation is not None
            assert agent.session == mock_session
            assert agent.conversation.state == ConversationState.ACTIVE

            # Check session was started
            mock_session.start.assert_called_once()

            # Check greeting was sent
            mock_session.generate_reply.assert_called_once()

    @pytest.mark.asyncio
    async def test_connect_registers_room_handlers(self, mock_config, mock_job_context):
        """Test that connect registers room event handlers"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)

            await agent.connect(mock_job_context)

            # Check that room event handlers were registered
            assert "participant_connected" in mock_job_context.room._event_handlers
            assert "participant_disconnected" in mock_job_context.room._event_handlers

    @pytest.mark.asyncio
    async def test_connect_with_existing_participants(
        self, mock_config, mock_job_context, mock_participant
    ):
        """Test that connect handles existing room participants"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            # Add participant to room before connect
            mock_job_context.room.add_participant(mock_participant)

            agent = VoiceAgent(config=mock_config)
            await agent.connect(mock_job_context)

            # Participant should be in conversation
            assert mock_participant.sid in agent.conversation.participants

    @pytest.mark.asyncio
    async def test_connect_error_handling(self, mock_config, mock_job_context):
        """Test error handling during connect"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class:

            mock_session = AsyncMock()
            mock_session.start = AsyncMock(side_effect=Exception("Connection failed"))
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)

            # Expect any exception during connect
            with pytest.raises((ValueError, ConnectionError, RuntimeError)):
                await agent.connect(mock_job_context)

            # Conversation should be ended
            if agent.conversation:
                assert agent.conversation.state == ConversationState.ENDED

    @pytest.mark.asyncio
    async def test_send_greeting(self, mock_config, mock_job_context):
        """Test sending initial greeting"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)
            await agent.connect(mock_job_context)

            # Check greeting was added to conversation
            assistant_messages = [
                m for m in agent.conversation.messages
                if m.role.value == "assistant"
            ]
            assert len(assistant_messages) > 0
            assert mock_config.initial_greeting in assistant_messages[0].content

    @pytest.mark.asyncio
    async def test_send_message(self, mock_config, mock_job_context):
        """Test sending a message"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)
            await agent.connect(mock_job_context)

            initial_message_count = len(agent.conversation.messages)

            await agent.send_message("Test message")

            # Check message was added to conversation
            assert len(agent.conversation.messages) > initial_message_count

            # Check generate_reply was called
            assert mock_session.generate_reply.call_count > 1  # Greeting + message

    @pytest.mark.asyncio
    async def test_send_message_not_connected(self, mock_config):
        """Test sending message when not connected raises error"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)

            with pytest.raises(RuntimeError, match="not connected"):
                await agent.send_message("Test")

    @pytest.mark.asyncio
    async def test_disconnect(self, mock_config, mock_job_context):
        """Test disconnecting agent"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)
            await agent.connect(mock_job_context)

            await agent.disconnect()

            # Check state is cleaned up
            assert agent.session is None
            assert agent.conversation is None
            assert agent.ctx is None

    @pytest.mark.asyncio
    async def test_disconnect_sets_conversation_ended(
        self, mock_config, mock_job_context
    ):
        """Test that disconnect sets conversation state to ENDED"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)
            await agent.connect(mock_job_context)

            conversation = agent.conversation

            await agent.disconnect()

            # Conversation should be marked as ended
            assert conversation.state == ConversationState.ENDED

    def test_get_conversation_summary_connected(self, mock_config):
        """Test getting conversation summary when connected"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)
            agent.conversation = ConversationManager("test_room")
            agent.conversation.set_state(ConversationState.ACTIVE)

            summary = agent.get_conversation_summary()
            assert summary is not None
            assert "test_room" in summary

    def test_get_conversation_summary_not_connected(self, mock_config):
        """Test getting conversation summary when not connected"""
        with patch("voice_agent_livekit.agent.setup_logging"):
            agent = VoiceAgent(config=mock_config)

            summary = agent.get_conversation_summary()
            assert summary is None


class TestAgentIntegration:
    """Integration tests for agent components"""

    @pytest.mark.asyncio
    async def test_full_agent_lifecycle(self, mock_config, mock_job_context):
        """Test complete agent lifecycle from connect to disconnect"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)

            # Connect
            await agent.connect(mock_job_context)
            assert agent.conversation.state == ConversationState.ACTIVE

            # Send message
            await agent.send_message("Test message")

            # Check conversation has messages
            assert len(agent.conversation.messages) > 0

            # Disconnect
            await agent.disconnect()
            assert agent.conversation is None

    @pytest.mark.asyncio
    async def test_agent_with_participant_events(
        self, mock_config, mock_job_context, mock_participant
    ):
        """Test agent handling participant connect/disconnect events"""
        with patch("voice_agent_livekit.agent.setup_logging"), \
             patch("voice_agent_livekit.agent.AgentSession") as mock_session_class, \
             patch("voice_agent_livekit.agent.deepgram"), \
             patch("voice_agent_livekit.agent.silero"):

            mock_session = AsyncMock()
            mock_session.start = AsyncMock()
            mock_session.generate_reply = AsyncMock()
            mock_session_class.return_value = mock_session

            agent = VoiceAgent(config=mock_config)
            await agent.connect(mock_job_context)

            # Emit participant connected event
            await mock_job_context.room.emit("participant_connected", mock_participant)
            assert mock_participant.sid in agent.conversation.participants

            # Emit participant disconnected event
            await mock_job_context.room.emit("participant_disconnected", mock_participant)
            assert mock_participant.sid not in agent.conversation.participants
