"""merge_videos - Combine multiple videos into one.

Generated by GRIMLOCK MCP Factory
"""

import json
import logging
from typing import Any

import httpx
from mcp.types import TextContent
from pydantic import BaseModel, Field

from ..clients.loom import LoomClient

logger = logging.getLogger("loom_mcp")


class MergeVideosInput(BaseModel):
    """Input schema for merge_videos.

    Combine multiple videos into one merged video.
    """

    video_ids: list[str] = Field(
        ...,
        min_length=2,
        description="List of Video IDs to merge (minimum 2). Videos will be merged in the order provided.",
    )
    title: str | None = Field(
        default=None,
        description="Optional title for the merged video",
    )


MergeVideosSchema = MergeVideosInput


async def merge_videos(arguments: dict[str, Any]) -> list[TextContent]:
    """Combine multiple videos into one.

    Args:
        arguments: Tool arguments from MCP call containing video_ids and optional title

    Returns:
        List of TextContent with merge result
    """
    try:
        # Validate input
        validated = MergeVideosInput(**arguments)

        logger.info(
            "merge_videos called",
            extra={
                "tool": "merge_videos",
                "video_count": len(validated.video_ids),
                "has_title": validated.title is not None,
            },
        )

        # Validate video IDs are not empty strings
        empty_ids = [i for i, vid in enumerate(validated.video_ids) if not vid.strip()]
        if empty_ids:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_PARAMETERS",
                            "message": f"Empty video ID(s) at position(s): {empty_ids}",
                        },
                        indent=2,
                    ),
                )
            ]

        # Check for duplicate video IDs
        seen = set()
        duplicates = []
        for vid in validated.video_ids:
            if vid in seen:
                duplicates.append(vid)
            seen.add(vid)

        if duplicates:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_PARAMETERS",
                            "message": f"Duplicate video ID(s): {duplicates}",
                        },
                        indent=2,
                    ),
                )
            ]

        client = LoomClient()
        result = await client.merge_videos(
            video_ids=validated.video_ids,
            title=validated.title,
        )

        response = {
            "success": True,
            "message": "Video merge initiated",
            "source_videos": validated.video_ids,
            "result": result,
        }

        logger.info(
            "merge_videos completed",
            extra={
                "tool": "merge_videos",
                "video_count": len(validated.video_ids),
            },
        )

        return [
            TextContent(
                type="text",
                text=json.dumps(response, indent=2),
            )
        ]

    except httpx.HTTPStatusError as e:
        error_code = e.response.status_code
        error_msg = str(e)

        if error_code == 401:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "AUTH_FAILED",
                            "message": "Loom access token is invalid or expired. Check your LOOM_ACCESS_TOKEN.",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 403:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "FORBIDDEN",
                            "message": "Access denied. You may not have permission to merge these videos.",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 404:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "NOT_FOUND",
                            "message": "One or more videos not found. Check your video IDs.",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 400:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "BAD_REQUEST",
                            "message": "Invalid merge request. Ensure all video IDs are valid.",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 429:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "RATE_LIMITED",
                            "message": "Rate limit exceeded. Please wait before retrying.",
                        },
                        indent=2,
                    ),
                )
            ]

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

    except (httpx.ConnectError, httpx.TimeoutException) as e:
        error_msg = str(e)
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "error": True,
                        "code": "CONNECTION_FAILED",
                        "message": f"Failed to connect to Loom API. Error: {error_msg}",
                    },
                    indent=2,
                ),
            )
        ]

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