# Copyright (C) 2026 GoodData Corporation

"""Parsing helpers for GitHub PR review comment URLs."""

from __future__ import annotations

import re

_RE_REVIEW_COMMENT_ANCHOR = re.compile(r"#discussion_r(?P<comment_id>\d+)$")
_AI_REPLY_PREFIX = "**AI:** "


def ensure_ai_reply_prefix(body: str) -> str:
    """
    Ensure reply body is prefixed with a small markdown header (`**AI:** `).

    Idempotent: won't double-prefix if already present, and will normalize legacy '(AI):' prefixes.
    """
    stripped = body.lstrip()

    # Backward-compatible normalization for older prefixes.
    if stripped.startswith("(AI):"):
        rest = stripped[len("(AI):") :].lstrip()
        return f"{_AI_REPLY_PREFIX}{rest}"

    # Idempotent for the current markdown prefix.
    if stripped.startswith("**AI:**"):
        rest = stripped[len("**AI:**") :].lstrip()
        return f"{_AI_REPLY_PREFIX}{rest}"

    return f"{_AI_REPLY_PREFIX}{stripped}"


def parse_review_comment_url(comment_url: str) -> tuple[str, int]:
    """Return (repo, comment_id) from a review-comment URL.

    Expected format:
      https://github.com/<owner>/<repo>/pull/<n>#discussion_r<comment_id>
    """
    try:
        base, anchor = comment_url.split("#", 1)
    except ValueError as e:
        raise ValueError("comment_url must contain an anchor like #discussion_r123") from e

    m = _RE_REVIEW_COMMENT_ANCHOR.match(f"#{anchor}")
    if not m:
        raise ValueError("comment_url must be a PR review comment URL ending in #discussion_r<id>")

    parts = base.strip("/").split("/")
    # https: / / github.com / owner / repo / pull / number
    if len(parts) < 6 or parts[2] != "github.com":
        raise ValueError("comment_url must be a github.com URL to a PR review comment")
    owner = parts[3]
    repo_name = parts[4]
    repo = f"{owner}/{repo_name}"
    return repo, int(m.group("comment_id"))
