"""videogen-mcp - MCP Server

Unified video generation with intelligent HeyGen/Veo routing.

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

# Unified interface tools
from .tools.generate_video import generate_video, GenerateVideoSchema
from .tools.get_video_status import get_video_status, GetVideoStatusSchema
from .tools.download_video import download_video, DownloadVideoSchema

# HeyGen-specific tools
from .tools.list_avatars import list_avatars, ListAvatarsSchema
from .tools.list_voices import list_voices, ListVoicesSchema
from .tools.create_avatar_video import create_avatar_video, CreateAvatarVideoSchema
from .tools.list_templates import list_templates, ListTemplatesSchema
from .tools.get_template_details import get_template_details, GetTemplateDetailsSchema
from .tools.generate_from_template import generate_from_template, GenerateFromTemplateSchema

# Veo-specific tools
from .tools.generate_creative_video import generate_creative_video, GenerateCreativeVideoSchema
from .tools.generate_video_from_image import generate_video_from_image, GenerateVideoFromImageSchema

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

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


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

    Returns:
        List of Tool definitions for MCP protocol
    """
    return [
        # Unified interface tools
        Tool(
            name="generate_video",
            description="Generate a video from a text prompt. Automatically routes to HeyGen (avatar/presenter) or Veo (creative/cinematic) based on content. Returns job_id for status polling.",
            inputSchema=GenerateVideoSchema.model_json_schema(),
        ),
        Tool(
            name="get_video_status",
            description="Check the status of a video generation job. Works for both HeyGen and Veo. Poll until status is 'completed' or 'failed'.",
            inputSchema=GetVideoStatusSchema.model_json_schema(),
        ),
        Tool(
            name="download_video",
            description="Get the download URL for a completed video. Call get_video_status first to ensure completion.",
            inputSchema=DownloadVideoSchema.model_json_schema(),
        ),
        # HeyGen-specific tools
        Tool(
            name="list_avatars",
            description="List available HeyGen avatars including stock and custom Instant Avatars.",
            inputSchema=ListAvatarsSchema.model_json_schema(),
        ),
        Tool(
            name="list_voices",
            description="List available HeyGen voices for avatar videos including stock and cloned voices.",
            inputSchema=ListVoicesSchema.model_json_schema(),
        ),
        Tool(
            name="create_avatar_video",
            description="Create a HeyGen avatar video with specific avatar and voice selection. Use for precise control over avatar.",
            inputSchema=CreateAvatarVideoSchema.model_json_schema(),
        ),
        Tool(
            name="list_templates",
            description="List available HeyGen templates with customizable variables.",
            inputSchema=ListTemplatesSchema.model_json_schema(),
        ),
        Tool(
            name="get_template_details",
            description="Get HeyGen template details including all customizable variables.",
            inputSchema=GetTemplateDetailsSchema.model_json_schema(),
        ),
        Tool(
            name="generate_from_template",
            description="Generate a HeyGen video from a template with custom variable values.",
            inputSchema=GenerateFromTemplateSchema.model_json_schema(),
        ),
        # Veo-specific tools
        Tool(
            name="generate_creative_video",
            description="Generate cinematic video using Google Veo. Best for b-roll, visual storytelling, and scenes without a presenter.",
            inputSchema=GenerateCreativeVideoSchema.model_json_schema(),
        ),
        Tool(
            name="generate_video_from_image",
            description="Animate a static image into video using Google Veo. The image becomes the first frame.",
            inputSchema=GenerateVideoFromImageSchema.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:
        # Unified interface tools
        case "generate_video":
            return await generate_video(arguments)
        case "get_video_status":
            return await get_video_status(arguments)
        case "download_video":
            return await download_video(arguments)
        # HeyGen-specific tools
        case "list_avatars":
            return await list_avatars(arguments)
        case "list_voices":
            return await list_voices(arguments)
        case "create_avatar_video":
            return await create_avatar_video(arguments)
        case "list_templates":
            return await list_templates(arguments)
        case "get_template_details":
            return await get_template_details(arguments)
        case "generate_from_template":
            return await generate_from_template(arguments)
        # Veo-specific tools
        case "generate_creative_video":
            return await generate_creative_video(arguments)
        case "generate_video_from_image":
            return await generate_video_from_image(arguments)
        case _:
            raise ValueError(f"Unknown tool: {name}")


async def run_server():
    """Run the MCP server using stdio transport."""
    logger.info("Starting videogen-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()
