"""Detect whether a PR was generated by an AI coding agent."""

from __future__ import annotations

import re

from mergeguard.models import AIAttribution, PRInfo

# Patterns that strongly indicate AI authorship
AI_COMMIT_PATTERNS = [
    r"generated by (claude|cursor|copilot|devin|aider|windsurf|codex)",
    r"co-authored-by:.*\b(cursor|copilot|devin|aider|windsurf)\b",
    r"^\[?(claude|cursor|aider|devin)\]?\s",
    r"feat\(ai\):",
    r"generated with .*(claude|gpt|gemini|copilot)",
]

# Files that indicate AI agent involvement
AI_MARKER_FILES = [
    ".cursor/",
    ".aider",
    ".claude/",
    ".agent-trace/",
    ".devin/",
    ".copilot/",
    "AGENTS.md",
]

# Branch name patterns
AI_BRANCH_PATTERNS = [
    r"^(cursor|aider|devin|claude|copilot)[-/]",
    r"^ai[-/]",
    r"^agent[-/]",
]


def detect_attribution(pr: PRInfo) -> AIAttribution:
    """Determine if a PR was likely generated by an AI agent.

    Uses a scoring system: accumulate evidence signals and classify
    based on total confidence.
    """
    confidence = 0.0

    # Check commit message patterns (from PR title as proxy)
    title_lower = pr.title.lower()
    for pattern in AI_COMMIT_PATTERNS:
        if re.search(pattern, title_lower, re.IGNORECASE):
            confidence += 0.6
            break

    # Check PR description
    desc_lower = pr.description.lower()
    for pattern in AI_COMMIT_PATTERNS:
        if re.search(pattern, desc_lower, re.IGNORECASE):
            confidence += 0.4
            break

    # Check for AI marker files in the diff
    for changed_file in pr.changed_files:
        for marker in AI_MARKER_FILES:
            if marker in changed_file.path:
                confidence += 0.5
                break

    # Check branch name
    for pattern in AI_BRANCH_PATTERNS:
        if re.search(pattern, pr.head_branch, re.IGNORECASE):
            confidence += 0.3
            break

    # Check labels
    ai_labels = {"ai-generated", "bot", "automated", "agent"}
    if ai_labels & {label.lower() for label in pr.labels}:
        confidence += 0.7

    # Check for Agent Trace data
    for changed_file in pr.changed_files:
        if ".agent-trace/" in changed_file.path:
            return AIAttribution.AI_CONFIRMED

    # Classify
    if confidence >= 0.6:
        return AIAttribution.AI_CONFIRMED
    elif confidence >= 0.3:
        return AIAttribution.AI_SUSPECTED
    else:
        return AIAttribution.UNKNOWN
