import shutil
from pathlib import Path

from pygeai.skills.models import Agent, Skill


class SkillInstaller:
    """Installs skills to coding agent directories."""

    def install(
        self, skill: Skill, agent: Agent, global_install: bool = False
    ) -> bool:
        """
        Install skill to agent's skills directory.

        Args:
            skill: Skill to install
            agent: Target agent
            global_install: Install globally vs project-level

        Returns:
            True if successful, False otherwise
        """
        if global_install:
            target_base = agent.global_skills_dir
        else:
            target_base = agent.project_skills_dir

        target_dir = target_base / skill.name

        target_dir.mkdir(parents=True, exist_ok=True)

        try:
            shutil.copy2(skill.path / "SKILL.md", target_dir / "SKILL.md")

            for dir_name in ["scripts", "references", "assets"]:
                src_dir = skill.path / dir_name
                if src_dir.exists():
                    dst_dir = target_dir / dir_name
                    if dst_dir.exists():
                        shutil.rmtree(dst_dir)
                    shutil.copytree(src_dir, dst_dir)

            return True
        except Exception as e:
            if target_dir.exists():
                shutil.rmtree(target_dir)
            return False

    def uninstall(self, skill_name: str, agent: Agent, global_install: bool = False) -> bool:
        """
        Uninstall skill from agent's skills directory.

        Args:
            skill_name: Name of skill to uninstall
            agent: Target agent
            global_install: Uninstall from global vs project-level

        Returns:
            True if successful, False otherwise
        """
        if global_install:
            target_base = agent.global_skills_dir
        else:
            target_base = agent.project_skills_dir

        target_dir = target_base / skill_name

        if not target_dir.exists():
            return False

        try:
            shutil.rmtree(target_dir)
            return True
        except Exception:
            return False
