"""generate_video_from_image - Animate a static image into video using 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 GenerateVideoFromImageInput(BaseModel):
    """Input schema for generate_video_from_image."""

    image_url: str = Field(
        ...,
        description="URL of the source image. Recommended: 720p+ resolution.",
        min_length=1,
    )
    prompt: str = Field(
        ...,
        description="Description of how the image should animate. Describe motion, camera movement, and changes.",
        min_length=1,
    )
    negative_prompt: str | None = Field(
        None,
        description="Elements to avoid in the animation.",
    )
    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.",
    )


GenerateVideoFromImageSchema = GenerateVideoFromImageInput


async def generate_video_from_image(arguments: dict[str, Any]) -> list[TextContent]:
    """Animate a static image into a video using Google Veo.

    Args:
        arguments: Tool arguments from MCP call

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

        logger.info(
            "generate_video_from_image called",
            extra={
                "tool": "generate_video_from_image",
                "image_url": input_data.image_url[:50] + "...",
                "duration": input_data.duration,
            },
        )

        client = VeoClient()
        result = await client.generate_video_from_image(
            image_url=input_data.image_url,
            prompt=input_data.prompt,
            negative_prompt=input_data.negative_prompt,
            duration=input_data.duration,
            model=input_data.model,
        )

        logger.info(
            "generate_video_from_image completed",
            extra={
                "tool": "generate_video_from_image",
                "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 "not found" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_IMAGE",
                            "message": "Image URL not accessible. Verify the URL is public and valid.",
                        },
                        indent=2,
                    ),
                )
            ]

        if "small" in error_msg.lower() or "resolution" in error_msg.lower() or "size" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "IMAGE_TOO_SMALL",
                            "message": "Image resolution below minimum requirements. Use 720p or higher.",
                        },
                        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": "Image or prompt blocked by safety filters.",
                        },
                        indent=2,
                    ),
                )
            ]

        if "format" in error_msg.lower() or "unsupported" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_IMAGE",
                            "message": "Image format not supported. Use JPEG, PNG, GIF, or WebP.",
                        },
                        indent=2,
                    ),
                )
            ]

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