"""
Comprehensive Realtime Command Tests for Issue #148

Tests the full realtime flow of the broadcast channel protocol:
- Channel subscription with correct name format
- Receiving navigate commands
- Sending confirmation responses
- Latency measurement and alerting
- Error scenarios (invalid commands, missing fields)

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
from datetime import datetime, timezone, timedelta

import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from slide_control_listener import SlideControlListener


class MockBroadcastChannel:
    """Mock Supabase realtime channel for testing broadcast protocol"""

    def __init__(self, name: str):
        self.name = name
        self.broadcast_callbacks = {}
        self.sent_messages = []
        self.subscribed = False
        self.message_delay = 0.0  # Simulated network delay

    def on_broadcast(self, event: str, callback):
        """Register broadcast callback"""
        self.broadcast_callbacks[event] = callback
        return self

    async def send_broadcast(self, event: str, payload: Dict[str, Any]):
        """Send broadcast message (simulates confirmation response)"""
        if self.message_delay > 0:
            await asyncio.sleep(self.message_delay)

        self.sent_messages.append({
            "event": event,
            "payload": payload,
            "timestamp": time.time()
        })

    def subscribe(self):
        """Subscribe to channel"""
        self.subscribed = True
        return self

    async def unsubscribe(self):
        """Unsubscribe from channel"""
        self.subscribed = False

    async def simulate_navigate_command(self, payload: Dict[str, Any], delay: float = 0.0):
        """Simulate receiving a navigate command from voice agent"""
        if delay > 0:
            await asyncio.sleep(delay)

        if "navigate" in self.broadcast_callbacks:
            # Wrap payload in broadcast event structure
            event = {"payload": payload}
            self.broadcast_callbacks["navigate"](event)


class TestChannelSubscription:
    """Test channel subscription with correct channel name format"""

    @pytest.mark.asyncio
    async def test_channel_name_format(self):
        """Test that channel follows slide_control:{deckId} format"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="my_deck_abc123",
            session_id="sess_123",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:my_deck_abc123")
        mock_client = MagicMock()
        mock_client.channel = MagicMock(return_value=mock_channel)

        with patch('slide_control_listener.create_client', return_value=mock_client):
            await listener.start()

            # Verify channel name format
            mock_client.channel.assert_called_once_with('slide_control:my_deck_abc123')
            assert listener.is_connected

    @pytest.mark.asyncio
    async def test_channel_subscribes_to_navigate_event(self):
        """Test that channel subscribes to 'navigate' broadcast event"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_123",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        mock_client = MagicMock()
        mock_client.channel = MagicMock(return_value=mock_channel)

        with patch('slide_control_listener.create_client', return_value=mock_client):
            await listener.start()

            # Verify navigate event callback is registered
            assert 'navigate' in mock_channel.broadcast_callbacks
            assert callable(mock_channel.broadcast_callbacks['navigate'])

    @pytest.mark.asyncio
    async def test_multiple_deck_isolation(self):
        """Test that different deck IDs create separate channels"""
        callback1 = AsyncMock()
        callback2 = AsyncMock()

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

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

        mock_channel_a = MockBroadcastChannel("slide_control:deck_a")
        mock_channel_b = MockBroadcastChannel("slide_control:deck_b")

        mock_client = MagicMock()
        mock_client.channel = MagicMock(side_effect=[mock_channel_a, mock_channel_b])

        with patch('slide_control_listener.create_client', return_value=mock_client):
            await listener1.start()
            await listener2.start()

            # Verify separate channels created
            assert mock_client.channel.call_count == 2
            assert mock_client.channel.call_args_list[0][0][0] == 'slide_control:deck_a'
            assert mock_client.channel.call_args_list[1][0][0] == 'slide_control:deck_b'


class TestNavigateCommands:
    """Test receiving navigate commands via broadcast"""

    @pytest.mark.asyncio
    async def test_receive_next_command(self):
        """Test receiving and processing 'next' command"""
        received_commands = []

        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            received_commands.append(command)
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 2,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        # Simulate navigate command
        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        # Verify command was received and processed
        assert len(received_commands) == 1
        assert received_commands[0]["direction"] == "next"

    @pytest.mark.asyncio
    async def test_receive_previous_command(self):
        """Test receiving and processing 'previous' command"""
        received_commands = []

        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            received_commands.append(command)
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "previous",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        assert len(received_commands) == 1
        assert received_commands[0]["direction"] == "previous"

    @pytest.mark.asyncio
    async def test_receive_goto_command(self):
        """Test receiving and processing 'goto' command with slide number"""
        received_commands = []

        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            received_commands.append(command)
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": command.get("slide_number", 1),
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "goto",
            "slide_number": 7,
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        assert len(received_commands) == 1
        assert received_commands[0]["direction"] == "goto"
        assert received_commands[0]["slide_number"] == 7


class TestConfirmationResponses:
    """Test sending confirmation responses back via broadcast"""

    @pytest.mark.asyncio
    async def test_send_success_confirmation(self):
        """Test sending successful confirmation response"""
        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 3,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        # Verify confirmation was sent
        assert len(mock_channel.sent_messages) == 1
        confirmation = mock_channel.sent_messages[0]
        assert confirmation["event"] == "confirmation"
        assert confirmation["payload"]["type"] == "confirmation"
        assert confirmation["payload"]["success"] == True
        assert confirmation["payload"]["current_slide"] == 3
        assert confirmation["payload"]["total_slides"] == 10
        assert "session_id" in confirmation["payload"]

    @pytest.mark.asyncio
    async def test_send_error_confirmation(self):
        """Test sending error confirmation when command fails"""
        async def failing_callback(command: Dict[str, Any]) -> Dict[str, Any]:
            raise Exception("Navigation failed")

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        # Verify error confirmation was sent
        assert len(mock_channel.sent_messages) == 1
        confirmation = mock_channel.sent_messages[0]
        assert confirmation["payload"]["success"] == False
        assert "error" in confirmation["payload"]

    @pytest.mark.asyncio
    async def test_confirmation_includes_session_id(self):
        """Test that confirmation response includes session_id from command"""
        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_unique_123"
        })

        await asyncio.sleep(0.1)

        # Verify session_id matches
        confirmation = mock_channel.sent_messages[0]
        assert confirmation["payload"]["session_id"] == "sess_unique_123"


class TestLatencyMeasurement:
    """Test latency measurement and alerting (>500ms target)"""

    @pytest.mark.asyncio
    async def test_latency_calculation(self):
        """Test that latency is calculated from command timestamp"""
        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            # Simulate some processing time
            await asyncio.sleep(0.05)
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        # Create command with timestamp in the past
        past_time = datetime.now(timezone.utc) - timedelta(milliseconds=100)
        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": past_time.isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.2)

        # Verify latency was tracked
        metrics = listener.metrics
        assert metrics["command_count"] == 1
        assert metrics["avg_latency_ms"] >= 100  # At least 100ms from past timestamp
        assert metrics["max_latency_ms"] >= 100

    @pytest.mark.asyncio
    async def test_high_latency_warning(self):
        """Test that high latency (>500ms) is detected and logged"""
        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        # Create command with old timestamp (simulate high latency)
        old_time = datetime.now(timezone.utc) - timedelta(milliseconds=600)

        with patch('slide_control_listener.logger') as mock_logger:
            await mock_channel.simulate_navigate_command({
                "type": "navigate",
                "direction": "next",
                "timestamp": old_time.isoformat().replace('+00:00', 'Z'),
                "session_id": "sess_abc"
            })

            await asyncio.sleep(0.1)

            # Verify warning was logged
            # Look for warning calls about high latency
            warning_calls = [call for call in mock_logger.warning.call_args_list
                           if call[0] and '500ms' in str(call[0][0])]
            assert len(warning_calls) > 0

    @pytest.mark.asyncio
    async def test_average_latency_tracking(self):
        """Test that average latency is calculated correctly across multiple commands"""
        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        # Send multiple commands with varying latencies
        for delay_ms in [50, 100, 150]:
            past_time = datetime.now(timezone.utc) - timedelta(milliseconds=delay_ms)
            await mock_channel.simulate_navigate_command({
                "type": "navigate",
                "direction": "next",
                "timestamp": past_time.isoformat().replace('+00:00', 'Z'),
                "session_id": "sess_abc"
            })
            await asyncio.sleep(0.1)

        # Verify average latency is in expected range
        metrics = listener.metrics
        assert metrics["command_count"] == 3
        assert 50 <= metrics["avg_latency_ms"] <= 200  # Average of 50, 100, 150
        assert metrics["max_latency_ms"] >= 150


class TestErrorScenarios:
    """Test error scenarios (invalid commands, missing fields)"""

    @pytest.mark.asyncio
    async def test_invalid_direction(self):
        """Test handling of invalid navigation direction"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_abc",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "invalid_direction",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        # Callback should not be invoked
        callback.assert_not_called()
        # Error confirmation should be sent
        assert len(mock_channel.sent_messages) == 1
        assert mock_channel.sent_messages[0]["payload"]["success"] == False

    @pytest.mark.asyncio
    async def test_missing_direction_field(self):
        """Test handling of command with missing direction field"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_abc",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            # Missing direction
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        callback.assert_not_called()
        assert len(mock_channel.sent_messages) == 1
        assert mock_channel.sent_messages[0]["payload"]["success"] == False
        assert "direction" in mock_channel.sent_messages[0]["payload"]["error"].lower()

    @pytest.mark.asyncio
    async def test_goto_missing_slide_number(self):
        """Test handling of goto command without slide_number"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_abc",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "goto",
            # Missing slide_number
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        callback.assert_not_called()
        assert len(mock_channel.sent_messages) == 1
        assert mock_channel.sent_messages[0]["payload"]["success"] == False
        assert "slide_number" in mock_channel.sent_messages[0]["payload"]["error"].lower()

    @pytest.mark.asyncio
    async def test_invalid_message_type(self):
        """Test handling of message with wrong type field"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_abc",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "wrong_type",  # Should be "navigate"
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        # Should be ignored (no callback, no confirmation)
        callback.assert_not_called()
        # No confirmation sent for wrong type (early return in handler)
        assert len(mock_channel.sent_messages) == 0

    @pytest.mark.asyncio
    async def test_session_id_mismatch(self):
        """Test that commands for different sessions are ignored"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_abc",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_different"  # Different session
        })

        await asyncio.sleep(0.1)

        # Should be ignored completely
        callback.assert_not_called()
        assert len(mock_channel.sent_messages) == 0

    @pytest.mark.asyncio
    async def test_callback_exception_handling(self):
        """Test that callback exceptions are caught and error confirmation sent"""
        async def failing_callback(command: Dict[str, Any]) -> Dict[str, Any]:
            raise RuntimeError("Callback failed unexpectedly")

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        # Should not crash
        await mock_channel.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_abc"
        })

        await asyncio.sleep(0.1)

        # Error confirmation should be sent
        assert len(mock_channel.sent_messages) == 1
        confirmation = mock_channel.sent_messages[0]
        assert confirmation["payload"]["success"] == False
        assert "error" in confirmation["payload"]["error"].lower()


