from pygeai.cli.commands import Option
from pygeai.core.common.exceptions import MissingRequirementException
from pygeai.core.utils.console import Console
from pygeai.skills import SkillsEngine


def install_skill(option_list: list = None):
    """Install a specific skill to coding agent(s)."""
    opts = {opt.name: arg for opt, arg in option_list} if option_list else {}

    skill_name = opts.get("skill")
    if not skill_name:
        raise MissingRequirementException("Skill name is required. Use --skill <name>")

    engine = SkillsEngine()
    skill = engine.get_skill(skill_name)

    if not skill:
        Console.write_error(f"Skill '{skill_name}' not found")
        return

    agent_names = opts.get("agent", "").split(",") if "agent" in opts else []
    global_install = "global" in opts

    if not agent_names:
        agents = engine.detect_agents()
        if not agents:
            Console.write_error(
                "No agents detected. Use --agent to specify agents explicitly."
            )
            return
    else:
        agents = []
        for name in agent_names:
            agent = engine.detector.get_agent(name.strip())
            if agent:
                agents.append(agent)
            else:
                Console.write_warning(f"Unknown agent '{name}', skipping")

    if not agents:
        Console.write_error("No valid agents to install to")
        return

    Console.write_stdout(f"Installing {skill.name}...")
    results = engine.install_skill(skill, agents, global_install)

    for agent_name, success in results.items():
        if success:
            Console.write_success(f"  ✓ {agent_name}")
        else:
            Console.write_error(f"  ✗ {agent_name} (failed)")

    Console.write_success("\n✓ Installation complete")


install_options = [
    Option("skill", ["--skill", "-s"], "Skill name to install", True),
    Option(
        "agent",
        ["--agent", "-a"],
        "Target agent(s) (comma-separated)",
        True,
    ),
    Option(
        "global",
        ["--global", "-g"],
        "Install globally (default: project-level)",
        False,
    ),
]
