"""abreka status — project summary."""

from __future__ import annotations

from collections import Counter

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

from abreka.config import find_abreka_dir, load_config, load_index
from abreka.metrics import parse_metric_ref
from abreka.run_control import stop_after_current_requested


@click.command("status")
def status_cmd():
    """Show project summary: experiment counts and best result."""
    abreka_dir = find_abreka_dir()
    config = load_config(abreka_dir)
    index = load_index(abreka_dir)
    stop_requested = stop_after_current_requested(abreka_dir)

    console = Console()

    if not index:
        console.print(f"[bold]{config.project.name}[/bold] — no experiments yet.")
        if stop_requested:
            console.print(
                "[bold yellow]Graceful stop queued[/bold yellow] — "
                "ABREKA will stop after the current experiment completes."
            )
        console.print("Run [bold]abreka propose[/bold] to get started.")
        return

    # Count by status
    status_counts = Counter(e["status"] for e in index.values())

    console.print(f"\n[bold]{config.project.name}[/bold]")
    if stop_requested:
        console.print(
            "  [bold yellow]Graceful stop queued[/bold yellow] — "
            "ABREKA will stop after the current experiment completes."
        )
    console.print(f"  Experiments: {len(index)} total", end="")
    parts = []
    for s in ("completed", "running", "proposed", "failed"):
        if status_counts.get(s):
            parts.append(f"{status_counts[s]} {s}")
    if parts:
        console.print(f" ({', '.join(parts)})")
    else:
        console.print()

    # Find best experiment by primary metric
    split, key = parse_metric_ref(config.experiment.primary_metric)
    maximize = config.experiment.metric_direction == "maximize"

    best_id = None
    best_val = None
    for eid, entry in index.items():
        metrics = entry.get("metrics", {})
        val = metrics.get(split, {}).get(key)
        if val is not None:
            if best_val is None or (maximize and val > best_val) or (not maximize and val < best_val):
                best_val = val
                best_id = eid

    if best_id:
        console.print(f"  Best: [bold green]{best_id}[/bold green] — {split}:{key} = {best_val}")
    console.print()