class TestConcurrentCommands:
    """Test handling of concurrent/rapid commands"""

    @pytest.mark.asyncio
    async def test_rapid_command_sequence(self):
        """Test that rapid commands are all processed"""
        received_commands = []

        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            received_commands.append(command)
            await asyncio.sleep(0.01)  # Simulate processing time
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": len(received_commands),
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        listener._channel = mock_channel

        # Send 5 rapid commands
        for i in range(5):
            await mock_channel.simulate_navigate_command({
                "type": "navigate",
                "direction": "next",
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": "sess_abc"
            })
            # Small delay between commands
            await asyncio.sleep(0.02)

        # Wait for all to process
        await asyncio.sleep(0.3)

        # All commands should be processed
        assert len(received_commands) == 5
        assert len(mock_channel.sent_messages) == 5

    @pytest.mark.asyncio
    async def test_concurrent_sessions(self):
        """Test that commands from different sessions are properly filtered"""
        received_abc = []
        received_xyz = []

        async def callback_abc(command: Dict[str, Any]) -> Dict[str, Any]:
            received_abc.append(command)
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

        async def callback_xyz(command: Dict[str, Any]) -> Dict[str, Any]:
            received_xyz.append(command)
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

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

        # Each listener gets its own channel mock
        mock_channel_abc = MockBroadcastChannel("slide_control:deck_123")
        mock_channel_xyz = MockBroadcastChannel("slide_control:deck_123")

        listener_abc._channel = mock_channel_abc
        listener_xyz._channel = mock_channel_xyz

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

        await mock_channel_xyz.simulate_navigate_command({
            "type": "navigate",
            "direction": "next",
            "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
            "session_id": "sess_xyz"
        })

        await asyncio.sleep(0.1)

        # Each listener should only receive its own commands
        assert len(received_abc) == 1
        assert len(received_xyz) == 1


