"""
Slide Generation Tool Functions

Provides AI-callable tool functions for generating new slides during
presentations. These tools enable the voice agent to create slides
on-the-fly based on user requests.

Part of Issue #144 - Stream B: Tool Functions & Slide Control
"""

import logging

from ..supabase_client import SupabaseClient

logger = logging.getLogger(__name__)


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


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

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

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


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

    Returns:
        SupabaseClient instance

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


async def generate_slide(
    topic: str,
    content: str | None = None,
    deck_id: str = "default"
) -> str:
    """
    Generate a new slide with the specified topic and content.

    This function creates a new slide generation request that will be
    processed asynchronously. The slide will be added to the presentation
    once generation is complete.

    Use cases:
    - "create a slide about AI" -> generate_slide(topic="AI")
    - "make a slide showing our Q4 results" -> generate_slide(topic="Q4 Results")
    - "add a slide with 3 bullet points about benefits" ->
      generate_slide(topic="Benefits", content="1. Cost savings\n2. Faster delivery\n3. Better quality")

    Args:
        topic: The main topic or title for the slide
        content: Optional content/body text for the slide
        deck_id: Unique identifier for the slide deck (defaults to 'default')

    Returns:
        Human-readable confirmation message

    Raises:
        RuntimeError: If slide generation not initialized
    """
    logger.info(
        f"generate_slide called: topic='{topic}', "
        f"content_length={len(content) if content else 0}, deck_id={deck_id}"
    )

    try:
        client = _get_client()

        # Create slide generation request in database
        # This will trigger a background job to generate the slide
        generation_data = {
            "deck_id": deck_id,
            "topic": topic,
            "content": content,
            "status": "pending",
        }

        result = client.client.table("slide_generation_requests").insert(
            generation_data
        ).execute()

        if not result.data:
            raise Exception("Failed to create slide generation request")

        request_id = result.data[0].get("id")

        logger.info(
            f"Slide generation request created: {request_id} "
            f"(topic: {topic})"
        )

        if content:
            return (
                f"I'm creating a new slide about '{topic}' with the content you specified. "
                f"It should appear shortly."
            )
        else:
            return (
                f"I'm creating a new slide about '{topic}'. "
                f"It should appear shortly."
            )

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


async def add_bullet_point(
    text: str,
    slide_number: int | None = None,
    deck_id: str = "default"
) -> str:
    """
    Add a bullet point to an existing slide.

    This function adds a new bullet point to either the current slide
    or a specified slide number.

    Use cases:
    - "add a bullet point saying cost savings" -> add_bullet_point(text="Cost savings")
    - "add 'improved efficiency' to slide 3" -> add_bullet_point(text="Improved efficiency", slide_number=3)

    Args:
        text: The bullet point text to add
        slide_number: Target slide number (None for current slide)
        deck_id: Unique identifier for the slide deck (defaults to 'default')

    Returns:
        Human-readable confirmation message

    Raises:
        RuntimeError: If slide generation not initialized
    """
    logger.info(
        f"add_bullet_point called: text='{text}', "
        f"slide_number={slide_number}, deck_id={deck_id}"
    )

    try:
        client = _get_client()

        # Determine target slide
        if slide_number is None:
            target = await client.get_current_slide_number(deck_id)
            if target is None:
                return "I couldn't determine the current slide number"
            target_desc = "the current slide"
        else:
            target = slide_number
            target_desc = f"slide {slide_number}"

        # Create bullet point addition request
        modification_data = {
            "deck_id": deck_id,
            "slide_number": target,
            "action": "add_bullet",
            "content": text,
            "status": "pending",
        }

        result = client.client.table("slide_modifications").insert(
            modification_data
        ).execute()

        if not result.data:
            raise Exception("Failed to create bullet point request")

        logger.info(
            f"Bullet point addition requested for slide {target}: '{text}'"
        )

        return f"I'm adding '{text}' to {target_desc}"

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


async def update_slide_content(
    content: str,
    slide_number: int | None = None,
    deck_id: str = "default"
) -> str:
    """
    Update the content of an existing slide.

    This function replaces the content of either the current slide
    or a specified slide number.

    Use cases:
    - "change the slide content to..." -> update_slide_content(content="...")
    - "update slide 5 with..." -> update_slide_content(content="...", slide_number=5)

    Args:
        content: New content for the slide
        slide_number: Target slide number (None for current slide)
        deck_id: Unique identifier for the slide deck (defaults to 'default')

    Returns:
        Human-readable confirmation message

    Raises:
        RuntimeError: If slide generation not initialized
    """
    logger.info(
        f"update_slide_content called: content_length={len(content)}, "
        f"slide_number={slide_number}, deck_id={deck_id}"
    )

    try:
        client = _get_client()

        # Determine target slide
        if slide_number is None:
            target = await client.get_current_slide_number(deck_id)
            if target is None:
                return "I couldn't determine the current slide number"
            target_desc = "the current slide"
        else:
            target = slide_number
            target_desc = f"slide {slide_number}"

        # Create content update request
        modification_data = {
            "deck_id": deck_id,
            "slide_number": target,
            "action": "update_content",
            "content": content,
            "status": "pending",
        }

        result = client.client.table("slide_modifications").insert(
            modification_data
        ).execute()

        if not result.data:
            raise Exception("Failed to create content update request")

        logger.info(f"Content update requested for slide {target}")

        return f"I'm updating the content of {target_desc}"

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


# Export tool functions for agent registration
__all__ = [
    "initialize_slide_generation",
    "generate_slide",
    "add_bullet_point",
    "update_slide_content",
]
