"""list_avatars - List available HeyGen avatars.

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 ListAvatarsInput(BaseModel):
    """Input schema for list_avatars."""

    filter_gender: str | None = Field(
        None,
        description="Filter by gender: 'male', 'female', or omit for all.",
    )
    include_instant: bool = Field(
        True,
        description="Include custom Instant Avatars.",
    )


ListAvatarsSchema = ListAvatarsInput


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

    Args:
        arguments: Tool arguments from MCP call

    Returns:
        List of TextContent with avatar information
    """
    try:
        input_data = ListAvatarsInput(**arguments)

        logger.info(
            "list_avatars called",
            extra={
                "tool": "list_avatars",
                "filter_gender": input_data.filter_gender,
            },
        )

        client = HeyGenClient()
        result = await client.list_avatars(
            filter_gender=input_data.filter_gender,
            include_instant=input_data.include_instant,
        )

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

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

        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "success": True,
                        "count": len(avatars),
                        "avatars": avatars,
                    },
                    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_avatars error: {error_msg}")
        return [
            TextContent(
                type="text",
                text=json.dumps({"error": True, "message": error_msg}, indent=2),
            )
        ]
