"""Presenter for billing project costs by agent command output."""

from decimal import Decimal

from alloy_runtime_types.dtos.billing import ProjectCostByAgent

from cli.infrastructure.output import OutputService
from cli.infrastructure.renderers.list_renderer import ColumnConfig


def _format_cost(cost: Decimal | None) -> str:
    """Format cost for display."""
    if cost is None:
        return "-"
    return f"${cost:.4f}"


def present_billing_costs_by_agent(entries: list[ProjectCostByAgent]) -> None:
    """Present billing project cost breakdown by agent."""
    output = OutputService.get()

    columns = [
        ColumnConfig(
            source_field="agent_name",
            header_label="Agent",
            compact_line=1,
            compact_style="green",
        ),
        ColumnConfig(
            source_field="agent_id",
            header_label="Agent ID",
            formatter=lambda x: str(x) if x else "(transient)",
            compact_line=2,
            compact_style="dim",
        ),
        ColumnConfig(
            source_field="execution_count",
            header_label="Executions",
            formatter=str,
            compact_line=1,
            compact_style="white",
        ),
        ColumnConfig(
            source_field="total_tokens",
            header_label="Total Tokens",
            formatter=lambda x: f"{x:,}",
            compact_line=2,
            compact_style="dim",
        ),
        ColumnConfig(
            source_field="llm_cost_usd",
            header_label="LLM Cost",
            formatter=_format_cost,
            compact_line=2,
            compact_style="dim",
        ),
        ColumnConfig(
            source_field="rag_cost_usd",
            header_label="RAG Cost",
            formatter=_format_cost,
            compact_line=2,
            compact_style="dim",
        ),
        ColumnConfig(
            source_field="total_cost_usd",
            header_label="Total Cost",
            formatter=_format_cost,
            compact_line=1,
            compact_style="green bold",
        ),
    ]

    output.table(
        items=entries,  # type: ignore[arg-type]
        title=f"Costs by Agent ({len(entries)} agents)",
        columns=columns,
        total_count=len(entries),
    )
