"""
Tests for Issue #148: 3-Participant Slide Coordination

Tests the realtime slide navigation protocol between voice agent and screenshare bot.
Validates message format, confirmation handling, and slide state tracking.

Part of Issue #148 - Stream A: Voice Agent Tool Implementation
"""

import asyncio
from datetime import UTC, datetime
from typing import Any

import pytest

from voice_agent_livekit.conversation import ConversationManager
from voice_agent_livekit.tools import initialize_slide_control, navigate_slide


class MockRealtimeChannel:
    """Mock Supabase realtime channel for testing"""

    def __init__(self, name: str):
        self.name = name
        self.messages = []
        self.subscribed = False
        self.callbacks = {}

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

    def send(self, message: dict[str, Any]):
        """Send message to channel"""
        self.messages.append(message)

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

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

    def simulate_confirmation(self, payload: dict[str, Any]):
        """Simulate receiving a confirmation from screenshare bot"""
        if "confirmation" in self.callbacks:
            self.callbacks["confirmation"](payload)


class MockSupabaseClientWithRealtime:
    """Mock Supabase client with realtime channel support for Issue #148"""

    def __init__(self, session_id: str = "test_session"):
        self.session_id = session_id
        self.channels: dict[str, MockRealtimeChannel] = {}
        self._confirmation_callbacks = {}
        self.commands = []

    def channel(self, name: str) -> MockRealtimeChannel:
        """Get or create a channel"""
        if name not in self.channels:
            self.channels[name] = MockRealtimeChannel(name)
        return self.channels[name]

    async def publish_slide_navigation(
        self,
        deck_id: str,
        direction: str,
        slide_number: int = None,
        timeout: float = 5.0
    ) -> dict[str, Any]:
        """
        Mock implementation of publish_slide_navigation that follows Issue #148 protocol
        """
        # Validate direction
        valid_directions = {"next", "previous", "goto"}
        if direction not in valid_directions:
            raise ValueError(f"Invalid direction: {direction}")

        # Validate slide_number for goto
        if direction == "goto":
            if slide_number is None:
                raise ValueError("slide_number is required for 'goto' direction")
            if not isinstance(slide_number, int) or slide_number < 1:
                raise ValueError("slide_number must be a positive integer")

        # Build message according to Issue #148 protocol
        message = {
            "type": "navigate",
            "direction": direction,
            "timestamp": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
            "session_id": self.session_id
        }

        if slide_number is not None:
            message["slide_number"] = slide_number

        # Store command for verification
        self.commands.append({
            "deck_id": deck_id,
            "message": message
        })

        channel_name = f"slide_control:{deck_id}"
        channel = self.channel(channel_name)

        # Publish message
        channel.send({
            "type": "broadcast",
            "event": "navigate",
            "payload": message
        })

        # Simulate confirmation from screenshare bot
        confirmation = {
            "type": "confirmation",
            "success": True,
            "current_slide": slide_number if direction == "goto" else 2,
            "total_slides": 10,
            "timestamp": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
            "session_id": self.session_id
        }

        return confirmation

    async def cleanup(self):
        """Cleanup channels"""
        self.channels.clear()


@pytest.fixture
def mock_realtime_client():
    """Fixture providing a mock Supabase client with realtime support"""
    return MockSupabaseClientWithRealtime(session_id="test_session_123")


@pytest.fixture
def initialized_realtime_tools(mock_realtime_client):
    """Fixture that initializes tools with realtime-enabled mock client"""
    initialize_slide_control(mock_realtime_client)
    return mock_realtime_client


@pytest.fixture
def conversation_manager():
    """Fixture providing a conversation manager"""
    return ConversationManager(room_name="test_room")


# Issue #148 Protocol Tests


@pytest.mark.asyncio
async def test_navigate_next_with_confirmation(initialized_realtime_tools):
    """Test navigating to next slide with confirmation from bot"""
    result = await navigate_slide(direction="next", deck_id="deck_123")

    # Verify command was sent
    assert len(initialized_realtime_tools.commands) == 1
    command = initialized_realtime_tools.commands[0]

    # Verify Issue #148 message format
    message = command["message"]
    assert message["type"] == "navigate"
    assert message["direction"] == "next"
    assert "timestamp" in message
    assert message["session_id"] == "test_session_123"
    assert "slide_number" not in message  # Not required for next

    # Verify channel name format
    assert command["deck_id"] == "deck_123"

    # Verify user-facing result includes slide info
    assert "slide" in result.lower()
    assert "2" in result  # Mock returns slide 2


