"""
End-to-End Integration Tests for Issue #148 3-Participant Coordination

Tests the complete flow:
1. Voice agent sends navigate command via Supabase broadcast
2. Screenshare bot receives command
3. Bot executes slide change (mocked)
4. Bot sends confirmation back via broadcast
5. Voice agent receives confirmation
6. Voice agent updates conversation state
7. Total latency measured (<500ms target)

Part of Issue #148 - Stream C: Integration Testing
"""

import pytest
import asyncio
import time
from unittest.mock import Mock, AsyncMock, MagicMock, patch
from typing import Dict, Any, Optional, List
from datetime import datetime, timezone

import sys
from pathlib import Path

# Add both paths to sys.path
sys.path.insert(0, str(Path(__file__).parent.parent))


# Mock slide navigator for bot side
class MockSlideNavigator:
    """Mock navigator that simulates slide changes"""

    def __init__(self):
        self.current_slide = 1
        self.total_slides = 10
        self.command_history = []

    async def execute_command(self, command: Dict[str, Any]) -> Dict[str, Any]:
        """Execute navigation command and return confirmation"""
        self.command_history.append(command)

        direction = command.get("direction")
        slide_number = command.get("slide_number")
        session_id = command.get("session_id", "unknown")

        # Simulate slide navigation
        if direction == "next":
            self.current_slide = min(self.current_slide + 1, self.total_slides)
        elif direction == "previous":
            self.current_slide = max(self.current_slide - 1, 1)
        elif direction == "goto" and slide_number:
            self.current_slide = slide_number

        # Return confirmation
        return {
            "type": "confirmation",
            "success": True,
            "current_slide": self.current_slide,
            "total_slides": self.total_slides,
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": session_id
        }


# Mock conversation manager for voice agent side
class MockConversationManager:
    """Mock conversation manager that tracks slide state"""

    def __init__(self):
        self.current_slide: Optional[int] = None
        self.total_slides: Optional[int] = None
        self.deck_id: Optional[str] = None
        self.state_updates = []

    def update_slide_state(
        self,
        current_slide: int,
        total_slides: int,
        deck_id: str
    ):
        """Update slide state from confirmation"""
        self.current_slide = current_slide
        self.total_slides = total_slides
        self.deck_id = deck_id
        self.state_updates.append({
            "current_slide": current_slide,
            "total_slides": total_slides,
            "deck_id": deck_id,
            "timestamp": time.time()
        })

    def get_slide_context(self) -> Optional[str]:
        """Get current slide context"""
        if self.current_slide is not None:
            return f"Slide {self.current_slide} of {self.total_slides}"
        return None


# Shared broadcast channel mock that both sides can use
class SharedBroadcastChannel:
    """
    Shared channel that simulates Supabase broadcast communication
    between voice agent and screenshare bot
    """

    def __init__(self, name: str):
        self.name = name
        self.navigate_callbacks = []
        self.confirmation_callbacks = []
        self.message_log = []
        self.network_latency_ms = 0  # Simulated network delay

    def on_broadcast(self, event: str, callback):
        """Register broadcast callback"""
        if event == "navigate":
            self.navigate_callbacks.append(callback)
        elif event == "confirmation":
            self.confirmation_callbacks.append(callback)
        return self

    async def send_broadcast(self, event: str, payload: Dict[str, Any]):
        """Send broadcast message to registered callbacks"""
        # Simulate network latency
        if self.network_latency_ms > 0:
            await asyncio.sleep(self.network_latency_ms / 1000.0)

        # Log message
        self.message_log.append({
            "event": event,
            "payload": payload,
            "timestamp": time.time()
        })

        # Deliver to appropriate callbacks
        if event == "navigate":
            for callback in self.navigate_callbacks:
                # Wrap in event structure
                callback({"payload": payload})
        elif event == "confirmation":
            for callback in self.confirmation_callbacks:
                callback({"payload": payload})

    def subscribe(self):
        """Subscribe to channel"""
        return self

    async def unsubscribe(self):
        """Unsubscribe from channel"""
        pass


