"""Agent commands for manta-client CLI."""

from __future__ import annotations

import asyncio
from typing import Any

import typer

from manta_client.api.agent.agent import get_agent_api
from manta_client.api.client import APIError
from manta_client.output import (
    console,
    print_error,
    print_json,
    print_key_value,
    print_success,
    print_table,
)

app = typer.Typer(help="Agent management")


@app.command("list")
def list_agents(
    json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
) -> None:
    """List all available agents."""

    async def _list():
        api = get_agent_api()
        return await api.list_agents()

    try:
        result = asyncio.run(_list())
    except APIError as e:
        print_error(e.message)
        raise typer.Exit(1) from None

    agents = result.get("agents", [])
    total = result.get("total", 0)

    if json_output:
        print_json(result)
        return

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

    columns = [
        ("name", "Name"),
        ("display_name", "Display Name"),
        ("type", "Type"),
        ("status", "Status"),
        ("version", "Version"),
    ]

    # Format status with colors
    for agent in agents:
        status = agent.get("status", "")
        if status == "available":
            agent["status"] = "[green]available[/green]"
        elif status == "disabled":
            agent["status"] = "[red]disabled[/red]"
        elif status == "deprecated":
            agent["status"] = "[yellow]deprecated[/yellow]"

    print_table(agents, columns=columns, title=f"Agents ({total})")


@app.command("info")
def agent_info(
    name: str = typer.Argument(..., help="Agent name"),
    json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
) -> None:
    """Show agent details."""

    async def _get_info():
        api = get_agent_api()
        return await api.get_agent(name)

    try:
        agent = asyncio.run(_get_info())
    except APIError as e:
        print_error(e.message)
        raise typer.Exit(1) from None

    if json_output:
        print_json(agent)
        return

    # Format for display
    data: dict[str, Any] = {
        "Name": agent.get("name"),
        "Display Name": agent.get("display_name"),
        "Description": agent.get("description"),
        "Type": agent.get("type"),
        "Status": agent.get("status"),
        "Version": agent.get("version"),
    }

    if agent.get("created_at"):
        data["Created At"] = agent["created_at"]

    print_key_value(data, title=f"Agent: {name}")

    # Show input schema if available
    input_schema = agent.get("input_schema")
    if input_schema:
        console.print("\n[bold]Input Schema:[/bold]")
        print_json(input_schema)


@app.command("run")
def run_agent(
    name: str = typer.Argument(..., help="Agent name"),
    message: str = typer.Option(
        "",
        "--message",
        "-m",
        help="Prompt message for the agent",
    ),
    input_json: str = typer.Option(
        None,
        "--input",
        "-i",
        help="Input data as JSON string",
    ),
    json_output: bool = typer.Option(False, "--json", "-j", help="Output as JSON"),
) -> None:
    """Execute an agent synchronously.

    This command runs the agent and waits for completion.
    For long-running jobs, consider using 'agent job create' instead.
    """
    import json as json_lib

    # Parse input JSON if provided
    input_data = {}
    if input_json:
        try:
            input_data = json_lib.loads(input_json)
        except json_lib.JSONDecodeError as e:
            print_error(f"Invalid JSON input: {e}")
            raise typer.Exit(1) from None

    if message:
        input_data["prompt"] = message

    async def _execute():
        api = get_agent_api()
        return await api.execute_agent(name, input_data=input_data)

    console.print(f"[cyan]Executing agent '{name}'...[/cyan]")

    try:
        result = asyncio.run(_execute())
    except APIError as e:
        print_error(e.message)
        raise typer.Exit(1) from None

    if json_output:
        print_json(result)
        return

    success = result.get("success", False)
    output = result.get("output", "")
    error = result.get("error")
    artifacts = result.get("artifacts", {})

    if success:
        print_success("Agent execution completed successfully!")
    else:
        console.print("[red]Agent execution failed.[/red]")

    if output:
        console.print("\n[bold]Output:[/bold]")
        console.print(output)

    if error:
        console.print(f"\n[red]Error: {error}[/red]")

    if artifacts:
        console.print("\n[bold]Artifacts:[/bold]")
        print_json(artifacts)
