"""generate_video - Unified video generation with intelligent routing.

Routes to HeyGen for avatar videos, Veo for creative content.

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
from ..clients.veo import VeoClient
from ..router import detect_service, validate_service_hint

logger = logging.getLogger("videogen_mcp")


class GenerateVideoInput(BaseModel):
    """Input schema for generate_video."""

    prompt: str = Field(
        ...,
        description="Description of the video to generate. Be specific about visual style, content, and any spoken text.",
        min_length=1,
    )
    service_hint: str | None = Field(
        None,
        description="Optional override: 'heygen' for avatar videos, 'veo' for creative videos.",
    )
    aspect_ratio: str = Field(
        "16:9",
        description="Video aspect ratio: '16:9', '9:16', or '1:1'.",
    )
    duration: int = Field(
        8,
        description="Target duration in seconds.",
        ge=4,
        le=60,
    )


GenerateVideoSchema = GenerateVideoInput


async def generate_video(arguments: dict[str, Any]) -> list[TextContent]:
    """Generate a video with intelligent service routing.

    Args:
        arguments: Tool arguments from MCP call

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

        # Determine which service to use
        validated_hint = validate_service_hint(input_data.service_hint)
        if validated_hint:
            service = validated_hint
            routing_reason = f"User specified '{validated_hint}'"
        else:
            service = detect_service(input_data.prompt)
            routing_reason = f"Auto-detected from prompt analysis"

        logger.info(
            "generate_video called",
            extra={
                "tool": "generate_video",
                "service": service,
                "routing_reason": routing_reason,
            },
        )

        if service == "heygen":
            # For HeyGen, we need to pick a default avatar and voice
            # The generate_video tool uses auto-selection for simplicity
            heygen = HeyGenClient()

            # Get available avatars and voices
            avatars_response = await heygen.list_avatars()
            voices_response = await heygen.list_voices(filter_language="en")

            avatars = avatars_response.get("avatars", [])
            voices = voices_response.get("voices", [])

            if not avatars:
                return [
                    TextContent(
                        type="text",
                        text=json.dumps(
                            {
                                "error": True,
                                "code": "NO_AVATARS_AVAILABLE",
                                "message": "No avatars available. Use list_avatars to check your account.",
                            },
                            indent=2,
                        ),
                    )
                ]

            if not voices:
                return [
                    TextContent(
                        type="text",
                        text=json.dumps(
                            {
                                "error": True,
                                "code": "NO_VOICES_AVAILABLE",
                                "message": "No voices available. Use list_voices to check your account.",
                            },
                            indent=2,
                        ),
                    )
                ]

            # Use first available avatar and voice
            avatar_id = avatars[0]["avatar_id"]
            voice_id = voices[0]["voice_id"]

            result = await heygen.create_avatar_video(
                script=input_data.prompt,
                avatar_id=avatar_id,
                voice_id=voice_id,
                aspect_ratio=input_data.aspect_ratio,
            )

            result["routing_reason"] = routing_reason
            result["avatar_used"] = avatars[0].get("avatar_name", avatar_id)
            result["voice_used"] = voices[0].get("display_name", voice_id)

        else:
            # Use Veo for creative content
            veo = VeoClient()

            # Clamp duration to Veo's limits
            veo_duration = min(max(input_data.duration, 4), 8)

            result = await veo.generate_video(
                prompt=input_data.prompt,
                aspect_ratio=input_data.aspect_ratio,
                duration=veo_duration,
            )

            result["routing_reason"] = routing_reason

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

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

    except Exception as e:
        logger.error(f"generate_video error: {str(e)}")
        return [
            TextContent(
                type="text",
                text=json.dumps({"error": True, "message": str(e)}, indent=2),
            )
        ]
