#!/usr/bin/env python3
"""
Unit tests for SlideNavigator

Tests all navigation commands (next, prev, goto, reload), command queueing,
error handling, and retry logic.
"""

import asyncio
import pytest
from unittest.mock import AsyncMock, Mock, patch, call
from slide_navigator import SlideNavigator


class TestSlideNavigatorBasics:
    """Test basic initialization and lifecycle"""

    @pytest.mark.asyncio
    async def test_initialization(self):
        """Test SlideNavigator initializes with correct defaults"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        assert navigator.page == mock_page
        assert navigator._command_queue is not None
        assert navigator._is_running is False
        assert navigator._command_timeout == 0.5
        assert navigator._max_retries == 1

    @pytest.mark.asyncio
    async def test_start_stop(self):
        """Test navigator can start and stop cleanly"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        # Start
        await navigator.start()
        assert navigator._is_running is True
        assert navigator._processing_task is not None

        # Stop
        await navigator.stop()
        assert navigator._is_running is False

    @pytest.mark.asyncio
    async def test_start_idempotent(self):
        """Test calling start() multiple times is safe"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()
        await navigator.start()  # Should not crash

        assert navigator._is_running is True
        await navigator.stop()

    @pytest.mark.asyncio
    async def test_stop_when_not_running(self):
        """Test calling stop() when not running is safe"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        # Stop without starting - should not crash
        await navigator.stop()
        assert navigator._is_running is False


class TestNavigationMethods:
    """Test individual navigation methods"""

    @pytest.mark.asyncio
    async def test_navigate_next(self):
        """Test navigate_next() presses ArrowRight"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.navigate_next()

        mock_page.keyboard.press.assert_called_once_with('ArrowRight')

    @pytest.mark.asyncio
    async def test_navigate_prev(self):
        """Test navigate_prev() presses ArrowLeft"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.navigate_prev()

        mock_page.keyboard.press.assert_called_once_with('ArrowLeft')

    @pytest.mark.asyncio
    async def test_navigate_goto_valid_slide(self):
        """Test navigate_goto() executes g + number + Enter sequence"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.navigate_goto(5)

        # Verify sequence: press g, type 5, press Enter
        assert mock_page.keyboard.press.call_count == 2
        assert mock_page.keyboard.press.call_args_list[0] == call('g')
        assert mock_page.keyboard.press.call_args_list[1] == call('Enter')
        mock_page.keyboard.type.assert_called_once_with('5')

    @pytest.mark.asyncio
    async def test_navigate_goto_invalid_slide_number(self):
        """Test navigate_goto() rejects invalid slide numbers"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        # Test negative number
        with pytest.raises(ValueError, match="slide_number must be >= 1"):
            await navigator.navigate_goto(-1)

        # Test zero
        with pytest.raises(ValueError, match="slide_number must be >= 1"):
            await navigator.navigate_goto(0)

    @pytest.mark.asyncio
    async def test_navigate_goto_large_slide_number(self):
        """Test navigate_goto() handles large slide numbers"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.navigate_goto(999)

        # Should still execute the sequence
        assert mock_page.keyboard.press.call_count == 2
        mock_page.keyboard.type.assert_called_once_with('999')

    @pytest.mark.asyncio
    async def test_navigate_reload(self):
        """Test navigate_reload() reloads page and waits for networkidle"""
        mock_page = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.navigate_reload()

        mock_page.reload.assert_called_once()
        mock_page.wait_for_load_state.assert_called_once_with('networkidle', timeout=5000)


class TestExecuteCommand:
    """Test execute_command() interface"""

    @pytest.mark.asyncio
    async def test_execute_command_next(self):
        """Test execute_command queues next command"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        # Execute command
        await navigator.execute_command("next")

        # Wait for command to be processed
        await asyncio.sleep(0.1)

        # Verify navigation method was called
        mock_page.keyboard.press.assert_called_with('ArrowRight')

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_execute_command_prev(self):
        """Test execute_command queues prev command"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        await navigator.execute_command("prev")
        await asyncio.sleep(0.1)

        mock_page.keyboard.press.assert_called_with('ArrowLeft')

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_execute_command_goto_with_slide_number(self):
        """Test execute_command queues goto command with slide number"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        await navigator.execute_command("goto", 7)
        await asyncio.sleep(0.1)

        # Verify goto sequence
        assert mock_page.keyboard.press.call_count == 2
        mock_page.keyboard.type.assert_called_once_with('7')

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_execute_command_goto_without_slide_number(self):
        """Test execute_command rejects goto without slide_number"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        with pytest.raises(ValueError, match="slide_number required"):
            await navigator.execute_command("goto", None)

    @pytest.mark.asyncio
    async def test_execute_command_goto_invalid_slide_number(self):
        """Test execute_command validates slide_number"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        with pytest.raises(ValueError, match="positive integer"):
            await navigator.execute_command("goto", 0)

        with pytest.raises(ValueError, match="positive integer"):
            await navigator.execute_command("goto", -5)

    @pytest.mark.asyncio
    async def test_execute_command_reload(self):
        """Test execute_command queues reload command"""
        mock_page = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        await navigator.execute_command("reload")
        await asyncio.sleep(0.1)

        mock_page.reload.assert_called_once()
        mock_page.wait_for_load_state.assert_called_once()

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_execute_command_unknown(self):
        """Test execute_command rejects unknown commands"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        with pytest.raises(ValueError, match="Unknown command"):
            await navigator.execute_command("invalid_command")

        with pytest.raises(ValueError, match="Unknown command"):
            await navigator.execute_command("forward")


class TestCommandQueueing:
    """Test command queue to prevent race conditions"""

    @pytest.mark.asyncio
    async def test_sequential_processing(self):
        """Test commands are processed sequentially"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        # Queue multiple commands rapidly
        await navigator.execute_command("next")
        await navigator.execute_command("next")
        await navigator.execute_command("prev")

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

        # All commands should have been processed
        assert mock_page.keyboard.press.call_count == 3

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_rapid_commands_no_race_condition(self):
        """Test rapid consecutive commands are queued correctly"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()

        # Add small delay to keyboard commands to simulate real behavior
        async def delayed_press(*args, **kwargs):
            await asyncio.sleep(0.01)

        mock_page.keyboard.press = AsyncMock(side_effect=delayed_press)

        navigator = SlideNavigator(mock_page)
        await navigator.start()

        # Send 10 rapid commands
        for _ in range(10):
            await navigator.execute_command("next")

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

        # All 10 commands should have been executed
        assert mock_page.keyboard.press.call_count == 10

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_mixed_commands_queued_correctly(self):
        """Test mix of different commands are queued and executed in order"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        # Queue different command types
        await navigator.execute_command("next")
        await navigator.execute_command("goto", 5)
        await navigator.execute_command("prev")

        # Wait for processing
        await asyncio.sleep(0.3)

        # Verify all were called
        # next: 1 ArrowRight
        # goto: 1 g, 1 Enter (type is separate)
        # prev: 1 ArrowLeft
        assert mock_page.keyboard.press.call_count >= 4  # At least 4 press calls

        await navigator.stop()


