"""get_video - Retrieve a specific video by ID.

Generated by GRIMLOCK MCP Factory
"""

import json
import logging
from typing import Any

import httpx
from mcp.types import TextContent
from pydantic import BaseModel, Field

from ..clients.loom import LoomClient

logger = logging.getLogger("loom_mcp")


class GetVideoInput(BaseModel):
    """Input schema for get_video.

    Retrieve a specific video by its unique identifier.
    """

    video_id: str = Field(
        ...,
        min_length=1,
        description="Unique identifier for the video",
    )


GetVideoSchema = GetVideoInput


async def get_video(arguments: dict[str, Any]) -> list[TextContent]:
    """Retrieve a specific video by ID.

    Args:
        arguments: Tool arguments from MCP call containing video_id

    Returns:
        List of TextContent with video details
    """
    try:
        # Validate input
        validated = GetVideoInput(**arguments)

        logger.info(
            "get_video called",
            extra={
                "tool": "get_video",
                "video_id": validated.video_id,
            },
        )

        client = LoomClient()
        video = await client.get_video(validated.video_id)

        response = {
            "success": True,
            "video": video,
        }

        logger.info(
            "get_video completed",
            extra={
                "tool": "get_video",
                "video_id": validated.video_id,
            },
        )

        return [
            TextContent(
                type="text",
                text=json.dumps(response, indent=2),
            )
        ]

    except httpx.HTTPStatusError as e:
        error_code = e.response.status_code
        error_msg = str(e)

        if error_code == 401:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "AUTH_FAILED",
                            "message": "Loom access token is invalid or expired. Check your LOOM_ACCESS_TOKEN.",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 403:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "FORBIDDEN",
                            "message": "Access denied. You may not have permission to view this video.",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 404:
            video_id = arguments.get("video_id", "unknown")
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "NOT_FOUND",
                            "message": f"Video not found: {video_id}",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 429:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "RATE_LIMITED",
                            "message": "Rate limit exceeded. Please wait before retrying.",
                        },
                        indent=2,
                    ),
                )
            ]

        logger.error(f"get_video HTTP error: {error_msg}")
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "error": True,
                        "code": f"HTTP_{error_code}",
                        "message": error_msg,
                    },
                    indent=2,
                ),
            )
        ]

    except (httpx.ConnectError, httpx.TimeoutException) as e:
        error_msg = str(e)
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "error": True,
                        "code": "CONNECTION_FAILED",
                        "message": f"Failed to connect to Loom API. Error: {error_msg}",
                    },
                    indent=2,
                ),
            )
        ]

    except Exception as e:
        error_msg = str(e)
        logger.error(f"get_video error: {error_msg}")
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "error": True,
                        "message": error_msg,
                    },
                    indent=2,
                ),
            )
        ]
