# Copyright (C) 2026 GoodData Corporation

"""Reply to a PR review comment (threaded)."""

from __future__ import annotations

from typing import cast

from aida_mcp.tools.github.client import GithubApiError, github_get_json, github_post_json
from aida_mcp.tools.github.comments_types import ReplyResult
from aida_mcp.tools.github.comments_url import ensure_ai_reply_prefix, parse_review_comment_url


async def reply_to_review_comment(*, comment_url: str, body: str) -> ReplyResult:
    repo, comment_id = parse_review_comment_url(comment_url)

    # Fetch comment to get the PR number deterministically.
    comment_obj = await github_get_json(f"/repos/{repo}/pulls/comments/{comment_id}")
    if not isinstance(comment_obj, dict):
        raise GithubApiError("Unexpected review comment response shape.")
    comment = cast(dict[str, object], comment_obj)
    pr_url = comment.get("pull_request_url")
    if not isinstance(pr_url, str) or not pr_url:
        raise GithubApiError("Comment is not associated with a pull request (unexpected).")

    # pr_url looks like: https://api.github.com/repos/<owner>/<repo>/pulls/<n>
    pr_number_str = pr_url.rstrip("/").split("/")[-1]
    if not pr_number_str.isdigit():
        raise GithubApiError("Could not parse PR number from pull_request_url.")
    pr_number = int(pr_number_str)

    # Create a reply (threaded) by creating a PR review comment with in_reply_to.
    payload = {"body": ensure_ai_reply_prefix(body), "in_reply_to": comment_id}
    reply_obj = await github_post_json(f"/repos/{repo}/pulls/{pr_number}/comments", json_body=payload)

    if not isinstance(reply_obj, dict):
        raise GithubApiError("Unexpected GitHub response when creating reply comment.")
    reply = cast(dict[str, object], reply_obj)
    rid = reply.get("id")
    rurl = reply.get("html_url")
    if not isinstance(rid, int) or not isinstance(rurl, str):
        raise GithubApiError("Unexpected GitHub response when creating reply comment.")

    return {
        "ok": True,
        "repo": repo,
        "pr_number": pr_number,
        "in_reply_to": comment_id,
        "reply_id": rid,
        "reply_url": rurl,
    }
