"""Git repository already-implemented validation helpers."""

from __future__ import annotations

import re
from typing import Dict, List, Optional

from packages.integrations.doc_validation import DocReference
from packages.integrations.github_search import CodeEvidence, GitHubEvidence
from packages.integrations.jira import JiraIssue
from packages.knowledge.retrievers import KnowledgeHit

GIT_REVIEW_HEADING = "Agent Nova: functionality may already be implemented in Git"
GIT_EXISTING_CODE_HEADING = "Agent Nova: related code found in GitHub"

_API_NAME = re.compile(r"\b[A-Za-z][A-Za-z0-9_]*__c\b")
_PATH_HIT_TITLE = re.compile(r"^(?P<path>\S+)(?: \[[A-Za-z]+\])?$")
_REPO_FROM_URL = re.compile(r"github\.com/([^/]+/[^/]+)/")
MAX_EXISTING_CODE = 15


def api_names_in(text: str) -> List[str]:
    return list(dict.fromkeys(_API_NAME.findall(text or "")))


def git_search_query(issue: JiraIssue) -> str:
    """Summary plus explicit API names, so field/object names are not truncated away."""
    names = api_names_in(f"{issue.summary}\n{issue.description}")
    return " ".join([issue.summary, *names]).strip()


def file_hits(hits: List[KnowledgeHit]) -> List[KnowledgeHit]:
    return [h for h in hits if h.source == "git" and not h.title.startswith("Repository inventory")]


def exact_api_matches(issue: JiraIssue, hits: List[KnowledgeHit]) -> List[str]:
    names = api_names_in(f"{issue.summary}\n{issue.description}")
    return [n for n in names if any(n.lower() in h.title.lower() for h in hits)]


def evidence_from_hits(hits: List[KnowledgeHit]) -> List[CodeEvidence]:
    """Convert path-matched repo hits (``path [Kind]``) to default-branch code evidence."""
    out: List[CodeEvidence] = []
    for h in file_hits(hits):
        m = _PATH_HIT_TITLE.match(h.title.strip())
        repo_m = _REPO_FROM_URL.search(h.url or "")
        out.append(
            CodeEvidence(
                kind="code",
                repo=repo_m.group(1) if repo_m else "",
                title=m.group("path") if m else h.title,
                url=h.url or "",
                snippet=h.snippet or "",
                state="default",
            )
        )
    return out


def select_existing_code(
    refs: List[DocReference], evidence: List[CodeEvidence]
) -> List[CodeEvidence]:
    """Evidence the LLM cited; all evidence when the citations do not map back."""
    keys = {r.url for r in refs if r.url} | {r.title for r in refs if r.title}
    cited = [
        ev
        for ev in evidence
        if ev.url in keys or ev.title in keys or ev.label() in keys or any(ev.title and ev.title in k for k in keys)
    ]
    # Ticket-key references are always relevant to the design
    keyed = [ev for ev in evidence if ev.kind in ("commit", "pr", "branch") and ev not in cited]
    chosen = (cited or list(evidence)) + keyed
    unique: List[CodeEvidence] = []
    for ev in chosen:
        if ev not in unique:
            unique.append(ev)
    return unique[:MAX_EXISTING_CODE]


_URL_GROUPS = (
    ("Pull requests", re.compile(r"/pull/\d+")),
    ("Commits", re.compile(r"/commit/[0-9a-f]+")),
    ("Branches", re.compile(r"/tree/")),
    ("Files", re.compile(r"/blob/")),
)


def _group_refs(refs: List[DocReference]) -> Dict[str, List[DocReference]]:
    groups: Dict[str, List[DocReference]] = {}
    for ref in refs:
        name = next((g for g, pat in _URL_GROUPS if ref.url and pat.search(ref.url)), "Files")
        groups.setdefault(name, []).append(ref)
    order = [g for g, _ in _URL_GROUPS[::-1]]
    return {g: groups[g] for g in order if g in groups}


