"""Usage statistics CLI command"""

from typing import Optional

import typer
from rich import print as rprint
from rich.table import Table


def usage(
    agent: Optional[str] = typer.Option(None, "--agent", "-a", help="Filter by agent name"),
    format: str = typer.Option("table", "--format", "-f", help="Output format: table or json"),
    server_url: Optional[str] = typer.Option(None, "--server-url", help="AgentKit server URL"),
):
    """Show LLM usage statistics"""
    if server_url:
        import httpx
        try:
            with httpx.Client(timeout=10.0) as client:
                params = {}
                if agent:
                    params["agent_name"] = agent
                response = client.get(f"{server_url}/api/v1/llm/usage", params=params)
                response.raise_for_status()
                data = response.json()
        except Exception as e:
            rprint(f"[red]Error: {e}[/red]")
            raise typer.Exit(code=1)
    else:
        # Local mode: use LLMGateway.UsageTracker
        try:
            from agentkit.llm.gateway import LLMGateway
            gateway = LLMGateway()
            summary = gateway.get_usage(agent_name=agent)
            data = {
                "total_tokens": summary.total_tokens,
                "total_cost": summary.total_cost,
                "total_requests": len(summary.records),
                "by_model": summary.by_model,
            }
        except Exception as e:
            rprint(f"[dim]No usage data available: {e}[/dim]")
            data = {"total_requests": 0, "total_tokens": 0, "total_cost": 0.0}

    if format == "json":
        import json
        rprint(json.dumps(data, indent=2, ensure_ascii=False))
    else:
        table = Table(title="LLM Usage Statistics")
        table.add_column("Metric", style="cyan")
        table.add_column("Value")
        for key, value in data.items():
            if isinstance(value, float):
                table.add_row(key, f"{value:.4f}")
            else:
                table.add_row(key, str(value))
        rprint(table)
