import os
from pathlib import Path
from typing import List, Optional

from pygeai.skills.models import Agent


class AgentDetector:
    """Detects installed AI coding agents."""

    AGENTS_CONFIG = {
        "opencode": {"project": ".opencode/skill", "global": "~/.config/opencode/skill"},
        "claude-code": {"project": ".claude/skills", "global": "~/.claude/skills"},
        "codex": {"project": ".codex/skills", "global": "~/.codex/skills"},
        "cursor": {"project": ".cursor/skills", "global": "~/.cursor/skills"},
        "coda-cli": {"project": ".coda/skills", "global": "~/.coda/skills"},
    }

    def detect_all(self) -> List[Agent]:
        """Detect all installed coding agents."""
        detected = []

        for agent_name, paths in self.AGENTS_CONFIG.items():
            if self.is_installed(agent_name):
                agent = Agent(
                    name=agent_name,
                    project_skills_dir=Path(paths["project"]),
                    global_skills_dir=Path(os.path.expanduser(paths["global"])),
                )
                detected.append(agent)

        return detected

    def is_installed(self, agent_name: str) -> bool:
        """Check if agent is installed/configured."""
        if agent_name in self.AGENTS_CONFIG:
            global_path = Path(
                os.path.expanduser(self.AGENTS_CONFIG[agent_name]["global"])
            )
            if global_path.exists():
                return True

        return False

    def get_agent(self, agent_name: str) -> Optional[Agent]:
        """Get specific agent configuration."""
        if agent_name in self.AGENTS_CONFIG:
            paths = self.AGENTS_CONFIG[agent_name]
            return Agent(
                name=agent_name,
                project_skills_dir=Path(paths["project"]),
                global_skills_dir=Path(os.path.expanduser(paths["global"])),
            )
        return None

    def list_supported_agents(self) -> List[str]:
        """List all supported agent names."""
        return list(self.AGENTS_CONFIG.keys())
