"""stats command — show aggregate statistics."""

from __future__ import annotations

import asyncio
from typing import Literal

import typer
from rich.console import Console
from rich.table import Table
from sqlalchemy.exc import OperationalError

from cli_framework import get_context
from session_hub_cli.cli import app
from session_hub_cli.commands._helpers import fmt_datetime, get_query_api, print_json
from session_hub_cli.context import SessionHubContext
from session_hub_core import Stats


@app.command("stats")
def stats(
    ctx: typer.Context,
    format: Literal["table", "json"] = typer.Option(
        "table", "--format", help="Output format: table, json"
    ),
) -> None:
    """Show aggregate statistics."""
    app_ctx = get_context(ctx)
    assert isinstance(app_ctx, SessionHubContext)
    console = app_ctx.console
    try:
        data = asyncio.run(_get_stats(console))
    except OperationalError as exc:
        console.print(f"[red]Error:[/red] Cannot connect to PostgreSQL: {exc}")
        raise typer.Exit(1) from None
    if format == "json":
        print_json(console, data.model_dump(mode="json"))
        return
    _print_table(console, data)


async def _get_stats(console: Console) -> Stats:
    api = get_query_api(console)
    try:
        return await api.get_stats()
    finally:
        await api.close()


def _print_table(console: Console, data: Stats) -> None:
    summary = Table(title="Session Hub Stats")
    summary.add_column("Metric")
    summary.add_column("Value")
    summary.add_row("Total sessions", str(data.total_sessions))
    summary.add_row("Total messages", str(data.total_messages))
    summary.add_row(
        "Date range",
        f"{fmt_datetime(data.oldest_session)} to {fmt_datetime(data.newest_session)}",
    )
    console.print(summary)

    hosts_table = Table(title="By Host")
    hosts_table.add_column("Host", style="cyan")
    hosts_table.add_column("Sessions", justify="right")
    hosts_table.add_column("Messages", justify="right")
    hosts_table.add_column("Last Sync", style="dim")
    for host, host_stats in sorted(data.by_host.items()):
        hosts_table.add_row(
            host,
            str(host_stats.sessions),
            str(host_stats.messages),
            fmt_datetime(host_stats.last_sync),
        )
    console.print(hosts_table)

    tools_table = Table(title="By Tool")
    tools_table.add_column("Tool", style="cyan")
    tools_table.add_column("Sessions", justify="right")
    tools_table.add_column("Messages", justify="right")
    for tool, tool_stats in sorted(data.by_tool.items()):
        tools_table.add_row(tool, str(tool_stats.sessions), str(tool_stats.messages))
    console.print(tools_table)
