"""ievo remove — uninstall an agent."""

from __future__ import annotations

import shutil

import typer

from ievo.core.config import AGENTS_DIR, CLAUDE_AGENTS_DIR, require_project
from ievo.core.project import ProjectManifest
from ievo.utils.console import error, info, success, warn


def remove(
    agent: str = typer.Argument(help="Agent name to remove."),
    force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation."),
) -> None:
    """[DEPRECATED] Remove an installed agent and its data."""
    from ievo.utils.deprecation import deprecated_command

    deprecated_command("ievo remove", alternative="the HR agent")
    root = require_project()
    manifest = ProjectManifest.load(root)

    if not manifest.has_agent(agent):
        error(f"Agent [bold]{agent}[/bold] is not installed.")
        raise typer.Exit(1)

    agent_dir = root / AGENTS_DIR / agent

    # Check if other agents depend on this one
    for other_name in manifest.agents:
        if other_name == agent:
            continue
        other_dir = root / AGENTS_DIR / other_name / "agent.yaml"
        if other_dir.exists():
            import yaml

            data = yaml.safe_load(other_dir.read_text()) or {}
            deps = data.get("dependencies", [])
            for dep in deps:
                if dep.split("@")[0] == agent:
                    warn(f"[bold]{other_name}[/bold] depends on {agent}.")
                    if not force:
                        error("Use --force to remove anyway.")
                        raise typer.Exit(1)

    if not force:
        confirm = typer.confirm(f"Remove {agent} and all its data?")
        if not confirm:
            info("Cancelled.")
            raise typer.Exit(0)

    # Remove files — both legacy directory and new .md format
    if agent_dir.exists():
        shutil.rmtree(agent_dir)

    claude_agent_md = root / CLAUDE_AGENTS_DIR / f"{agent}.md"
    if claude_agent_md.exists():
        claude_agent_md.unlink()

    manifest.remove_agent(agent)
    manifest.save(root)

    success(f"Removed [bold]{agent}[/bold].")