def _ref_lines(refs: List[DocReference]) -> List[str]:
    lines: List[str] = []
    for label, group in _group_refs(refs).items():
        lines.append(f"{label}:")
        for i, ref in enumerate(group, start=1):
            link = f" — {ref.url}" if ref.url else ""
            lines.append(f"{i}. {ref.title}{link}")
    return lines


def git_review_comment_body(refs: List[DocReference], rationale: str = "") -> str:
    lines = [
        f"## {GIT_REVIEW_HEADING}",
        "",
        "GitHub already contains code, commits, or pull requests that appear to implement this request.",
    ]
    if rationale.strip():
        lines.extend(["", f"Reason: {rationale.strip()}"])
    lines.append("")
    if refs:
        lines.extend(_ref_lines(refs))
    else:
        lines.extend(["Files:", "- (see repository search results)"])
    lines.extend(
        [
            "",
            "Next step: reply with `continue` to proceed anyway, or `already done` / "
            "`close` to stop this run.",
        ]
    )
    return "\n".join(lines)


def existing_code_comment_body(evidence: List[CodeEvidence], rationale: str = "") -> str:
    lines = [
        f"## {GIT_EXISTING_CODE_HEADING}",
        "",
        "Part of this request already exists in GitHub. The design will extend or update "
        "this code instead of recreating it.",
    ]
    if rationale.strip():
        lines.extend(["", f"Reason: {rationale.strip()}"])
    lines.append("")
    refs = [DocReference(title=ev.label(), url=ev.url) for ev in evidence]
    lines.extend(_ref_lines(refs) if refs else ["- (see repository search results)"])
    lines.extend(["", "No action needed; Agent Nova is continuing with the design."])
    return "\n".join(lines)


def _evidence_lines(items: List[CodeEvidence]) -> List[str]:
    if not items:
        return ["(none)"]
    lines: List[str] = []
    for ev in items:
        lines.extend(
            [
                f"- Title: {ev.label()}",
                f"  URL: {ev.url or '(none)'}",
                f"  Snippet: {(ev.snippet or '')[:600]}",
            ]
        )
    return lines


def build_git_check_prompt(
    issue: JiraIssue,
    hits: List[KnowledgeHit],
    inventory: str = "",
    evidence: Optional[GitHubEvidence] = None,
) -> str:
    exact = exact_api_matches(issue, hits)
    lines = [
        "Decide whether the NEW Jira ticket requests Salesforce functionality that ALREADY "
        "EXISTS in GitHub (repository files, code search matches, commits, pull requests, branches).",
        "Mark already_implemented=true only when the evidence clearly implements the same feature "
        "(same object, same field/rule/flow/class, same behavior). A MERGED pull request or a "
        "default-branch commit that references this ticket key, together with matching code, is "
        "strong evidence for already_implemented=true.",
        "Mark partially_implemented=true (and already_implemented=false) when related code exists "
        "that the ticket would CHANGE or EXTEND (new values, new logic, extra fields on an existing "
        "object), or when an OPEN pull request / branch for this ticket key exists but is not merged.",
        "Mark both false when the evidence is only loosely related.",
        "If either is true, list the matching evidence as references: title = file path or "
        "PR/commit title, url = its URL.",
        "",
        "NEW ticket:",
        f"Key: {issue.key}",
        f"Summary: {issue.summary}",
        f"Description: {(issue.description or '')[:2000]}",
        "",
        "REPOSITORY FILES:",
    ]
    if inventory:
        lines.append(f"Inventory: {inventory}")
    if exact:
        lines.append(f"Exact API-name matches in repo: {', '.join(exact)}")
    if not hits:
        lines.append("(none)")
    for h in hits:
        lines.extend(
            [
                f"- Title: {h.title}",
                f"  URL: {h.url or '(none)'}",
                f"  Snippet: {(h.snippet or '')[:600]}",
            ]
        )
    if evidence is not None:
        lines.extend(["", "CODE MATCHES:", *_evidence_lines(evidence.code)])
        lines.extend(["", "TICKET KEY REFERENCES:", *_evidence_lines(evidence.ticket_refs)])
        lines.extend(["", "OPEN PR FILES:", *_evidence_lines(evidence.pr_files)])
    return "\n".join(lines)
