"""get_video_status - Check video generation job status.

Works for both HeyGen and Veo jobs.

Generated by GRIMLOCK MCP Factory
"""

import json
import logging
from typing import Any

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

from ..clients.heygen import HeyGenClient
from ..clients.veo import VeoClient

logger = logging.getLogger("videogen_mcp")


class GetVideoStatusInput(BaseModel):
    """Input schema for get_video_status."""

    job_id: str = Field(
        ...,
        description="The job_id returned from generate_video or other generation tools.",
        min_length=1,
    )
    service: str = Field(
        ...,
        description="Which service created this job: 'heygen' or 'veo'.",
    )


GetVideoStatusSchema = GetVideoStatusInput


async def get_video_status(arguments: dict[str, Any]) -> list[TextContent]:
    """Check the status of a video generation job.

    Args:
        arguments: Tool arguments from MCP call

    Returns:
        List of TextContent with status information
    """
    try:
        input_data = GetVideoStatusInput(**arguments)

        service = input_data.service.lower().strip()
        if service not in ("heygen", "veo"):
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "INVALID_SERVICE",
                            "message": "Service must be 'heygen' or 'veo'.",
                        },
                        indent=2,
                    ),
                )
            ]

        logger.info(
            "get_video_status called",
            extra={
                "tool": "get_video_status",
                "job_id": input_data.job_id,
                "service": service,
            },
        )

        if service == "heygen":
            client = HeyGenClient()
            result = await client.get_video_status(input_data.job_id)
        else:
            client = VeoClient()
            result = await client.get_operation_status(input_data.job_id)

        result["job_id"] = input_data.job_id
        result["service"] = service

        logger.info(
            "get_video_status completed",
            extra={
                "tool": "get_video_status",
                "status": result.get("status"),
            },
        )

        return [
            TextContent(
                type="text",
                text=json.dumps({"success": True, **result}, indent=2),
            )
        ]

    except Exception as e:
        error_msg = str(e)
        # Check for common error patterns
        if "404" in error_msg or "not found" in error_msg.lower():
            return [
                TextContent(
                    type="text",
                    text=json.dumps(
                        {
                            "error": True,
                            "code": "JOB_NOT_FOUND",
                            "message": f"No job exists with ID: {arguments.get('job_id')}",
                        },
                        indent=2,
                    ),
                )
            ]

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