"""get_template_details - Get HeyGen template details with variables.

Generated by GRIMLOCK MCP Factory
"""

import json
import logging
from typing import Any

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

from ..clients.heygen import HeyGenClient

logger = logging.getLogger("videogen_mcp")


class GetTemplateDetailsInput(BaseModel):
    """Input schema for get_template_details."""

    template_id: str = Field(
        ...,
        description="Template ID from list_templates.",
        min_length=1,
    )


GetTemplateDetailsSchema = GetTemplateDetailsInput


async def get_template_details(arguments: dict[str, Any]) -> list[TextContent]:
    """Get detailed information about a HeyGen template.

    Args:
        arguments: Tool arguments from MCP call

    Returns:
        List of TextContent with template details
    """
    try:
        input_data = GetTemplateDetailsInput(**arguments)

        logger.info(
            "get_template_details called",
            extra={
                "tool": "get_template_details",
                "template_id": input_data.template_id,
            },
        )

        client = HeyGenClient()
        result = await client.get_template_details(input_data.template_id)

        logger.info(
            "get_template_details completed",
            extra={
                "tool": "get_template_details",
                "template_id": input_data.template_id,
                "variable_count": len(result.get("variables", [])),
            },
        )

        return [
            TextContent(
                type="text",
                text=json.dumps({"success": True, **result}, indent=2),
            )
        ]

    except Exception as e:
        error_msg = str(e)

        if "404" in error_msg or "not found" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "TEMPLATE_NOT_FOUND",
                            "message": f"Template ID not found: {arguments.get('template_id')}",
                        },
                        indent=2,
                    ),
                )
            ]

        if "401" in error_msg or "403" in error_msg:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "AUTH_FAILED",
                            "message": "HeyGen API key is invalid or expired.",
                        },
                        indent=2,
                    ),
                )
            ]

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