class TestE2ESlideCoordination:
    """End-to-end tests for 3-participant slide coordination"""

    @pytest.mark.asyncio
    async def test_complete_navigate_flow(self):
        """
        Test complete flow: voice agent -> Supabase -> bot -> confirmation -> voice agent
        """
        # Setup shared channel
        channel = SharedBroadcastChannel("slide_control:deck_123")

        # Setup bot components
        navigator = MockSlideNavigator()

        async def bot_command_handler(command: Dict[str, Any]) -> Dict[str, Any]:
            """Bot's command handler"""
            return await navigator.execute_command(command)

        # Setup voice agent components
        conversation = MockConversationManager()

        # Import and setup actual listener
        from slide_control_listener import SlideControlListener

        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_e2e",
            on_command=bot_command_handler
        )

        # Inject shared channel
        listener._channel = channel

        # Register confirmation callback for voice agent
        received_confirmations = []

        def voice_agent_confirmation_handler(event):
            """Voice agent's confirmation handler"""
            confirmation = event["payload"]
            received_confirmations.append(confirmation)

            # Update conversation state
            conversation.update_slide_state(
                current_slide=confirmation["current_slide"],
                total_slides=confirmation["total_slides"],
                deck_id="deck_123"
            )

        channel.on_broadcast("confirmation", voice_agent_confirmation_handler)

        # Execute the flow
        start_time = time.time()

        # 1. Voice agent sends navigate command
        await channel.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_e2e"
        })

        # Wait for processing
        await asyncio.sleep(0.1)

        end_time = time.time()
        total_latency_ms = (end_time - start_time) * 1000

        # Verify the complete flow
        # 1. Bot received and executed command
        assert len(navigator.command_history) == 1
        assert navigator.command_history[0]["direction"] == "next"
        assert navigator.current_slide == 2  # Moved from 1 to 2

        # 2. Confirmation was sent back
        assert len(received_confirmations) == 1
        confirmation = received_confirmations[0]
        assert confirmation["success"] == True
        assert confirmation["current_slide"] == 2

        # 3. Voice agent updated conversation state
        assert conversation.current_slide == 2
        assert conversation.total_slides == 10
        assert len(conversation.state_updates) == 1

        # 4. Latency is within target
        assert total_latency_ms < 500, f"Total latency {total_latency_ms:.1f}ms exceeds 500ms target"

    @pytest.mark.asyncio
    async def test_goto_command_e2e(self):
        """Test end-to-end goto command with slide number"""
        channel = SharedBroadcastChannel("slide_control:deck_123")
        navigator = MockSlideNavigator()

        async def bot_command_handler(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_e2e",
            on_command=bot_command_handler
        )

        listener._channel = channel

        conversation = MockConversationManager()
        received_confirmations = []

        def voice_agent_confirmation_handler(event):
            confirmation = event["payload"]
            received_confirmations.append(confirmation)
            conversation.update_slide_state(
                current_slide=confirmation["current_slide"],
                total_slides=confirmation["total_slides"],
                deck_id="deck_123"
            )

        channel.on_broadcast("confirmation", voice_agent_confirmation_handler)

        # Send goto command
        await channel.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "goto",
            "slide_number": 7,
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_e2e"
        })

        await asyncio.sleep(0.1)

        # Verify goto worked
        assert navigator.current_slide == 7
        assert conversation.current_slide == 7

    @pytest.mark.asyncio
    async def test_multiple_commands_sequence(self):
        """Test sequence of multiple commands maintaining state"""
        channel = SharedBroadcastChannel("slide_control:deck_123")
        navigator = MockSlideNavigator()

        async def bot_command_handler(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_e2e",
            on_command=bot_command_handler
        )

        listener._channel = channel

        conversation = MockConversationManager()

        def voice_agent_confirmation_handler(event):
            confirmation = event["payload"]
            conversation.update_slide_state(
                current_slide=confirmation["current_slide"],
                total_slides=confirmation["total_slides"],
                deck_id="deck_123"
            )

        channel.on_broadcast("confirmation", voice_agent_confirmation_handler)

        # Execute sequence: next, next, goto 5, previous
        commands = [
            {"direction": "next"},
            {"direction": "next"},
            {"direction": "goto", "slide_number": 5},
            {"direction": "previous"}
        ]

        for cmd in commands:
            payload = {
                "type": "navigate",
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": "sess_e2e",
                **cmd
            }
            await channel.send_broadcast("navigate", payload)
            await asyncio.sleep(0.05)

        # Final state should be slide 4 (started at 1, +1, +1, goto 5, -1)
        assert navigator.current_slide == 4
        assert conversation.current_slide == 4
        assert len(navigator.command_history) == 4

    @pytest.mark.asyncio
    async def test_latency_measurement(self):
        """Test that total round-trip latency is measured accurately"""
        channel = SharedBroadcastChannel("slide_control:deck_123")
        navigator = MockSlideNavigator()

        async def bot_command_handler(command: Dict[str, Any]) -> Dict[str, Any]:
            # Simulate processing time
            await asyncio.sleep(0.05)
            return await navigator.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_e2e",
            on_command=bot_command_handler
        )

        listener._channel = channel

        latency_measurements = []

        def voice_agent_confirmation_handler(event):
            latency = time.time() - start_time
            latency_measurements.append(latency * 1000)

        channel.on_broadcast("confirmation", voice_agent_confirmation_handler)

        # Measure latency for command
        start_time = time.time()
        await channel.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_e2e"
        })

        await asyncio.sleep(0.2)

        # Verify latency was measured
        assert len(latency_measurements) == 1
        assert latency_measurements[0] < 500  # Within target

    @pytest.mark.asyncio
    async def test_session_isolation(self):
        """Test that commands for different sessions are isolated"""
        channel = SharedBroadcastChannel("slide_control:deck_123")

        # Setup two navigators for two sessions
        navigator_abc = MockSlideNavigator()
        navigator_xyz = MockSlideNavigator()

        async def bot_handler_abc(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator_abc.execute_command(command)

        async def bot_handler_xyz(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator_xyz.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener_abc = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_abc",
            on_command=bot_handler_abc
        )

        listener_xyz = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_xyz",
            on_command=bot_handler_xyz
        )

        listener_abc._channel = channel
        listener_xyz._channel = channel

        # Send commands to both sessions
        await channel.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await channel.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "goto",
            "slide_number": 5,
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_xyz"
        })

        await asyncio.sleep(0.1)

        # Verify session isolation
        assert len(navigator_abc.command_history) == 1
        assert navigator_abc.current_slide == 2  # next from 1

        assert len(navigator_xyz.command_history) == 1
        assert navigator_xyz.current_slide == 5  # goto 5

    @pytest.mark.asyncio
    async def test_error_recovery(self):
        """Test error scenarios and confirmation responses"""
        channel = SharedBroadcastChannel("slide_control:deck_123")

        # Navigator that fails on goto commands
        class FailingNavigator(MockSlideNavigator):
            async def execute_command(self, command: Dict[str, Any]) -> Dict[str, Any]:
                if command.get("direction") == "goto":
                    return {
                        "type": "confirmation",
                        "success": False,
                        "current_slide": self.current_slide,
                        "total_slides": self.total_slides,
                        "error": "goto not supported",
                        "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                        "session_id": command.get("session_id", "unknown")
                    }
                return await super().execute_command(command)

        navigator = FailingNavigator()

        async def bot_command_handler(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_e2e",
            on_command=bot_command_handler
        )

        listener._channel = channel

        received_confirmations = []

        def voice_agent_confirmation_handler(event):
            received_confirmations.append(event["payload"])

        channel.on_broadcast("confirmation", voice_agent_confirmation_handler)

        # Send goto command (will fail)
        await channel.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "goto",
            "slide_number": 5,
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_e2e"
        })

        await asyncio.sleep(0.1)

        # Verify error confirmation was received
        assert len(received_confirmations) == 1
        confirmation = received_confirmations[0]
        assert confirmation["success"] == False
        assert "error" in confirmation
        assert navigator.current_slide == 1  # No change

    @pytest.mark.asyncio
    async def test_high_latency_detection(self):
        """Test detection of high latency scenarios"""
        channel = SharedBroadcastChannel("slide_control:deck_123")
        # Simulate high network latency
        channel.network_latency_ms = 300

        navigator = MockSlideNavigator()

        async def bot_command_handler(command: Dict[str, Any]) -> Dict[str, Any]:
            # Simulate slow processing
            await asyncio.sleep(0.15)
            return await navigator.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_e2e",
            on_command=bot_command_handler
        )

        listener._channel = channel

        latency_measurements = []

        def voice_agent_confirmation_handler(event):
            latency = time.time() - start_time
            latency_measurements.append(latency * 1000)

        channel.on_broadcast("confirmation", voice_agent_confirmation_handler)

        # Measure total latency
        start_time = time.time()
        await channel.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_e2e"
        })

        await asyncio.sleep(0.8)

        # Verify high latency was detected
        assert len(latency_measurements) == 1
        # Total: 300ms network + 150ms processing + 300ms return ~= 750ms
        assert latency_measurements[0] > 500  # Exceeds target

    @pytest.mark.asyncio
    async def test_concurrent_multi_deck_coordination(self):
        """Test coordinating multiple decks simultaneously"""
        # Create separate channels for two decks
        channel_a = SharedBroadcastChannel("slide_control:deck_a")
        channel_b = SharedBroadcastChannel("slide_control:deck_b")

        navigator_a = MockSlideNavigator()
        navigator_b = MockSlideNavigator()

        async def bot_handler_a(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator_a.execute_command(command)

        async def bot_handler_b(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator_b.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener_a = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_a",
            session_id="sess_123",
            on_command=bot_handler_a
        )

        listener_b = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_b",
            session_id="sess_123",
            on_command=bot_handler_b
        )

        listener_a._channel = channel_a
        listener_b._channel = channel_b

        # Send different commands to each deck
        await channel_a.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_123"
        })

        await channel_b.send_broadcast("navigate", {
            "type": "navigate",
            "direction": "goto",
            "slide_number": 8,
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_123"
        })

        await asyncio.sleep(0.1)

        # Verify independent deck control
        assert navigator_a.current_slide == 2
        assert navigator_b.current_slide == 8

    @pytest.mark.asyncio
    async def test_message_log_ordering(self):
        """Test that messages are logged in correct order"""
        channel = SharedBroadcastChannel("slide_control:deck_123")
        navigator = MockSlideNavigator()

        async def bot_command_handler(command: Dict[str, Any]) -> Dict[str, Any]:
            return await navigator.execute_command(command)

        from slide_control_listener import SlideControlListener

        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_e2e",
            on_command=bot_command_handler
        )

        listener._channel = channel

        # Send multiple commands
        for i in range(3):
            await channel.send_broadcast("navigate", {
                "type": "navigate",
                "direction": "next",
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": "sess_e2e"
            })
            await asyncio.sleep(0.05)

        await asyncio.sleep(0.2)

        # Verify message log has all messages in order
        # Should have 3 navigate + 3 confirmation = 6 messages
        assert len(channel.message_log) == 6

        # Verify alternating pattern: navigate, confirmation, navigate, confirmation, ...
        for i in range(3):
            assert channel.message_log[i * 2]["event"] == "navigate"
            # Confirmation might not be at i*2+1 due to async, just check they exist

        confirmation_count = sum(1 for msg in channel.message_log if msg["event"] == "confirmation")
        assert confirmation_count == 3
