"""edit_video - Edit a video by adding clips or trimming sections.

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 EditVideoInput(BaseModel):
    """Input schema for edit_video.

    Edit a video by adding clips or trimming sections.
    """

    video_id: str = Field(
        ...,
        min_length=1,
        description="Unique identifier for the video",
    )
    editing_details: dict[str, Any] = Field(
        ...,
        description=(
            "Details for editing the video. Supported options:\n"
            "- trim_start: Start time in seconds to trim from beginning\n"
            "- trim_end: End time in seconds where video should end\n"
            "- clips: List of clip objects with 'start' and 'end' times in seconds\n"
            "- title: Optional new title for the edited video\n"
            "- description: Optional new description for the edited video"
        ),
    )


EditVideoSchema = EditVideoInput


async def edit_video(arguments: dict[str, Any]) -> list[TextContent]:
    """Edit a video by adding clips or trimming sections.

    Args:
        arguments: Tool arguments from MCP call containing video_id and editing_details

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

        logger.info(
            "edit_video called",
            extra={
                "tool": "edit_video",
                "video_id": validated.video_id,
                "has_trim_start": "trim_start" in validated.editing_details,
                "has_trim_end": "trim_end" in validated.editing_details,
                "has_clips": "clips" in validated.editing_details,
            },
        )

        # Validate editing_details structure
        editing_details = validated.editing_details
        valid_keys = {"trim_start", "trim_end", "clips", "title", "description"}
        invalid_keys = set(editing_details.keys()) - valid_keys

        if invalid_keys:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_PARAMETERS",
                            "message": f"Invalid editing parameters: {', '.join(invalid_keys)}. "
                            f"Valid options are: {', '.join(valid_keys)}",
                        },
                        indent=2,
                    ),
                )
            ]

        # Validate clips structure if provided
        if "clips" in editing_details:
            clips = editing_details["clips"]
            if not isinstance(clips, list):
                return [
                    TextContent(
                        type="text",
                        text=json.dumps(
                            {
                                "error": True,
                                "code": "INVALID_PARAMETERS",
                                "message": "clips must be a list of objects with 'start' and 'end' times",
                            },
                            indent=2,
                        ),
                    )
                ]

            for i, clip in enumerate(clips):
                if not isinstance(clip, dict) or "start" not in clip or "end" not in clip:
                    return [
                        TextContent(
                            type="text",
                            text=json.dumps(
                                {
                                    "error": True,
                                    "code": "INVALID_PARAMETERS",
                                    "message": f"Clip at index {i} must have 'start' and 'end' times",
                                },
                                indent=2,
                            ),
                        )
                    ]

        client = LoomClient()
        result = await client.edit_video(
            video_id=validated.video_id,
            editing_details=validated.editing_details,
        )

        response = {
            "success": True,
            "message": "Video edit initiated",
            "video_id": validated.video_id,
            "result": result,
        }

        logger.info(
            "edit_video completed",
            extra={
                "tool": "edit_video",
                "video_id": validated.video_id,
            },
        )

        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 edit this video.",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 404:
            video_id = arguments.get("video_id", "unknown")
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "NOT_FOUND",
                            "message": f"Video not found: {video_id}",
                        },
                        indent=2,
                    ),
                )
            ]
        elif error_code == 400:
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "BAD_REQUEST",
                            "message": "Invalid editing parameters. Check your trim times and clips.",
                        },
                        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"edit_video 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"edit_video error: {error_msg}")
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "error": True,
                        "message": error_msg,
                    },
                    indent=2,
                ),
            )
        ]