class TestChannelCleanup:
    """Test channel cleanup on disconnect"""

    @pytest.mark.asyncio
    async def test_cleanup_on_stop(self):
        """Test that channel is properly cleaned up when listener stops"""
        callback = AsyncMock()
        listener = SlideControlListener(
            supabase_url="https://test.supabase.co",
            supabase_key="test-key",
            deck_id="deck_123",
            session_id="sess_abc",
            on_command=callback
        )

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        mock_client = MagicMock()
        mock_client.channel = MagicMock(return_value=mock_channel)

        with patch('slide_control_listener.create_client', return_value=mock_client):
            await listener.start()
            assert listener.is_connected
            assert mock_channel.subscribed

            await listener.stop()
            assert not listener.is_connected
            assert not mock_channel.subscribed

    @pytest.mark.asyncio
    async def test_metrics_logged_on_stop(self):
        """Test that metrics are logged when listener stops"""
        async def callback(command: Dict[str, Any]) -> Dict[str, Any]:
            return {
                "type": "confirmation",
                "success": True,
                "current_slide": 1,
                "total_slides": 10,
                "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                "session_id": command["session_id"]
            }

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

        mock_channel = MockBroadcastChannel("slide_control:deck_123")
        mock_client = MagicMock()
        mock_client.channel = MagicMock(return_value=mock_channel)

        with patch('slide_control_listener.create_client', return_value=mock_client):
            await listener.start()

            # Process some commands
            listener._channel = mock_channel
            for _ in range(3):
                await mock_channel.simulate_navigate_command({
                    "type": "navigate",
                    "direction": "next",
                    "timestamp": datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
                    "session_id": "sess_abc"
                })
                await asyncio.sleep(0.05)

            # Stop and verify metrics were logged
            with patch('slide_control_listener.logger') as mock_logger:
                await listener.stop()

                # Check that metrics were logged
                info_calls = [str(call) for call in mock_logger.info.call_args_list]
                metrics_logged = any('metrics' in call.lower() for call in info_calls)
                assert metrics_logged
