"""
Agent CLI Commands

Provides CLI integration for agent management.
"""

from pathlib import Path
from typing import Optional

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

from groknroll.agents import AgentManager

console = Console()


@click.group()
def agent():
    """Manage groknroll agents"""
    pass


@agent.command("list")
@click.option("--path", type=click.Path(exists=True), help="Project path")
def list_agents(path: Optional[str]):
    """List all available agents"""
    project_path = Path(path) if path else Path.cwd()

    try:
        manager = AgentManager(project_path=project_path)
        agents = manager.list_agents()

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

        # Display agents in table
        table = Table(title="Available Agents", show_header=True)
        table.add_column("Name", style="cyan")
        table.add_column("Description", style="white")
        table.add_column("Capabilities", style="green")
        table.add_column("Active", style="magenta")

        for agent_info in agents:
            active_indicator = "✓" if agent_info.is_active else ""
            capabilities_str = ", ".join(agent_info.capabilities)
            table.add_row(
                agent_info.name, agent_info.description, capabilities_str, active_indicator
            )

        console.print()
        console.print(table)

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")


@agent.command("switch")
@click.argument("agent_name")
@click.option("--path", type=click.Path(exists=True), help="Project path")
def switch_agent(agent_name: str, path: Optional[str]):
    """Switch to a different agent"""
    project_path = Path(path) if path else Path.cwd()

    try:
        manager = AgentManager(project_path=project_path)

        if manager.switch(agent_name):
            console.print(
                f"[bold green]✓ Switched to agent:[/bold green] [cyan]{agent_name}[/cyan]"
            )
        else:
            console.print(
                f"[bold red]Error:[/bold red] Agent '{agent_name}' not found\n"
                f"[dim]Use 'groknroll agent list' to see available agents[/dim]"
            )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")


@agent.command("info")
@click.argument("agent_name", required=False)
@click.option("--path", type=click.Path(exists=True), help="Project path")
def agent_info(agent_name: Optional[str], path: Optional[str]):
    """Show agent information"""
    project_path = Path(path) if path else Path.cwd()

    try:
        manager = AgentManager(project_path=project_path)

        # If no agent specified, show current agent
        if not agent_name:
            agent_name = manager.current_agent_name

        agent = manager.get_agent(agent_name)

        if not agent:
            console.print(f"[bold red]Error:[/bold red] Agent '{agent_name}' not found")
            return

        # Display agent info
        stats = agent.get_stats()
        caps = agent.get_capabilities()

        console.print()
        console.print(
            Panel.fit(
                f"[bold cyan]Agent:[/bold cyan] {stats['name']}\n"
                f"[cyan]Description:[/cyan] {stats['description']}\n"
                f"[cyan]Capabilities:[/cyan] {', '.join(caps)}\n"
                f"[cyan]Total Executions:[/cyan] {stats['total_executions']}\n"
                f"[cyan]Successful:[/cyan] {stats['successful_executions']}\n"
                f"[cyan]Failed:[/cyan] {stats['failed_executions']}",
                title=f"[bold]{agent_name}[/bold]",
                border_style="cyan",
            )
        )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")


@agent.command("reload")
@click.option("--path", type=click.Path(exists=True), help="Project path")
def reload_agents(path: Optional[str]):
    """Reload custom agents from configuration"""
    project_path = Path(path) if path else Path.cwd()

    try:
        manager = AgentManager(project_path=project_path)
        loaded = manager.reload_custom_agents()

        if loaded:
            console.print(f"[bold green]✓ Reloaded {len(loaded)} custom agent(s)[/bold green]")
            for name in loaded.keys():
                console.print(f"  - [cyan]{name}[/cyan]")
        else:
            console.print("[yellow]No custom agents found[/yellow]")
            console.print(
                "\n[dim]Create custom agents in:[/dim]\n"
                "  - groknroll.json (agent section)\n"
                "  - .groknroll/agent/<name>.md"
            )

    except Exception as e:
        console.print(f"[bold red]Error:[/bold red] {e}")


def add_agent_option(command_func):
    """
    Decorator to add --agent option to commands

    Example:
        @click.command()
        @add_agent_option
        def chat(message, agent, path):
            ...
    """
    return click.option(
        "--agent",
        default="build",
        help="Agent to use (build/plan/custom)",
        show_default=True,
    )(command_func)
