"""loony skills — list, add, and remove loony-bundled agent skills."""

import shutil
from pathlib import Path

from .types import SkillAction, SkillsResult

TEMPLATES_DIR = Path(__file__).parent / "templates"

# All loony-owned skills (loony- prefix)
BUNDLED_SKILLS = {
    "loony-build-pipeline": "Guide for building a data pipeline from API to queryable views",
    "loony-test-validate": "Test and validate a pipeline — fix type mismatches, schema drift, transform errors",
}


def detect_agent(project_dir: Path) -> str | None:
    """Detect which agent is in use."""
    if (project_dir / ".claude").exists():
        return "claude"
    if (project_dir / ".cursor").exists():
        return "cursor"
    if (project_dir / "AGENTS.md").exists():
        return "codex"
    return None


def get_skills_dir(agent: str, project_dir: Path) -> Path:
    """Get the skills directory for an agent."""
    if agent == "claude":
        return project_dir / ".claude" / "skills"
    elif agent == "cursor":
        return project_dir / ".cursor" / "skills"
    elif agent == "codex":
        return project_dir / ".codex" / "skills"
    raise ValueError(f"Unknown agent: {agent}")


def list_skills(project_dir: Path | None = None) -> SkillsResult:
    """List available and installed skills."""
    project_dir = project_dir or Path.cwd()
    agent = detect_agent(project_dir)

    available: dict[str, str] = {}
    installed: dict[str, str] = {}

    for name, description in BUNDLED_SKILLS.items():
        available[name] = description

    if agent:
        skills_dir = get_skills_dir(agent, project_dir)
        if skills_dir.exists():
            for d in skills_dir.iterdir():
                if d.is_dir() and (d / "SKILL.md").exists():
                    if d.name in BUNDLED_SKILLS:
                        installed[d.name] = "bundled"
                    else:
                        installed[d.name] = "user"

    return {
        "agent": agent,
        "available": available,
        "installed": installed,
    }


def add_skill(name: str, agent: str | None = None, project_dir: Path | None = None) -> SkillAction:
    """Add a bundled skill to the project."""
    project_dir = project_dir or Path.cwd()
    agent = agent or detect_agent(project_dir)

    if not agent:
        raise ValueError("No agent detected. Run 'loony init' first or specify --agent.")

    if name not in BUNDLED_SKILLS:
        available = ", ".join(BUNDLED_SKILLS.keys())
        raise ValueError(f"Unknown skill '{name}'. Available: {available}")

    # Source skill from bundled templates
    if agent == "claude":
        src = TEMPLATES_DIR / "claude" / "skills" / name
    else:
        # For cursor/codex, use claude skills as source (same SKILL.md format)
        src = TEMPLATES_DIR / "claude" / "skills" / name

    if not src.exists():
        raise ValueError(f"Skill template not found for '{name}'")

    dest = get_skills_dir(agent, project_dir) / name
    dest.parent.mkdir(parents=True, exist_ok=True)

    if dest.exists():
        shutil.rmtree(dest)
        action = "updated"
    else:
        action = "added"

    shutil.copytree(src, dest)

    return {"name": name, "action": action, "path": str(dest.relative_to(project_dir))}


def remove_skill(name: str, project_dir: Path | None = None) -> SkillAction:
    """Remove a skill from the project."""
    project_dir = project_dir or Path.cwd()
    agent = detect_agent(project_dir)

    if not agent:
        raise ValueError("No agent detected.")

    dest = get_skills_dir(agent, project_dir) / name

    if not dest.exists():
        raise ValueError(f"Skill '{name}' is not installed.")

    shutil.rmtree(dest)

    return {"name": name, "action": "removed", "path": str(dest.relative_to(project_dir))}