@pytest.mark.asyncio
async def test_navigate_previous_with_confirmation(initialized_realtime_tools):
    """Test navigating to previous slide with confirmation"""
    result = await navigate_slide(direction="previous", deck_id="deck_123")

    assert len(initialized_realtime_tools.commands) == 1
    command = initialized_realtime_tools.commands[0]

    # Verify direction is normalized to "previous"
    assert command["message"]["direction"] == "previous"
    assert "previous" in result.lower() or "slide" in result.lower()


@pytest.mark.asyncio
async def test_navigate_goto_with_confirmation(initialized_realtime_tools):
    """Test navigating to specific slide with confirmation"""
    result = await navigate_slide(direction="goto", slide_number=5, deck_id="deck_123")

    assert len(initialized_realtime_tools.commands) == 1
    command = initialized_realtime_tools.commands[0]

    # Verify Issue #148 message format for goto
    message = command["message"]
    assert message["type"] == "navigate"
    assert message["direction"] == "goto"
    assert message["slide_number"] == 5  # Required for goto
    assert "timestamp" in message

    # Verify result
    assert "5" in result


@pytest.mark.asyncio
async def test_message_timestamp_format(initialized_realtime_tools):
    """Test that timestamps follow ISO 8601 format as per Issue #148"""
    await navigate_slide(direction="next", deck_id="deck_123")

    command = initialized_realtime_tools.commands[0]
    timestamp = command["message"]["timestamp"]

    # Verify ISO 8601 format with Z suffix
    assert timestamp.endswith("Z")
    assert "T" in timestamp

    # Verify it's a valid ISO format
    datetime.fromisoformat(timestamp.replace("Z", "+00:00"))


@pytest.mark.asyncio
async def test_channel_name_format(initialized_realtime_tools):
    """Test that channel names follow slide_control:{deckId} format"""
    await navigate_slide(direction="next", deck_id="my_deck_abc123")

    # Verify channel was created with correct name
    channel_name = "slide_control:my_deck_abc123"
    assert channel_name in initialized_realtime_tools.channels

    # Verify message was sent to correct channel
    channel = initialized_realtime_tools.channels[channel_name]
    assert len(channel.messages) > 0


@pytest.mark.asyncio
async def test_session_id_tracking(initialized_realtime_tools):
    """Test that session_id is included in all messages"""
    await navigate_slide(direction="next", deck_id="deck_123")
    await navigate_slide(direction="previous", deck_id="deck_123")
    await navigate_slide(direction="goto", slide_number=7, deck_id="deck_123")

    # All messages should include the same session_id
    for command in initialized_realtime_tools.commands:
        assert command["message"]["session_id"] == "test_session_123"


@pytest.mark.asyncio
async def test_confirmation_response_format(initialized_realtime_tools):
    """Test that confirmation responses follow Issue #148 format"""
    result = await navigate_slide(direction="next", deck_id="deck_123")

    # The mock returns a proper confirmation
    # In real implementation, this would be received from screenshare bot
    # Verify the result message includes slide context
    assert "slide" in result.lower()
    assert "10" in result  # total slides from mock


@pytest.mark.asyncio
async def test_conversation_state_update(conversation_manager):
    """Test that conversation state tracks slide position"""
    # Update slide state
    conversation_manager.update_slide_state(
        current_slide=5,
        total_slides=10,
        deck_id="deck_123"
    )

    # Verify state is tracked
    assert conversation_manager.current_slide == 5
    assert conversation_manager.total_slides == 10
    assert conversation_manager.deck_id == "deck_123"

    # Verify context includes slide info
    context = conversation_manager.get_conversation_context()
    assert context["current_slide"] == 5
    assert context["total_slides"] == 10
    assert context["deck_id"] == "deck_123"


@pytest.mark.asyncio
async def test_slide_context_string(conversation_manager):
    """Test getting slide context as human-readable string"""
    # Before setting slide state
    assert conversation_manager.get_slide_context() is None

    # After setting slide state
    conversation_manager.update_slide_state(
        current_slide=3,
        total_slides=8,
        deck_id="deck_123"
    )

    context_str = conversation_manager.get_slide_context()
    assert "3" in context_str
    assert "8" in context_str
    assert "slide" in context_str.lower()


