"""Score calculation and pattern detection algorithms."""

from __future__ import annotations

from dashboard.services.scorecard.types import AgentMetrics


def calculate_pr_merge_rate(prs_opened: int, prs_merged: int) -> float:
    """Calculate PR merge rate.

    Args:
        prs_opened: Number of PRs opened
        prs_merged: Number of PRs merged

    Returns:
        Merge rate between 0.0 and 1.0
    """
    if prs_opened == 0:
        return 0.0
    return prs_merged / prs_opened


def detect_patterns(metrics: AgentMetrics) -> list[str]:
    """Detect interesting patterns in agent behavior.

    Args:
        metrics: The agent's metrics

    Returns:
        List of pattern descriptions
    """
    patterns: list[str] = []

    pr_opened = len(metrics.prs_opened)
    merge_rate = metrics.pr_merge_rate

    # Merge rate patterns
    if pr_opened >= 3:
        if merge_rate >= 0.8:
            patterns.append("High merge rate with few failures — code quality focus.")
        elif merge_rate <= 0.3:
            patterns.append("Lots of noisy PRs, low merge rate — may need review support.")

    # Activity patterns
    if metrics.commits > 10 and pr_opened == 0:
        patterns.append("High commit volume without PRs — working directly on main?")

    if len(metrics.issues_touched) > 5 and metrics.comments == 0:
        patterns.append("Touching many issues but low comment volume — silent worker.")

    if metrics.comments > len(metrics.issues_touched) * 2:
        patterns.append("Highly communicative — lots of discussion relative to work items.")

    # Token patterns
    net_tokens = metrics.tokens_earned - metrics.tokens_spent
    if net_tokens > 100:
        patterns.append("Strong token accumulation — high value delivery.")
    elif net_tokens < -50:
        patterns.append("High token spend — may be in experimentation phase.")

    return patterns