class TestErrorHandling:
    """Test error handling and retry logic"""

    @pytest.mark.asyncio
    async def test_navigation_failure_retries(self):
        """Test navigation failures trigger retry"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()

        # First call fails, second succeeds
        mock_page.keyboard.press = AsyncMock(
            side_effect=[Exception("Keyboard error"), None]
        )

        navigator = SlideNavigator(mock_page)
        await navigator.start()

        await navigator.execute_command("next")
        await asyncio.sleep(0.2)

        # Should have retried - 2 calls total
        assert mock_page.keyboard.press.call_count == 2

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_navigation_failure_after_max_retries(self):
        """Test navigation fails after max retries exceeded"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()

        # Always fail
        mock_page.keyboard.press = AsyncMock(
            side_effect=Exception("Persistent keyboard error")
        )

        navigator = SlideNavigator(mock_page)
        await navigator.start()

        await navigator.execute_command("next")
        await asyncio.sleep(0.3)

        # Should have tried initial + 1 retry = 2 times
        assert mock_page.keyboard.press.call_count == 2

        # Failed commands metric should be incremented
        metrics = navigator.metrics
        assert metrics["failed_commands"] == 2  # Each failed attempt counts

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_goto_failure_with_retry(self):
        """Test goto command failure and retry"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()

        # First press('g') fails, retry succeeds
        call_count = 0

        async def press_with_failure(*args, **kwargs):
            nonlocal call_count
            call_count += 1
            if call_count == 1:
                raise Exception("First attempt fails")

        mock_page.keyboard.press = AsyncMock(side_effect=press_with_failure)

        navigator = SlideNavigator(mock_page)
        await navigator.start()

        await navigator.execute_command("goto", 3)
        await asyncio.sleep(0.2)

        # Should have retried entire sequence
        assert mock_page.keyboard.press.call_count >= 2

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_reload_failure_with_retry(self):
        """Test reload command failure and retry"""
        mock_page = AsyncMock()

        # First reload fails, second succeeds
        mock_page.reload = AsyncMock(
            side_effect=[Exception("Reload failed"), None]
        )

        navigator = SlideNavigator(mock_page)
        await navigator.start()

        await navigator.execute_command("reload")
        await asyncio.sleep(0.2)

        # Should have retried
        assert mock_page.reload.call_count == 2

        await navigator.stop()


class TestMetrics:
    """Test performance metrics tracking"""

    @pytest.mark.asyncio
    async def test_metrics_initialization(self):
        """Test metrics start at zero"""
        mock_page = Mock()
        navigator = SlideNavigator(mock_page)

        metrics = navigator.metrics

        assert metrics["command_count"] == 0
        assert metrics["avg_command_time_ms"] == 0.0
        assert metrics["failed_commands"] == 0
        assert metrics["queue_size"] == 0

    @pytest.mark.asyncio
    async def test_metrics_after_successful_command(self):
        """Test metrics are updated after successful command"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        await navigator.execute_command("next")
        await asyncio.sleep(0.1)

        metrics = navigator.metrics

        assert metrics["command_count"] == 1
        assert metrics["avg_command_time_ms"] > 0
        assert metrics["failed_commands"] == 0

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_metrics_after_failed_command(self):
        """Test failed commands are tracked in metrics"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()

        # Always fail
        mock_page.keyboard.press = AsyncMock(
            side_effect=Exception("Always fail")
        )

        navigator = SlideNavigator(mock_page)

        await navigator.start()

        await navigator.execute_command("next")
        # Wait longer to ensure retries complete (initial + 0.1s delay + retry = ~0.25s minimum)
        await asyncio.sleep(0.5)

        metrics = navigator.metrics

        # Command attempted but failed (initial + retry = 2 failures)
        assert metrics["failed_commands"] == 2

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_metrics_multiple_commands(self):
        """Test metrics track multiple commands"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        # Execute several commands
        await navigator.execute_command("next")
        await navigator.execute_command("prev")
        await navigator.execute_command("goto", 5)

        await asyncio.sleep(0.3)

        metrics = navigator.metrics

        assert metrics["command_count"] == 3
        assert metrics["avg_command_time_ms"] > 0

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_queue_size_metric(self):
        """Test queue_size metric reflects pending commands"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()

        # Add delay to processing
        async def slow_press(*args, **kwargs):
            await asyncio.sleep(0.1)

        mock_page.keyboard.press = AsyncMock(side_effect=slow_press)

        navigator = SlideNavigator(mock_page)
        await navigator.start()

        # Queue multiple commands rapidly
        await navigator.execute_command("next")
        await navigator.execute_command("next")
        await navigator.execute_command("next")

        # Check queue size immediately (should have pending commands)
        metrics = navigator.metrics
        # Queue size may vary depending on processing speed
        assert metrics["queue_size"] >= 0

        # Wait for all to complete
        await asyncio.sleep(0.5)

        # Queue should be empty now
        metrics = navigator.metrics
        assert metrics["queue_size"] == 0

        await navigator.stop()


class TestIntegration:
    """Integration tests with realistic scenarios"""

    @pytest.mark.asyncio
    async def test_typical_navigation_sequence(self):
        """Test typical navigation sequence: next, next, prev, goto"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        # Typical sequence
        await navigator.execute_command("next")
        await asyncio.sleep(0.05)

        await navigator.execute_command("next")
        await asyncio.sleep(0.05)

        await navigator.execute_command("prev")
        await asyncio.sleep(0.05)

        await navigator.execute_command("goto", 10)
        await asyncio.sleep(0.1)

        # All commands should execute successfully
        assert mock_page.keyboard.press.call_count >= 5  # 3 arrow keys + 2 for goto (g + Enter)

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_stress_test_20_commands(self):
        """Test handling 20 rapid commands without issues"""
        mock_page = Mock()
        mock_page.keyboard = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        # Send 20 commands
        for i in range(20):
            if i % 2 == 0:
                await navigator.execute_command("next")
            else:
                await navigator.execute_command("prev")

        # Wait for all to complete
        await asyncio.sleep(1.0)

        metrics = navigator.metrics
        assert metrics["command_count"] == 20
        assert metrics["queue_size"] == 0  # All processed

        await navigator.stop()

    @pytest.mark.asyncio
    async def test_navigation_with_reload(self):
        """Test navigation commands work after reload"""
        mock_page = AsyncMock()
        navigator = SlideNavigator(mock_page)

        await navigator.start()

        # Navigate
        await navigator.execute_command("next")
        await asyncio.sleep(0.05)

        # Reload
        await navigator.execute_command("reload")
        await asyncio.sleep(0.1)

        # Navigate again
        await navigator.execute_command("next")
        await asyncio.sleep(0.05)

        # All commands should succeed
        mock_page.reload.assert_called_once()
        assert mock_page.keyboard.press.call_count == 2  # Two next commands

        await navigator.stop()


if __name__ == "__main__":
    pytest.main([__file__, "-v"])
