"""download_video - Get download URL for completed videos.

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

logger = logging.getLogger("videogen_mcp")


class DownloadVideoInput(BaseModel):
    """Input schema for download_video."""

    job_id: str = Field(
        ...,
        description="The job_id of the completed video.",
        min_length=1,
    )
    service: str = Field(
        ...,
        description="Which service created this job: 'heygen' or 'veo'.",
    )


DownloadVideoSchema = DownloadVideoInput


async def download_video(arguments: dict[str, Any]) -> list[TextContent]:
    """Get the download URL for a completed video.

    Args:
        arguments: Tool arguments from MCP call

    Returns:
        List of TextContent with download information
    """
    try:
        input_data = DownloadVideoInput(**arguments)

        service = input_data.service.lower().strip()
        if service not in ("heygen", "veo"):
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_SERVICE",
                            "message": "Service must be 'heygen' or 'veo'.",
                        },
                        indent=2,
                    ),
                )
            ]

        logger.info(
            "download_video called",
            extra={
                "tool": "download_video",
                "job_id": input_data.job_id,
                "service": service,
            },
        )

        if service == "heygen":
            client = HeyGenClient()
            status_result = await client.get_video_status(input_data.job_id)
        else:
            client = VeoClient()
            status_result = await client.get_operation_status(input_data.job_id)

        status = status_result.get("status", "")

        if status == "failed":
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "VIDEO_GENERATION_FAILED",
                            "message": status_result.get("error_message", "Video generation failed."),
                        },
                        indent=2,
                    ),
                )
            ]

        if status != "completed":
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "VIDEO_NOT_READY",
                            "message": f"Video generation is not yet complete. Current status: {status}",
                            "current_status": status,
                            "progress_percent": status_result.get("progress_percent", 0),
                        },
                        indent=2,
                    ),
                )
            ]

        # Build download result
        result: dict[str, Any] = {
            "job_id": input_data.job_id,
            "service": service,
            "video_url": status_result.get("video_url"),
        }

        if "thumbnail_url" in status_result:
            result["thumbnail_url"] = status_result["thumbnail_url"]

        if "duration_seconds" in status_result:
            result["duration_seconds"] = status_result["duration_seconds"]

        # For Veo, we might have multiple videos
        if "videos" in status_result and len(status_result["videos"]) > 1:
            result["additional_videos"] = status_result["videos"][1:]

        if not result["video_url"]:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "VIDEO_EXPIRED",
                            "message": "Video URL has expired or is not available. Regeneration may be required.",
                        },
                        indent=2,
                    ),
                )
            ]

        logger.info(
            "download_video completed",
            extra={
                "tool": "download_video",
                "job_id": input_data.job_id,
            },
        )

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

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