#!/usr/bin/env python3
"""
Slide Navigation Module for Slidev Deck Control

Provides keyboard-based navigation commands for controlling Slidev presentations
via Playwright. Handles next/prev/goto/reload commands with command queueing
to prevent race conditions.
"""

import asyncio
import logging
import time
from typing import Optional, Dict, Any, Tuple
from playwright.async_api import Page

logger = logging.getLogger(__name__)


class SlideNavigator:
    """
    Keyboard navigation controller for Slidev decks.

    Executes navigation commands (next, prev, goto, reload) via Playwright
    keyboard events. Commands are queued and processed sequentially to prevent
    race conditions.

    Updated for Issue #148: Returns confirmation data with current/total slides.

    Interface for Stream A (SlideControlListener):
        - execute_command(command: Dict[str, Any]) -> Dict[str, Any]

    Example:
        >>> navigator = SlideNavigator(playwright_page)
        >>> cmd = {"type": "navigate", "direction": "next", "session_id": "sess_123"}
        >>> result = await navigator.execute_command(cmd)
        >>> print(result)  # {"type": "confirmation", "success": True, "current_slide": 2, ...}
    """

    def __init__(self, page: Page) -> None:
        """
        Initialize slide navigator.

        Args:
            page: Playwright Page object (from ScreenshotCapture._page)
        """
        self.page: Page = page

        # Command queue to prevent race conditions
        self._command_queue: asyncio.Queue[Tuple[Dict[str, Any], asyncio.Future]] = asyncio.Queue()
        self._processing_task: Optional[asyncio.Task[None]] = None
        self._is_running: bool = False

        # Configuration
        self._command_timeout: float = 0.5  # 500ms target per command
        self._max_retries: int = 1  # Retry once on failure

        # Slide tracking
        self._current_slide: int = 1  # Current slide number (1-indexed)
        self._total_slides: int = 0   # Total slides (detected from Slidev)

        # Metrics
        self._command_count: int = 0
        self._total_command_time: float = 0.0
        self._failed_commands: int = 0

    async def start(self) -> None:
        """
        Start the command processor and detect slide count.

        Begins processing commands from the queue. Must be called before
        execute_command() will work.
        """
        if self._is_running:
            logger.warning("Command processor already running")
            return

        self._is_running = True

        # Try to detect total slide count from Slidev
        try:
            await self._detect_slide_count()
            logger.info(f"Detected {self._total_slides} total slides")
        except Exception as e:
            logger.warning(f"Failed to detect slide count: {e}. Will use fallback value.")
            self._total_slides = 0

        self._processing_task = asyncio.create_task(self._process_command_queue())
        logger.info("Slide navigator command processor started")

    async def stop(self) -> None:
        """
        Stop the command processor and clean up.

        Waits for current command to complete, then stops processing.
        """
        if not self._is_running:
            return

        self._is_running = False

        # Wait for processing task to finish
        if self._processing_task:
            try:
                await asyncio.wait_for(self._processing_task, timeout=2.0)
            except asyncio.TimeoutError:
                logger.warning("Command processor did not stop gracefully")
                self._processing_task.cancel()

        logger.info("Slide navigator command processor stopped")

        # Log final metrics
        if self._command_count > 0:
            avg_time = self._total_command_time / self._command_count
            logger.info(
                f"Final navigation metrics: "
                f"total={self._command_count}, "
                f"avg_time={avg_time*1000:.1f}ms, "
                f"failed={self._failed_commands}"
            )

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

        Commands are queued and processed sequentially to prevent race conditions.
        This is the main interface called by SlideControlListener (Issue #148).

        Args:
            command: Command dict with keys:
                    - type: "navigate"
                    - direction: "next" | "previous" | "goto"
                    - slide_number: int (optional, for goto)
                    - timestamp: str (ISO 8601)
                    - session_id: str

        Returns:
            Confirmation dict with keys:
            - type: "confirmation"
            - success: bool
            - current_slide: int
            - total_slides: int
            - error: str (optional, if success=False)
            - timestamp: str (ISO 8601)
            - session_id: str

        Raises:
            ValueError: If command format is invalid
        """
        from datetime import datetime

        # Extract fields
        direction = command.get('direction')
        slide_number = command.get('slide_number')
        session_id = command.get('session_id', 'unknown')

        # Validate direction
        valid_directions = ["next", "previous", "goto"]
        if direction not in valid_directions:
            return {
                "type": "confirmation",
                "success": False,
                "current_slide": self._current_slide,
                "total_slides": self._total_slides,
                "error": f"Invalid direction: {direction}",
                "timestamp": datetime.utcnow().isoformat() + 'Z',
                "session_id": session_id
            }

        # Validate slide_number for goto command
        if direction == "goto":
            if slide_number is None:
                return {
                    "type": "confirmation",
                    "success": False,
                    "current_slide": self._current_slide,
                    "total_slides": self._total_slides,
                    "error": "slide_number required for 'goto' direction",
                    "timestamp": datetime.utcnow().isoformat() + 'Z',
                    "session_id": session_id
                }
            if not isinstance(slide_number, int) or slide_number < 1:
                return {
                    "type": "confirmation",
                    "success": False,
                    "current_slide": self._current_slide,
                    "total_slides": self._total_slides,
                    "error": f"slide_number must be positive integer, got: {slide_number}",
                    "timestamp": datetime.utcnow().isoformat() + 'Z',
                    "session_id": session_id
                }

        # Create a future for the result
        result_future: asyncio.Future[Dict[str, Any]] = asyncio.Future()

        # Queue the command with its future
        await self._command_queue.put((command, result_future))
        logger.debug(f"Queued command: direction={direction}, slide_number={slide_number}")

        # Wait for result
        return await result_future

    async def _process_command_queue(self) -> None:
        """
        Background task that processes commands from the queue sequentially.
        """
        logger.info("Command queue processor started")

        while self._is_running:
            try:
                # Get next command from queue (with timeout to allow checking _is_running)
                try:
                    command, result_future = await asyncio.wait_for(
                        self._command_queue.get(),
                        timeout=0.5
                    )
                except asyncio.TimeoutError:
                    # No command available, continue loop
                    continue

                # Process the command and get result
                result = await self._execute_command_internal(command)

                # Set the result on the future
                if not result_future.done():
                    result_future.set_result(result)

                # Mark task done
                self._command_queue.task_done()

            except Exception as e:
                logger.error(f"Error in command queue processor: {e}", exc_info=True)
                # Continue processing despite errors

        logger.info("Command queue processor stopped")

    async def _execute_command_internal(self, command: Dict[str, Any]) -> Dict[str, Any]:
        """
        Internal command execution with retry logic and metrics.

        Args:
            command: Command dict with direction, slide_number, session_id

        Returns:
            Confirmation dict
        """
        from datetime import datetime

        start_time = time.time()
        direction = command.get('direction')
        slide_number = command.get('slide_number')
        session_id = command.get('session_id', 'unknown')

        logger.info(f"Executing navigation command: direction={direction}, slide_number={slide_number}")

        last_error = None

        for attempt in range(1, self._max_retries + 2):  # +2 because range is exclusive and we want initial + 1 retry
            try:
                # Execute the appropriate navigation method
                if direction == "next":
                    await self.navigate_next()
                    self._current_slide = min(self._current_slide + 1, self._total_slides or 999)
                elif direction == "previous":
                    await self.navigate_prev()
                    self._current_slide = max(self._current_slide - 1, 1)
                elif direction == "goto":
                    assert slide_number is not None, "slide_number validated earlier"
                    await self.navigate_goto(slide_number)
                    self._current_slide = slide_number

                # Success - record metrics
                command_time = time.time() - start_time
                self._command_count += 1
                self._total_command_time += command_time

                logger.info(
                    f"Navigation command completed: {direction} "
                    f"(time={command_time*1000:.1f}ms, attempt={attempt}, current_slide={self._current_slide})"
                )

                # Warn if command took longer than target
                if command_time > self._command_timeout:
                    logger.warning(
                        f"Command latency ({command_time*1000:.1f}ms) "
                        f"exceeds target ({self._command_timeout*1000:.0f}ms)"
                    )

                # Return success confirmation
                return {
                    "type": "confirmation",
                    "success": True,
                    "current_slide": self._current_slide,
                    "total_slides": self._total_slides,
                    "timestamp": datetime.utcnow().isoformat() + 'Z',
                    "session_id": session_id
                }

            except Exception as e:
                last_error = e
                self._failed_commands += 1

                if attempt <= self._max_retries:
                    logger.warning(
                        f"Navigation command failed (attempt {attempt}/{self._max_retries + 1}): {e}"
                    )
                    await asyncio.sleep(0.1)  # Brief delay before retry
                else:
                    logger.error(
                        f"Navigation command failed after {self._max_retries + 1} attempts: {e}",
                        exc_info=True
                    )

        # All attempts failed - return error confirmation
        return {
            "type": "confirmation",
            "success": False,
            "current_slide": self._current_slide,
            "total_slides": self._total_slides,
            "error": f"Navigation failed: {str(last_error)}",
            "timestamp": datetime.utcnow().isoformat() + 'Z',
            "session_id": session_id
        }

    async def _detect_slide_count(self) -> None:
        """
        Detect total slide count from Slidev deck.

        Slidev typically exposes slide info in the DOM or via JavaScript.
        We'll try to extract it from the page.
        """
        try:
            # Try to get slide count from Slidev's internal state
            # Slidev stores slide info in __slidev__ global variable
            slide_count = await self.page.evaluate(
                "() => window.__slidev__?.nav?.total || 0"
            )

            if slide_count and isinstance(slide_count, (int, float)) and slide_count > 0:
                self._total_slides = int(slide_count)
                logger.info(f"Detected {self._total_slides} slides from Slidev")
            else:
                # Fallback: count elements with specific class
                slide_count = await self.page.evaluate(
                    "() => document.querySelectorAll('.slidev-page, [data-slidev-no]').length"
                )
                if slide_count:
                    self._total_slides = int(slide_count)
                    logger.info(f"Detected {self._total_slides} slides via DOM query")
                else:
                    logger.warning("Could not detect slide count, using fallback value")
                    self._total_slides = 0

        except Exception as e:
            logger.warning(f"Failed to detect slide count: {e}")
            self._total_slides = 0

    async def navigate_next(self) -> None:
        """
        Navigate to next slide.

        Presses ArrowRight key in Playwright page.

        Raises:
            Exception: If keyboard command fails
        """
        logger.debug("Pressing ArrowRight key")
        await self.page.keyboard.press('ArrowRight')

    async def navigate_prev(self) -> None:
        """
        Navigate to previous slide.

        Presses ArrowLeft key in Playwright page.

        Raises:
            Exception: If keyboard command fails
        """
        logger.debug("Pressing ArrowLeft key")
        await self.page.keyboard.press('ArrowLeft')

    async def navigate_goto(self, slide_number: Optional[int]) -> None:
        """
        Navigate to specific slide number.

        Slidev goto sequence: Press 'g', type slide number, press Enter.

        Args:
            slide_number: Target slide number (1-indexed)

        Raises:
            ValueError: If slide_number is invalid
            Exception: If keyboard commands fail
        """
        if slide_number is None or slide_number < 1:
            raise ValueError(f"slide_number must be >= 1, got {slide_number}")

        logger.debug(f"Executing goto sequence for slide {slide_number}")

        # Press 'g' to open goto dialog
        await self.page.keyboard.press('g')

        # Type the slide number
        await self.page.keyboard.type(str(slide_number))

        # Press Enter to navigate
        await self.page.keyboard.press('Enter')

    async def navigate_reload(self) -> None:
        """
        Reload the current page.

        Reloads the Playwright page and waits for networkidle state.

        Raises:
            Exception: If page reload fails
        """
        logger.debug("Reloading page")

        # Reload the page
        await self.page.reload()

        # Wait for page to be fully loaded
        await self.page.wait_for_load_state('networkidle', timeout=5000)  # 5s timeout

    @property
    def metrics(self) -> Dict[str, Any]:
        """
        Get navigation performance metrics.

        Returns:
            dict with keys: command_count, avg_command_time_ms, failed_commands
        """
        avg_time = (
            self._total_command_time / self._command_count
            if self._command_count > 0
            else 0.0
        )

        return {
            "command_count": self._command_count,
            "avg_command_time_ms": round(avg_time * 1000, 2),
            "failed_commands": self._failed_commands,
            "queue_size": self._command_queue.qsize()
        }
