# chuk-motion/src/chuk_motion/components/overlays/EndScreen/tool.py
"""EndScreen MCP tool."""

import asyncio

from chuk_motion.generator.composition_builder import ComponentInstance
from chuk_motion.models import ErrorResponse, OverlayComponentResponse


def register_tool(mcp, project_manager):
    """Register the EndScreen tool with the MCP server."""

    @mcp.tool
    async def remotion_add_end_screen(
        cta_text: str,
        thumbnail_url: str | None = None,
        variant: str | None = None,
        duration: float | str = 10.0,
        track: str = "overlay",
        gap_before: float | str | None = None,
    ) -> str:
        """
        Add EndScreen to the composition.

        YouTube end screen with CTAs and video suggestions

        Args:
            cta_text: Call-to-action text
            thumbnail_url: Optional thumbnail image URL
            variant: Style variant
            duration: Duration in seconds
            track: Track name (default: "overlay")
            gap_before: Gap before component in seconds (overrides track default)

        Returns:
            JSON with component info
        """

        def _add():
            if not project_manager.current_timeline:
                return ErrorResponse(
                    error="No active project. Create a project first."
                ).model_dump_json()

            try:
                component = ComponentInstance(
                    component_type="EndScreen",
                    start_frame=0,
                    duration_frames=0,
                    props={
                        "cta_text": cta_text,
                        "thumbnail_url": thumbnail_url,
                        "variant": variant,
                    },
                    layer=0,
                )

                component = project_manager.current_timeline.add_component(
                    component, duration=duration, track=track, gap_before=gap_before
                )

                return OverlayComponentResponse(
                    component="EndScreen",
                    start_time=project_manager.current_timeline.frames_to_seconds(
                        component.start_frame
                    ),
                    duration=duration,
                ).model_dump_json()
            except Exception as e:
                return ErrorResponse(error=str(e)).model_dump_json()

        return await asyncio.get_event_loop().run_in_executor(None, _add)
