"""Display formatting and narrative generation for scorecards."""

from __future__ import annotations

from dashboard.services.scorecard.types import AgentMetrics, PeriodType


def format_activity_summary(metrics: AgentMetrics) -> list[str]:
    """Format activity summary items.

    Args:
        metrics: The agent's metrics

    Returns:
        List of activity description strings
    """
    activities = []
    if metrics.commits:
        activities.append(f"{metrics.commits} commit{'s' if metrics.commits != 1 else ''}")
    if len(metrics.prs_opened):
        activities.append(
            f"{len(metrics.prs_opened)} PR{'s' if len(metrics.prs_opened) != 1 else ''} opened"
        )
    if len(metrics.prs_merged):
        activities.append(
            f"{len(metrics.prs_merged)} PR{'s' if len(metrics.prs_merged) != 1 else ''} merged"
        )
    if len(metrics.issues_touched):
        activities.append(
            f"{len(metrics.issues_touched)} issue{'s' if len(metrics.issues_touched) != 1 else ''} touched"
        )
    if metrics.comments:
        activities.append(f"{metrics.comments} comment{'s' if metrics.comments != 1 else ''}")

    return activities


def format_token_summary(tokens_earned: int, tokens_spent: int) -> str | None:
    """Format token summary text.

    Args:
        tokens_earned: Tokens earned
        tokens_spent: Tokens spent

    Returns:
        Formatted token summary string or None if no token activity
    """
    if not tokens_earned and not tokens_spent:
        return None

    net_tokens = tokens_earned - tokens_spent
    if net_tokens > 0:
        return f"Net earned {net_tokens} tokens ({tokens_earned} earned, {tokens_spent} spent)."
    elif net_tokens < 0:
        return f"Net spent {abs(net_tokens)} tokens ({tokens_earned} earned, {tokens_spent} spent)."
    else:
        return f"Balanced token flow ({tokens_earned} earned, {tokens_spent} spent)."


def generate_narrative_bullets(metrics: AgentMetrics, period_type: PeriodType) -> list[str]:
    """Generate narrative summary bullets for a scorecard.

    Args:
        metrics: The agent's metrics
        period_type: daily or weekly

    Returns:
        List of narrative bullet points
    """
    bullets: list[str] = []
    period_label = "day" if period_type == PeriodType.daily else "week"

    # Activity summary
    activities = format_activity_summary(metrics)
    if activities:
        bullets.append(f"Active across {', '.join(activities)} this {period_label}.")

    # Test activity
    if len(metrics.tests_affected):
        bullets.append(
            f"Affected {len(metrics.tests_affected)} test file{'s' if len(metrics.tests_affected) != 1 else ''}."
        )

    # Token summary
    token_summary = format_token_summary(metrics.tokens_earned, metrics.tokens_spent)
    if token_summary:
        bullets.append(token_summary)

    # Handle empty case
    if not bullets:
        bullets.append(f"No recorded activity this {period_label}.")

    return bullets