@pytest.mark.asyncio
async def test_multiple_deck_coordination(initialized_realtime_tools):
    """Test coordinating slides across multiple decks"""
    # Navigate in first deck
    await navigate_slide(direction="next", deck_id="deck_a")

    # Navigate in second deck
    await navigate_slide(direction="next", deck_id="deck_b")

    # Verify separate channels were created
    assert "slide_control:deck_a" in initialized_realtime_tools.channels
    assert "slide_control:deck_b" in initialized_realtime_tools.channels

    # Verify commands were sent to correct decks
    assert initialized_realtime_tools.commands[0]["deck_id"] == "deck_a"
    assert initialized_realtime_tools.commands[1]["deck_id"] == "deck_b"


@pytest.mark.asyncio
async def test_rapid_navigation_sequence(initialized_realtime_tools):
    """Test rapid successive navigation commands"""
    # Simulate rapid navigation
    results = await asyncio.gather(
        navigate_slide(direction="next", deck_id="deck_123"),
        navigate_slide(direction="next", deck_id="deck_123"),
        navigate_slide(direction="goto", slide_number=5, deck_id="deck_123"),
    )

    # All commands should complete
    assert len(results) == 3
    assert all(isinstance(r, str) for r in results)

    # All commands should be tracked
    assert len(initialized_realtime_tools.commands) == 3


@pytest.mark.asyncio
async def test_error_handling_invalid_direction(initialized_realtime_tools):
    """Test error handling for invalid navigation direction"""
    # The normalize_slide method should handle this gracefully
    result = await navigate_slide(direction="next", deck_id="deck_123")
    assert "error" not in result.lower() or "slide" in result.lower()


@pytest.mark.asyncio
async def test_error_handling_goto_without_slide_number(initialized_realtime_tools):
    """Test that goto requires slide_number"""
    # This should be caught by the client validation
    # In the actual implementation, navigate_slide with slide_number=None
    # uses "next" or "previous" direction, not "goto"
    result = await navigate_slide(direction="next", deck_id="deck_123")
    # Should succeed as normal "next" command
    assert "slide" in result.lower()


@pytest.mark.asyncio
async def test_conversation_reset_clears_slide_state(conversation_manager):
    """Test that resetting conversation clears slide state"""
    # Set slide state
    conversation_manager.update_slide_state(
        current_slide=5,
        total_slides=10,
        deck_id="deck_123"
    )

    # Reset
    conversation_manager.reset()

    # Verify slide state is cleared
    assert conversation_manager.current_slide is None
    assert conversation_manager.total_slides is None
    assert conversation_manager.deck_id is None


@pytest.mark.asyncio
async def test_latency_target_compliance(initialized_realtime_tools):
    """Test that navigation completes within latency target (<500ms)"""
    import time

    start_time = time.time()
    await navigate_slide(direction="next", deck_id="deck_123")
    elapsed = time.time() - start_time

    # With mock, should be very fast (<50ms)
    # In production with real Supabase, target is <500ms total
    assert elapsed < 0.5, f"Navigation took {elapsed*1000:.0f}ms, target is <500ms"


@pytest.mark.asyncio
async def test_deck_id_special_characters(initialized_realtime_tools):
    """Test handling of deck IDs with special characters"""
    special_deck_ids = [
        "deck-with-dashes",
        "deck_with_underscores",
        "deck123",
        "DECK_ABC_123"
    ]

    for deck_id in special_deck_ids:
        await navigate_slide(direction="next", deck_id=deck_id)

        # Verify channel was created correctly
        channel_name = f"slide_control:{deck_id}"
        assert channel_name in initialized_realtime_tools.channels


@pytest.mark.asyncio
async def test_system_message_on_slide_update(conversation_manager):
    """Test that system messages are added when slide state updates"""
    initial_message_count = len(conversation_manager.messages)

    conversation_manager.update_slide_state(
        current_slide=3,
        total_slides=10,
        deck_id="deck_123"
    )

    # Should have added a system message
    assert len(conversation_manager.messages) == initial_message_count + 1

    # Verify the system message content
    last_message = conversation_manager.messages[-1]
    assert "slide" in last_message.content.lower()
    assert "3" in last_message.content
    assert "10" in last_message.content
