"""list_voices - List available HeyGen voices.

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

    filter_language: str | None = Field(
        None,
        description="Filter by language code (e.g., 'en', 'es', 'fr').",
    )
    filter_gender: str | None = Field(
        None,
        description="Filter by voice gender: 'male', 'female', or omit for all.",
    )


ListVoicesSchema = ListVoicesInput


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

    Args:
        arguments: Tool arguments from MCP call

    Returns:
        List of TextContent with voice information
    """
    try:
        input_data = ListVoicesInput(**arguments)

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

        client = HeyGenClient()
        result = await client.list_voices(
            filter_language=input_data.filter_language,
            filter_gender=input_data.filter_gender,
        )

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

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

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