"""bilge history - List past training runs."""

import json

import typer
from rich.console import Console
from rich.table import Table

from bilgeai.memory.store import ExperimentStore

console = Console()


def history_command(
    limit: int = typer.Option(20, "--limit", "-n", help="Number of runs to show"),
    status: str = typer.Option(None, "--status", "-s", help="Filter by status"),
    model: str = typer.Option(None, "--model", "-m", help="Filter by model name"),
    json_output: bool = typer.Option(False, "--json", help="Output as JSON"),
    compact: bool = typer.Option(False, "--compact", "-c", help="One line per run (table view)"),
) -> None:
    """List past training runs from experiment memory."""
    store = ExperimentStore()
    runs = store.list_runs(limit=limit, status=status, model_name=model)

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

    if json_output:
        data = [json.loads(r.model_dump_json()) for r in runs]
        console.print_json(json.dumps(data, indent=2))
        return

    if compact:
        _render_compact(runs)
    else:
        _render_detailed(runs)


def _render_compact(runs) -> None:
    """Render runs as a compact Rich table."""
    table = Table(title=f"Training Runs ({len(runs)})", show_header=True)
    table.add_column("Run ID", style="cyan", no_wrap=True)
    table.add_column("Status")
    table.add_column("Model", style="green")
    table.add_column("Loss", justify="right")
    table.add_column("Steps", justify="right")
    table.add_column("Time", justify="right")
    table.add_column("Date", style="dim")

    status_colors = {
        "completed": "green",
        "running": "blue",
        "failed": "red",
        "created": "dim",
    }

    for run in runs:
        color = status_colors.get(run.status, "white")
        table.add_row(
            run.run_id[:12],
            f"[{color}]{run.status}[/{color}]",
            run.model_name,
            f"{run.best_loss:.4f}" if run.best_loss is not None else "-",
            str(run.total_steps) if run.total_steps is not None else "-",
            f"{run.training_time_seconds:.0f}s" if run.training_time_seconds is not None else "-",
            run.timestamp[:16],
        )

    console.print(table)


def _render_detailed(runs) -> None:
    """Render runs in detailed multi-line format."""
    console.print(f"\n[bold]Training Runs[/bold] (showing {len(runs)})\n")

    for run in runs:
        status_colors = {
            "completed": "green",
            "running": "blue",
            "failed": "red",
            "created": "dim",
        }
        color = status_colors.get(run.status, "white")

        # Build concise one-line summary
        loss_str = f"loss={run.best_loss:.4f}" if run.best_loss is not None else ""
        steps_str = f"steps={run.total_steps}" if run.total_steps is not None else ""
        time_str = (
            f"{run.training_time_seconds:.0f}s" if run.training_time_seconds is not None else ""
        )
        details = "  ".join(filter(None, [loss_str, steps_str, time_str]))

        console.print(
            f"  [cyan]{run.run_id}[/cyan]  [{color}]{run.status:<9}[/{color}]  "
            f"[green]{run.model_name}[/green]"
        )
        if details:
            console.print(f"    {details}")
        console.print(f"    [dim]{run.timestamp[:19]}[/dim]")
        console.print()
