"""nestdx sessions — list historical sessions."""

from __future__ import annotations

from pathlib import Path

import click
from rich.table import Table

from nestdx.config.parser import load_config
from nestdx.session.manager import SessionManager
from nestdx.utils.console import STATUS_COLORS, console, format_duration


@click.command()
@click.option("--limit", "-n", default=20, help="Number of sessions to show.")
@click.option("--summary", is_flag=True, help="Show summary stats only.")
def sessions_cmd(limit: int, summary: bool):
    """List historical NestDX sessions."""
    project_root = Path.cwd()

    try:
        config = load_config()
    except Exception as e:
        console.print(f"[red]Error:[/red] {e}")
        raise SystemExit(1)

    manager = SessionManager(config, project_root)

    if summary:
        _print_summary_from_store(manager)
        return

    sessions = manager.list_sessions(limit=limit)

    if not sessions:
        console.print("[yellow]No sessions found.[/yellow]")
        return

    # Full table
    table = Table(show_header=True, header_style="bold")
    table.add_column("ID", style="dim")
    table.add_column("Status")
    table.add_column("Started")
    table.add_column("Duration", justify="right")
    table.add_column("Tools", justify="right")
    table.add_column("Files", justify="right")
    table.add_column("Cost", justify="right")
    table.add_column("Violations", justify="right")

    for s in sessions:
        status_color = STATUS_COLORS.get(s.status.value, "white")
        errors = sum(1 for v in s.violations if v.severity == "error")
        warnings = sum(1 for v in s.violations if v.severity == "warning")

        if errors:
            viol_str = f"[red]{errors}E[/red] [yellow]{warnings}W[/yellow]"
        elif warnings:
            viol_str = f"[yellow]{warnings}W[/yellow]"
        else:
            viol_str = "[green]clean[/green]"

        cost_str = f"${s.total_cost:.2f}" if s.total_cost > 0 else "-"

        table.add_row(
            s.id,
            f"[{status_color}]{s.status.value}[/{status_color}]",
            f"{s.start_time:%Y-%m-%d %H:%M}",
            format_duration(s.duration_seconds),
            str(len(s.tool_runs)),
            str(len(s.file_changes)),
            cost_str,
            viol_str,
        )

    console.print(table)


def _print_summary_from_store(manager: SessionManager) -> None:
    """Print aggregate stats powered by SQLite."""
    stats = manager.store.aggregate(group_by="status")
    total = stats["total_sessions"]

    if total == 0:
        console.print("[yellow]No sessions found.[/yellow]")
        return

    # Extract per-status counts from groups
    status_counts: dict[str, int] = {}
    for g in stats.get("groups", []):
        status_counts[g["status"]] = g["sessions"]

    completed = status_counts.get("completed", 0)
    aborted = status_counts.get("aborted", 0)
    with_violations = stats["violations_count"]

    console.print(f"[bold]Session Summary ({total} sessions):[/bold]")
    console.print(f"  Completed: [green]{completed}[/green]")
    console.print(f"  Aborted: [red]{aborted}[/red]")
    console.print(f"  With violations: [red]{with_violations}[/red]")
    console.print(f"  Files changed: {stats['file_changes_count']}")
    console.print(f"  Duration: {format_duration(stats['total_duration'])}")
    if stats["total_tokens"] > 0 or stats["total_cost"] > 0:
        console.print(f"  Total tokens: {stats['total_tokens']:,}")
        console.print(f"  Total cost: ${stats['total_cost']:.2f}")
