"""ievo list — show installed agents."""

from __future__ import annotations

import typer
from rich.table import Table

from ievo.core.agent import AgentPackage
from ievo.core.config import AGENTS_DIR, CLAUDE_AGENTS_DIR, require_project
from ievo.core.project import ProjectManifest
from ievo.marketplace import parse_agent_frontmatter
from ievo.utils.console import console, info

MODEL_STYLES = {
    "opus": "red",
    "sonnet": "magenta",
    "haiku": "cyan",
}


def list_agents(
    marketplace: bool = typer.Option(False, "--marketplace", help="Show all available agents."),
) -> None:
    """[DEPRECATED] Show installed agents (or marketplace catalog)."""
    from ievo.utils.deprecation import deprecated_command

    deprecated_command("ievo list", alternative="the TUI dashboard")
    if marketplace:
        _list_marketplace()
        return

    root = require_project()
    manifest = ProjectManifest.load(root)

    if not manifest.agents:
        info("No agents installed. Run: [bold]ievo add spec-writer[/bold]")
        return

    table = Table(show_header=True, header_style="dim", padding=(0, 2))
    table.add_column("Agent", style="bright_white")
    table.add_column("Version", style="dim cyan")
    table.add_column("Model", style="dim")
    table.add_column("Description", style="dim")

    for agent_name, version in manifest.agents.items():
        model = "sonnet"
        description = ""

        # Try new .claude/agents/<name>.md format first
        claude_agent_md = root / CLAUDE_AGENTS_DIR / f"{agent_name}.md"
        if claude_agent_md.exists():
            fm = parse_agent_frontmatter(claude_agent_md)
            model = fm.get("model", "sonnet")
            description = fm.get("description", "")
        else:
            # Legacy fallback
            agent_dir = root / AGENTS_DIR / agent_name
            try:
                pkg = AgentPackage.load(agent_dir)
                model = pkg.model.primary
                description = pkg.description
            except FileNotFoundError:
                pass

        style = MODEL_STYLES.get(model, "white")
        table.add_row(
            agent_name,
            version,
            f"[{style}]{model}[/{style}]",
            description,
        )

    console.print(table)


def _list_marketplace() -> None:
    """Show all agents in the marketplace registry."""
    import asyncio

    from ievo.core.registry import Registry

    async def _fetch() -> Registry:
        reg = Registry.load_cached()
        await reg.fetch()
        return reg

    registry = asyncio.run(_fetch())
    entries = registry.list_all()

    # Bundled fallback if fetch returned nothing
    if not entries:
        from ievo.marketplace import load_bundled_registry

        bundled = load_bundled_registry()
        if bundled and bundled.get("agents"):
            from ievo.core.registry import RegistryEntry

            entries = [
                RegistryEntry(
                    name=a["name"],
                    version=a.get("version", "0.1.0"),
                    description=a.get("description", ""),
                    model=a.get("model", "sonnet"),
                    dependencies=a.get("dependencies", []),
                    category=a.get("category", "core"),
                )
                for a in bundled["agents"]
            ]

    if not entries:
        info("Marketplace registry is empty or unreachable.")
        return

    table = Table(show_header=True, header_style="dim", padding=(0, 2))
    table.add_column("Agent", style="bright_white")
    table.add_column("Version", style="dim cyan")
    table.add_column("Model", style="dim")
    table.add_column("Category", style="dim")
    table.add_column("Description", style="dim")

    for entry in entries:
        style = MODEL_STYLES.get(entry.model, "white")
        table.add_row(
            entry.name,
            entry.version,
            f"[{style}]{entry.model}[/{style}]",
            entry.category,
            entry.description,
        )

    console.print(table)
