# Copyright (C) 2026 GoodData Corporation

"""GitHub-related MCP tools (PR comments)."""

from __future__ import annotations

from typing import TYPE_CHECKING, Annotated

from pydantic import Field

from aida_mcp.server.app_instance import Context
from aida_mcp.tools.github.comments import (
    GithubCommentsAction,
    list_review_threads,
    reply_to_review_comment,
    resolve_review_thread,
)

if TYPE_CHECKING:
    from mcp.server.fastmcp import FastMCP


def register(mcp: FastMCP) -> None:
    """Register GitHub-related MCP tools."""
    mcp.tool()(github_comments)


async def github_comments(
    action: Annotated[
        GithubCommentsAction,
        Field(description=("Operation: reply_to_review_comment, resolve_review_thread, or list_review_threads.")),
    ],
    repo: Annotated[
        str,
        Field(description="Repository in 'owner/repo' (required for list_review_threads)."),
    ] = "",
    pr_number: Annotated[
        int | None,
        Field(description="PR number (required for list_review_threads)."),
    ] = None,
    comment_url: Annotated[
        str,
        Field(description=("Review comment URL ending with #discussion_r<ID>.")),
    ] = "",
    body: Annotated[
        str,
        Field(description="Reply body (required for reply_to_review_comment)."),
    ] = "",
    limit: Annotated[
        int,
        Field(description="Max threads returned for list_review_threads."),
    ] = 30,
    include_resolved: Annotated[
        bool,
        Field(description=("Include resolved threads in list output.")),
    ] = False,
    *,
    ctx: Context,
) -> object:
    """Manage PR review threads: list, reply, or resolve."""
    if action == "reply_to_review_comment":
        if not comment_url:
            raise ValueError("comment_url is required for reply_to_review_comment")
        if not body:
            raise ValueError("body is required for reply_to_review_comment")
        await ctx.info("💬 Replying in-thread to review comment…")
        return await reply_to_review_comment(comment_url=comment_url, body=body)

    if action == "resolve_review_thread":
        if not comment_url:
            raise ValueError("comment_url is required for resolve_review_thread")
        await ctx.info("✅ Resolving review thread…")
        return await resolve_review_thread(comment_url=comment_url)

    if action == "list_review_threads":
        if not repo:
            raise ValueError("repo is required for list_review_threads")
        if pr_number is None:
            raise ValueError("pr_number is required for list_review_threads")
        msg = "🧵 Listing review threads" + (" (including resolved)…" if include_resolved else "…")
        await ctx.info(msg)
        return await list_review_threads(repo=repo, pr_number=pr_number, limit=limit, include_resolved=include_resolved)

    raise ValueError(f"Unknown action: {action}")
