"""create_avatar_video - Create HeyGen avatar video with specific avatar/voice.

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

    script: str = Field(
        ...,
        description="The text the avatar will speak. Keep under 2500 characters for best results.",
        min_length=1,
        max_length=5000,
    )
    avatar_id: str = Field(
        ...,
        description="Avatar ID from list_avatars.",
        min_length=1,
    )
    voice_id: str = Field(
        ...,
        description="Voice ID from list_voices.",
        min_length=1,
    )
    background: dict[str, Any] | None = Field(
        None,
        description="Background configuration: {type: 'color'|'image'|'video'|'transparent', value?: string, url?: string}",
    )
    aspect_ratio: str = Field(
        "16:9",
        description="Video aspect ratio: '16:9', '9:16', or '1:1'.",
    )
    test_mode: bool = Field(
        False,
        description="If true, generates a watermarked preview without consuming credits.",
    )


CreateAvatarVideoSchema = CreateAvatarVideoInput


async def create_avatar_video(arguments: dict[str, Any]) -> list[TextContent]:
    """Create a HeyGen avatar video with specific avatar and voice.

    Args:
        arguments: Tool arguments from MCP call

    Returns:
        List of TextContent with job information
    """
    try:
        input_data = CreateAvatarVideoInput(**arguments)

        # Validate script length
        if len(input_data.script) > 2500:
            logger.warning(
                "Script length exceeds recommended 2500 characters",
                extra={"script_length": len(input_data.script)},
            )

        logger.info(
            "create_avatar_video called",
            extra={
                "tool": "create_avatar_video",
                "avatar_id": input_data.avatar_id,
                "voice_id": input_data.voice_id,
                "script_length": len(input_data.script),
            },
        )

        client = HeyGenClient()
        result = await client.create_avatar_video(
            script=input_data.script,
            avatar_id=input_data.avatar_id,
            voice_id=input_data.voice_id,
            background=input_data.background,
            aspect_ratio=input_data.aspect_ratio,
            test_mode=input_data.test_mode,
        )

        logger.info(
            "create_avatar_video completed",
            extra={
                "tool": "create_avatar_video",
                "job_id": result.get("job_id"),
            },
        )

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

    except Exception as e:
        error_msg = str(e)

        # Check for specific error types
        if "avatar" in error_msg.lower() and ("not found" in error_msg.lower() or "invalid" in error_msg.lower()):
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_AVATAR",
                            "message": f"Avatar ID not found or not accessible: {arguments.get('avatar_id')}",
                        },
                        indent=2,
                    ),
                )
            ]

        if "voice" in error_msg.lower() and ("not found" in error_msg.lower() or "invalid" in error_msg.lower()):
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_VOICE",
                            "message": f"Voice ID not found or not accessible: {arguments.get('voice_id')}",
                        },
                        indent=2,
                    ),
                )
            ]

        if "quota" in error_msg.lower() or "credit" in error_msg.lower() or "limit" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "QUOTA_EXCEEDED",
                            "message": "HeyGen API credits exhausted. Check your account balance.",
                        },
                        indent=2,
                    ),
                )
            ]

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