"""ievo deps — manage agent plugin and MCP dependencies."""

from __future__ import annotations

import typer

from ievo.core.agent import AgentPackage
from ievo.core.config import AGENTS_DIR, require_project
from ievo.core.deps import (
    McpType,
    check_mcp_deps,
    check_plugin_deps,
    ensure_mcp_configured,
)
from ievo.core.project import ProjectManifest
from ievo.utils.console import info, step, success, warn

app = typer.Typer(no_args_is_help=True)


@app.command(name="check")
def check(
    agent: str | None = typer.Argument(default=None, help="Agent name (all if omitted)."),
) -> None:
    """Check if agent dependencies (MCP servers, plugins) are satisfied."""
    root = require_project()
    manifest = ProjectManifest.load(root)

    agents_to_check = [agent] if agent else list(manifest.agents.keys())

    all_ok = True
    for agent_name in agents_to_check:
        agent_dir = root / AGENTS_DIR / agent_name
        try:
            pkg = AgentPackage.load(agent_dir)
        except FileNotFoundError:
            warn(f"{agent_name}: agent.yaml not found, skipping")
            continue

        info(f"[bold]{agent_name}[/bold]")

        mcp_results = check_mcp_deps(root, pkg.mcp)
        plugin_results = check_plugin_deps(pkg.plugins)

        for r in mcp_results:
            if r.satisfied:
                step(f"[success]✓[/success] {r.name} — {r.message}")
            else:
                all_ok = False
                fix = f" [dim]({r.fix_command})[/dim]" if r.fix_command else ""
                step(f"[error]✗[/error] {r.name} — {r.message}{fix}")

        for r in plugin_results:
            marker = "[warn]?[/warn]" if not r.satisfied else "[success]✓[/success]"
            fix = f" [dim]({r.fix_command})[/dim]" if r.fix_command else ""
            step(f"{marker} {r.name} [dim](plugin)[/dim] — {r.message}{fix}")

    if all_ok:
        success("All dependencies satisfied.")
    else:
        warn("Some dependencies need attention. Run: ievo deps install")


@app.command(name="install")
def install(
    agent: str | None = typer.Argument(default=None, help="Agent name (all if omitted)."),
) -> None:
    """Configure MCP servers in .mcp.json and show plugin install instructions."""
    root = require_project()
    manifest = ProjectManifest.load(root)

    agents_to_install = [agent] if agent else list(manifest.agents.keys())

    all_plugins: list[tuple[str, str]] = []  # (name, marketplace)
    all_marketplaces: set[str] = set()

    for agent_name in agents_to_install:
        agent_dir = root / AGENTS_DIR / agent_name
        try:
            pkg = AgentPackage.load(agent_dir)
        except FileNotFoundError:
            warn(f"{agent_name}: agent.yaml not found, skipping")
            continue

        # Auto-configure MCP servers
        if pkg.mcp:
            warnings = ensure_mcp_configured(root, pkg.mcp)
            non_builtin = [m for m in pkg.mcp if m.type != McpType.BUILTIN]
            if non_builtin:
                info(f"[bold]{agent_name}[/bold] — MCP servers configured in .mcp.json")
            for w in warnings:
                warn(w)

        # Collect plugin instructions
        for plugin in pkg.plugins:
            all_plugins.append((plugin.name, plugin.marketplace))
            if plugin.marketplace != "claude-plugins-official":
                all_marketplaces.add(plugin.marketplace)

    if all_plugins:
        info("Plugin installation (run in Claude Code):")
        for marketplace in sorted(all_marketplaces):
            step(f"/plugin marketplace add {marketplace}")
        for name, _marketplace in all_plugins:
            step(f"/plugin install {name}")
    else:
        success("No plugin dependencies to install.")


@app.command(name="status")
def status() -> None:
    """Overview of dependency status for all installed agents."""
    root = require_project()
    manifest = ProjectManifest.load(root)

    if not manifest.agents:
        info("No agents installed.")
        return

    for agent_name in manifest.agents:
        agent_dir = root / AGENTS_DIR / agent_name
        try:
            pkg = AgentPackage.load(agent_dir)
        except FileNotFoundError:
            step(f"[bold]{agent_name}[/bold]  [dim]no agent.yaml[/dim]")
            continue

        mcp_count = len(pkg.mcp)
        plugin_count = len(pkg.plugins)
        non_builtin = sum(1 for m in pkg.mcp if m.type != McpType.BUILTIN)

        info(
            f"[bold]{agent_name}[/bold]  "
            f"mcp: {mcp_count} ({non_builtin} external)  "
            f"plugins: {plugin_count}"
        )
