from __future__ import annotations

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

from leshy.cli.app import app
from leshy.core.registry import (
    attack_registry,
    buff_registry,
    evaluator_registry,
    logger_registry,
    target_registry,
)

console = Console()


@app.command("list")
def list_plugins(
    plugin_type: str = typer.Argument(
        ...,
        help="Plugin type to list: attacks, targets, evaluators, loggers, or buffs",
    ),
) -> None:
    """List available plugins by type."""
    registries = {
        "attacks": attack_registry,
        "targets": target_registry,
        "evaluators": evaluator_registry,
        "loggers": logger_registry,
        "buffs": buff_registry,
    }

    if plugin_type not in registries:
        typer.echo(
            f"Unknown plugin type: '{plugin_type}'. "
            f"Choose from: {', '.join(registries.keys())}",
            err=True,
        )
        raise typer.Exit(code=2)

    registry = registries[plugin_type]
    items = registry.items()

    if not items:
        typer.echo(f"No {plugin_type} registered.")
        return

    table = Table(title=f"Available {plugin_type.title()}")
    table.add_column("Name", style="bold")
    table.add_column("Description")

    for key, cls in items:
        desc = getattr(cls, "description", "") or getattr(cls, "__doc__", "") or ""
        # Take first line only
        desc = desc.strip().split("\n")[0]
        table.add_row(key, desc)

    console.print(table)
