"""list_templates - List available HeyGen templates.

Generated by GRIMLOCK MCP Factory
"""

import json
import logging
from typing import Any

from mcp.types import TextContent
from pydantic import BaseModel

from ..clients.heygen import HeyGenClient

logger = logging.getLogger("videogen_mcp")


class ListTemplatesInput(BaseModel):
    """Input schema for list_templates (no parameters)."""

    pass


ListTemplatesSchema = ListTemplatesInput


async def list_templates(arguments: dict[str, Any]) -> list[TextContent]:
    """List available HeyGen templates.

    Args:
        arguments: Tool arguments from MCP call (none required)

    Returns:
        List of TextContent with template information
    """
    try:
        logger.info("list_templates called", extra={"tool": "list_templates"})

        client = HeyGenClient()
        result = await client.list_templates()

        templates = result.get("templates", [])

        logger.info(
            "list_templates completed",
            extra={
                "tool": "list_templates",
                "count": len(templates),
            },
        )

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

    except Exception as e:
        error_msg = str(e)
        if "401" in error_msg or "403" in error_msg or "unauthorized" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "AUTH_FAILED",
                            "message": "HeyGen API key is invalid or expired. Check your HEYGEN_API_KEY.",
                        },
                        indent=2,
                    ),
                )
            ]

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