"""
API-based tool functions for the voice agent.

These tools allow the agent to interact with the slide system API
to generate presentations and control slides via HTTP requests.
"""

import logging
import os
from typing import Any

import httpx

from ..conversation import ConversationManager

logger = logging.getLogger(__name__)


# Get API base URL from environment
API_BASE_URL = os.getenv("SLIDE_API_BASE_URL", "https://slide-system-production-5813.up.railway.app")


async def generate_deck_tool(
    conversation: ConversationManager,
    topic: str,
    **kwargs: Any,
) -> str:
    """
    Generate a new slide deck on the given topic.

    Args:
        conversation: The conversation manager (provides context)
        topic: The topic for the presentation
        **kwargs: Additional parameters (slides_count, style, etc.)

    Returns:
        A message describing the result
    """
    logger.info(f"[Tool] generate_deck_tool called with topic: {topic}")

    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            # Call the slidev generate API
            response = await client.post(
                f"{API_BASE_URL}/api/slidev/generate",
                json={
                    "topic": topic,
                    "slides_count": kwargs.get("slides_count", 5),
                    "style": kwargs.get("style", "professional"),
                }
            )

            if response.status_code == 200:
                data = response.json()
                deck_url = data.get("deck_url", "")
                logger.info(f"[Tool] Deck generated successfully: {deck_url}")
                return f"I've created a presentation about {topic}. The deck is ready and will appear on screen shortly."
            else:
                logger.error(f"[Tool] API error: {response.status_code} - {response.text}")
                return "I encountered an error generating the presentation. Please try again."

    except Exception as e:
        logger.error(f"[Tool] Error calling generate API: {e}", exc_info=True)
        return "I'm having trouble generating the presentation right now. Please try again in a moment."


async def next_slide_tool(
    conversation: ConversationManager,
    **kwargs: Any,
) -> str:
    """
    Navigate to the next slide in the current presentation.

    Args:
        conversation: The conversation manager
        **kwargs: Additional parameters

    Returns:
        A message confirming the action
    """
    logger.info("[Tool] next_slide_tool called")

    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.post(
                f"{API_BASE_URL}/api/slidev/control",
                json={"action": "next"}
            )

            if response.status_code == 200:
                return "Moving to the next slide."
            else:
                return "I couldn't navigate to the next slide."

    except Exception as e:
        logger.error(f"[Tool] Error calling control API: {e}", exc_info=True)
        return "I'm having trouble controlling the slides right now."


async def previous_slide_tool(
    conversation: ConversationManager,
    **kwargs: Any,
) -> str:
    """
    Navigate to the previous slide in the current presentation.

    Args:
        conversation: The conversation manager
        **kwargs: Additional parameters

    Returns:
        A message confirming the action
    """
    logger.info("[Tool] previous_slide_tool called")

    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.post(
                f"{API_BASE_URL}/api/slidev/control",
                json={"action": "previous"}
            )

            if response.status_code == 200:
                return "Going back to the previous slide."
            else:
                return "I couldn't navigate to the previous slide."

    except Exception as e:
        logger.error(f"[Tool] Error calling control API: {e}", exc_info=True)
        return "I'm having trouble controlling the slides right now."


async def go_to_slide_tool(
    conversation: ConversationManager,
    slide_number: int,
    **kwargs: Any,
) -> str:
    """
    Navigate to a specific slide number.

    Args:
        conversation: The conversation manager
        slide_number: The slide number to navigate to (1-indexed)
        **kwargs: Additional parameters

    Returns:
        A message confirming the action
    """
    logger.info(f"[Tool] go_to_slide_tool called with slide_number: {slide_number}")

    try:
        async with httpx.AsyncClient(timeout=10.0) as client:
            response = await client.post(
                f"{API_BASE_URL}/api/slidev/control",
                json={"action": "goto", "slide": slide_number}
            )

            if response.status_code == 200:
                return f"Jumping to slide {slide_number}."
            else:
                return f"I couldn't navigate to slide {slide_number}."

    except Exception as e:
        logger.error(f"[Tool] Error calling control API: {e}", exc_info=True)
        return "I'm having trouble controlling the slides right now."


# Export all tools
__all__ = [
    "generate_deck_tool",
    "next_slide_tool",
    "previous_slide_tool",
    "go_to_slide_tool",
]
