"""loom-mcp - MCP Server

Video management for Loom screen recordings.

Generated by GRIMLOCK MCP Factory
"""

import asyncio
import logging
from typing import Any

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent, Tool

from .tools.list_recorded_videos import list_recorded_videos, ListRecordedVideosSchema
from .tools.get_video import get_video, GetVideoSchema
from .tools.edit_video import edit_video, EditVideoSchema
from .tools.merge_videos import merge_videos, MergeVideosSchema

# Initialize logger
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("loom_mcp")

# Initialize MCP server
server = Server("loom-mcp")


@server.list_tools()
async def list_tools() -> list[Tool]:
    """List available tools.

    Returns:
        List of Tool definitions for MCP protocol
    """
    return [
        Tool(
            name="list_recorded_videos",
            description="Retrieve a list of recorded videos from Loom. Returns video metadata including IDs, titles, thumbnails, and creation dates. Supports pagination and folder filtering.",
            inputSchema=ListRecordedVideosSchema.model_json_schema(),
        ),
        Tool(
            name="get_video",
            description="Retrieve a specific video by ID. Returns full video details including title, description, duration, embed URL, share link, and transcript availability.",
            inputSchema=GetVideoSchema.model_json_schema(),
        ),
        Tool(
            name="edit_video",
            description="Edit a video by adding clips or trimming sections. Supports trimming start/end, extracting clips, and updating metadata like title and description.",
            inputSchema=EditVideoSchema.model_json_schema(),
        ),
        Tool(
            name="merge_videos",
            description="Combine multiple videos into one merged video. Provide at least 2 video IDs in the desired merge order. Optionally specify a title for the merged result.",
            inputSchema=MergeVideosSchema.model_json_schema(),
        ),
    ]


@server.call_tool()
async def call_tool(name: str, arguments: dict[str, Any]) -> list[TextContent]:
    """Handle tool calls.

    Args:
        name: Name of the tool to execute
        arguments: Tool arguments

    Returns:
        List of TextContent with result

    Raises:
        ValueError: If tool name is unknown
    """
    logger.info(f"Tool called: {name}", extra={"tool": name, "has_args": bool(arguments)})

    match name:
        case "list_recorded_videos":
            return await list_recorded_videos(arguments)
        case "get_video":
            return await get_video(arguments)
        case "edit_video":
            return await edit_video(arguments)
        case "merge_videos":
            return await merge_videos(arguments)
        case _:
            raise ValueError(f"Unknown tool: {name}")


async def run_server():
    """Run the MCP server using stdio transport."""
    logger.info("Starting loom-mcp MCP server")

    async with stdio_server() as (read_stream, write_stream):
        await server.run(
            read_stream,
            write_stream,
            server.create_initialization_options(),
        )


def main():
    """Main entry point."""
    asyncio.run(run_server())


if __name__ == "__main__":
    main()
