"""
Slide Control Tool Functions

Provides AI-callable tool functions for slide navigation and control.
These tools are exposed to the LLM agent to enable voice-controlled
slide presentations.

Part of Issue #144 - Stream B: Tool Functions & Slide Control
Enhanced for Issue #148 - Stream A: 3-Participant Coordination with Realtime
"""

import logging
from typing import Literal

from ..supabase_client import SupabaseClient

logger = logging.getLogger(__name__)


# Global Supabase client instance (initialized by agent)
_supabase_client: SupabaseClient | None = None


def initialize_slide_control(supabase_client: SupabaseClient) -> None:
    """
    Initialize slide control tools with Supabase client.

    This must be called by the agent before using any slide control tools.

    Args:
        supabase_client: Initialized SupabaseClient instance
    """
    global _supabase_client
    _supabase_client = supabase_client
    logger.info("Slide control tools initialized")


def _get_client() -> SupabaseClient:
    """
    Get the global Supabase client instance.

    Returns:
        SupabaseClient instance

    Raises:
        RuntimeError: If slide control has not been initialized
    """
    if _supabase_client is None:
        raise RuntimeError(
            "Slide control not initialized. "
            "Call initialize_slide_control() first."
        )
    return _supabase_client


async def navigate_slide(
    direction: Literal["next", "prev", "previous"] = "next",
    slide_number: int | None = None,
    deck_id: str = "default"
) -> str:
    """
    Navigate through slides in a presentation.

    This function allows the voice agent to control slide navigation
    by sending commands to the slide deck via Supabase realtime channels.
    It uses the Issue #148 protocol for 3-participant coordination and
    waits for confirmation from the screenshare bot.

    Use cases:
    - "next slide" -> navigate_slide(direction="next")
    - "previous slide" -> navigate_slide(direction="previous")
    - "go to slide 5" -> navigate_slide(direction="goto", slide_number=5)

    Args:
        direction: Navigation direction ('next', 'prev', or 'previous')
        slide_number: Target slide number (for goto navigation)
        deck_id: Unique identifier for the slide deck (defaults to 'default')

    Returns:
        Human-readable confirmation message

    Raises:
        ValueError: If parameters are invalid
        RuntimeError: If slide control not initialized
    """
    logger.info(
        f"navigate_slide called: direction={direction}, "
        f"slide_number={slide_number}, deck_id={deck_id}"
    )

    try:
        client = _get_client()

        # Normalize direction
        if direction == "prev":
            direction = "previous"

        # Determine navigation type
        navigation_direction = "goto" if slide_number is not None else direction

        # Publish navigation command to realtime channel (Issue #148)
        try:
            confirmation = await client.publish_slide_navigation(
                deck_id=deck_id,
                direction=navigation_direction,
                slide_number=slide_number,
                timeout=5.0
            )

            # Update conversation state with slide info (handled by caller)
            # Store confirmation for conversation context
            if confirmation.get("success"):
                current = confirmation.get("current_slide")
                total = confirmation.get("total_slides")

                messages = {
                    "goto": f"Moved to slide {current} of {total}",
                    "next": f"Moved to next slide (slide {current} of {total})",
                    "previous": f"Moved to previous slide (slide {current} of {total})"
                }
                return messages.get(navigation_direction, f"Moved to slide {current} of {total}")
            else:
                error = confirmation.get("error", "Unknown error")
                return f"Sorry, couldn't navigate: {error}"

        except TimeoutError:
            logger.warning("Navigation confirmation timeout - command may still execute")
            # Still return success message as command was sent
            timeout_messages = {
                "goto": f"Navigating to slide {slide_number} (confirmation pending)",
                "next": "Moving to next slide (confirmation pending)",
                "previous": "Moving to previous slide (confirmation pending)"
            }
            return timeout_messages.get(navigation_direction, "Navigating slides (confirmation pending)")

    except ValueError as e:
        error_msg = f"Invalid navigation parameters: {e}"
        logger.error(error_msg)
        return f"Sorry, I couldn't navigate: {e}"

    except Exception as e:
        error_msg = f"Failed to navigate slide: {e}"
        logger.error(error_msg, exc_info=True)
        return "Sorry, I encountered an error while navigating the slides"


async def get_current_slide(deck_id: str = "default") -> str:
    """
    Get the current slide number for a presentation.

    This function queries the database to retrieve the current slide
    number for the specified deck.

    Use cases:
    - "what slide are we on?" -> get_current_slide()
    - "which slide is showing?" -> get_current_slide()

    Args:
        deck_id: Unique identifier for the slide deck (defaults to 'default')

    Returns:
        Human-readable message with current slide number

    Raises:
        RuntimeError: If slide control not initialized
    """
    logger.info(f"get_current_slide called: deck_id={deck_id}")

    try:
        client = _get_client()

        slide_number = await client.get_current_slide_number(deck_id)

        if slide_number is None:
            return f"I couldn't find information for slide deck '{deck_id}'"

        return f"We're currently on slide {slide_number}"

    except Exception as e:
        error_msg = f"Failed to get current slide: {e}"
        logger.error(error_msg, exc_info=True)
        return "Sorry, I couldn't retrieve the current slide information"


async def goto_slide(
    slide_number: int,
    deck_id: str = "default"
) -> str:
    """
    Jump to a specific slide number.

    This is a convenience wrapper around navigate_slide for explicit
    goto operations.

    Use cases:
    - "go to slide 5" -> goto_slide(slide_number=5)
    - "jump to slide 10" -> goto_slide(slide_number=10)
    - "show me slide 3" -> goto_slide(slide_number=3)

    Args:
        slide_number: Target slide number (must be positive integer)
        deck_id: Unique identifier for the slide deck (defaults to 'default')

    Returns:
        Human-readable confirmation message

    Raises:
        ValueError: If slide_number is invalid
        RuntimeError: If slide control not initialized
    """
    logger.info(f"goto_slide called: slide_number={slide_number}, deck_id={deck_id}")

    if not isinstance(slide_number, int) or slide_number < 1:
        return "Slide number must be a positive integer"

    return await navigate_slide(
        direction="next",  # direction is ignored when slide_number is provided
        slide_number=slide_number,
        deck_id=deck_id
    )


async def reload_slide(deck_id: str = "default") -> str:
    """
    Reload the current slide.

    This function sends a reload command to refresh the current slide,
    useful for presentations with dynamic content.

    Use cases:
    - "reload the slide" -> reload_slide()
    - "refresh this slide" -> reload_slide()

    Args:
        deck_id: Unique identifier for the slide deck (defaults to 'default')

    Returns:
        Human-readable confirmation message

    Raises:
        RuntimeError: If slide control not initialized
    """
    logger.info(f"reload_slide called: deck_id={deck_id}")

    try:
        client = _get_client()

        await client.publish_slide_command(
            deck_id=deck_id,
            command="reload"
        )

        return "Reloading the current slide"

    except Exception as e:
        error_msg = f"Failed to reload slide: {e}"
        logger.error(error_msg, exc_info=True)
        return "Sorry, I couldn't reload the slide"


# Export tool functions for agent registration
__all__ = [
    "initialize_slide_control",
    "navigate_slide",
    "get_current_slide",
    "goto_slide",
    "reload_slide",
]
