"""generate_from_template - Generate HeyGen video from template.

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

    template_id: str = Field(
        ...,
        description="Template ID from list_templates.",
        min_length=1,
    )
    variables: dict[str, Any] = Field(
        ...,
        description="Object mapping variable names to values with type and properties.",
    )
    title: str | None = Field(
        None,
        description="Optional title for the generated video.",
    )
    test_mode: bool = Field(
        False,
        description="If true, generates a watermarked preview.",
    )


GenerateFromTemplateSchema = GenerateFromTemplateInput


async def generate_from_template(arguments: dict[str, Any]) -> list[TextContent]:
    """Generate a HeyGen video using a template with custom variables.

    Args:
        arguments: Tool arguments from MCP call

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

        logger.info(
            "generate_from_template called",
            extra={
                "tool": "generate_from_template",
                "template_id": input_data.template_id,
                "variable_count": len(input_data.variables),
            },
        )

        client = HeyGenClient()
        result = await client.generate_from_template(
            template_id=input_data.template_id,
            variables=input_data.variables,
            title=input_data.title,
            test_mode=input_data.test_mode,
        )

        logger.info(
            "generate_from_template completed",
            extra={
                "tool": "generate_from_template",
                "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)

        if "404" in error_msg or "template" in error_msg.lower() and "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 "variable" in error_msg.lower() and "required" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "MISSING_REQUIRED_VARIABLE",
                            "message": "A required template variable was not provided. Use get_template_details to see required variables.",
                        },
                        indent=2,
                    ),
                )
            ]

        if "variable" in error_msg.lower() and ("invalid" in error_msg.lower() or "type" in error_msg.lower()):
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_VARIABLE_VALUE",
                            "message": "Variable value doesn't match expected type or constraints.",
                        },
                        indent=2,
                    ),
                )
            ]

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