"""list_recorded_videos - Retrieve a list of recorded videos.

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

    Retrieve a list of recorded videos from Loom.
    """

    limit: int = Field(
        default=50,
        ge=1,
        le=100,
        description="Maximum number of videos to return (1-100, default 50)",
    )
    offset: int = Field(
        default=0,
        ge=0,
        description="Pagination offset (default 0)",
    )
    folder_id: str | None = Field(
        default=None,
        description="Optional folder ID to filter videos by folder",
    )


ListRecordedVideosSchema = ListRecordedVideosInput


async def list_recorded_videos(arguments: dict[str, Any]) -> list[TextContent]:
    """Retrieve a list of recorded videos from Loom.

    Args:
        arguments: Tool arguments from MCP call

    Returns:
        List of TextContent with videos list
    """
    try:
        # Validate input
        validated = ListRecordedVideosInput(**arguments)

        logger.info(
            "list_recorded_videos called",
            extra={
                "tool": "list_recorded_videos",
                "limit": validated.limit,
                "offset": validated.offset,
            },
        )

        client = LoomClient()
        result = await client.list_videos(
            limit=validated.limit,
            offset=validated.offset,
            folder_id=validated.folder_id,
        )

        # Format response
        videos = result.get("videos", [])
        total = result.get("total", len(videos))

        response = {
            "success": True,
            "total_videos": total,
            "returned_count": len(videos),
            "offset": validated.offset,
            "videos": videos,
        }

        logger.info(
            "list_recorded_videos completed",
            extra={
                "tool": "list_recorded_videos",
                "total": total,
                "returned": len(videos),
            },
        )

        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. Your token may not have permission to list videos.",
                        },
                        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"list_recorded_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"list_recorded_videos error: {error_msg}")
        return [
            TextContent(
                type="text",
                text=json.dumps(
                    {
                        "error": True,
                        "message": error_msg,
                    },
                    indent=2,
                ),
            )
        ]
