"""generate_creative_video - Generate cinematic video using Google Veo.

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.veo import VeoClient

logger = logging.getLogger("videogen_mcp")


class GenerateCreativeVideoInput(BaseModel):
    """Input schema for generate_creative_video."""

    prompt: str = Field(
        ...,
        description="Detailed description of the video. Include subject, action, setting, camera movement, lighting, and style.",
        min_length=1,
    )
    negative_prompt: str | None = Field(
        None,
        description="Elements to avoid in generation (e.g., 'blurry, low quality, text overlays').",
    )
    aspect_ratio: str = Field(
        "16:9",
        description="Video aspect ratio: '16:9', '9:16', '1:1'.",
    )
    duration: int = Field(
        8,
        description="Video duration in seconds: 4, 6, or 8.",
        ge=4,
        le=8,
    )
    model: str = Field(
        "veo-3.1-generate-preview",
        description="Veo model version.",
    )
    seed: int | None = Field(
        None,
        description="Seed for reproducible generation (0-4294967295).",
        ge=0,
        le=4294967295,
    )
    sample_count: int = Field(
        1,
        description="Number of video variants to generate (1-4).",
        ge=1,
        le=4,
    )


GenerateCreativeVideoSchema = GenerateCreativeVideoInput


async def generate_creative_video(arguments: dict[str, Any]) -> list[TextContent]:
    """Generate a cinematic video using Google Veo.

    Args:
        arguments: Tool arguments from MCP call

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

        logger.info(
            "generate_creative_video called",
            extra={
                "tool": "generate_creative_video",
                "model": input_data.model,
                "duration": input_data.duration,
                "sample_count": input_data.sample_count,
            },
        )

        client = VeoClient()
        result = await client.generate_video(
            prompt=input_data.prompt,
            negative_prompt=input_data.negative_prompt,
            aspect_ratio=input_data.aspect_ratio,
            duration=input_data.duration,
            model=input_data.model,
            seed=input_data.seed,
            sample_count=input_data.sample_count,
        )

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

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

        if "safety" in error_msg.lower() or "blocked" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "CONTENT_BLOCKED",
                            "message": "Prompt was blocked by safety filters. Try a different prompt.",
                        },
                        indent=2,
                    ),
                )
            ]

        if not arguments.get("prompt") or len(arguments.get("prompt", "").strip()) == 0:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_PROMPT",
                            "message": "Prompt is empty or too vague.",
                        },
                        indent=2,
                    ),
                )
            ]

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