"""Skill installer — copy SKILL.md + references/ to AI-tool skill directories."""

from __future__ import annotations

import shutil
from pathlib import Path

import click
from rich.console import Console
from rich.table import Table

console = Console()

TOOL_CONFIGS = {
    "claude-code": {
        "user": Path.home() / ".claude" / "skills" / "gsearch-mcp",
        "project": Path(".claude/skills/gsearch-mcp"),
        "description": "Claude Code CLI and Desktop",
    },
    "cursor": {
        "user": Path.home() / ".cursor" / "skills" / "gsearch-mcp",
        "project": Path(".cursor/skills/gsearch-mcp"),
        "description": "Cursor AI editor",
    },
    "agents": {
        "user": Path.home() / ".agents" / "skills" / "gsearch-mcp",
        "project": Path(".agents/skills/gsearch-mcp"),
        "description": "Generic agent skill (Gemini CLI, Codex, and others)",
    },
    "codex": {
        "user": Path.home() / ".agents" / "skills" / "gsearch-mcp",
        "project": Path(".agents/skills/gsearch-mcp"),
        "description": "OpenAI Codex CLI agent",
    },
    "gemini-cli": {
        "user": Path.home() / ".agents" / "skills" / "gsearch-mcp",
        "project": Path(".agents/skills/gsearch-mcp"),
        "description": "Google Gemini CLI",
    },
    "opencode": {
        "user": Path.home() / ".config" / "opencode" / "skills" / "gsearch-mcp",
        "project": Path(".opencode/skills/gsearch-mcp"),
        "description": "OpenCode AI assistant",
    },
    "antigravity": {
        "user": Path.home() / ".gemini" / "antigravity" / "skills" / "gsearch-mcp",
        "project": Path(".agents/skills/gsearch-mcp"),
        "description": "Google Antigravity AI IDE",
    },
    "cline": {
        "user": Path.home() / ".cline" / "skills" / "gsearch-mcp",
        "project": Path(".cline/skills/gsearch-mcp"),
        "description": "Cline CLI terminal agent",
    },
    "openclaw": {
        "user": Path.home() / ".openclaw" / "workspace" / "skills" / "gsearch-mcp",
        "project": Path(".openclaw/workspace/skills/gsearch-mcp"),
        "description": "OpenClaw AI agent framework",
    },
    "cc-claw": {
        "user": Path.home() / ".cc-claw" / "workspace" / "skills" / "gsearch-mcp",
        "project": Path(".cc-claw/workspace/skills/gsearch-mcp"),
        "description": "CC-Claw AI agent framework",
    },
    "other": {
        "project": Path("./gsearch-mcp-skill-export"),
        "description": "Export all formats for manual installation",
    },
}


def _data_dir() -> Path:
    return Path(__file__).resolve().parent.parent / "data"


def _is_installed(tool_id: str) -> bool:
    cfg = TOOL_CONFIGS[tool_id]
    user_path = cfg.get("user")
    if user_path and (user_path / "SKILL.md").is_file():
        return True
    return False


def _install_to(target: Path) -> None:
    data = _data_dir()
    target.mkdir(parents=True, exist_ok=True)

    shutil.copy2(data / "SKILL.md", target / "SKILL.md")

    refs_src = data / "references"
    if refs_src.is_dir():
        refs_dst = target / "references"
        if refs_dst.exists():
            shutil.rmtree(refs_dst)
        shutil.copytree(refs_src, refs_dst)


@click.group("skill")
def skill_cmd():
    """Manage gsearch skill installation for AI tools."""


@skill_cmd.command("list")
def skill_list():
    """Show available install targets and their status."""
    table = Table(title="Skill Install Targets")
    table.add_column("Tool", style="bold")
    table.add_column("Status")
    table.add_column("Path", style="dim")
    table.add_column("Description", style="dim")

    for tool_id, cfg in TOOL_CONFIGS.items():
        if tool_id == "other":
            table.add_row(tool_id, "-", str(cfg.get("project", "")), cfg["description"])
            continue
        installed = _is_installed(tool_id)
        status = "[green]installed[/green]" if installed else "[dim]not installed[/dim]"
        user_path = cfg.get("user", "")
        table.add_row(tool_id, status, str(user_path), cfg["description"])

    console.print(table)


@skill_cmd.command("install")
@click.argument("target", type=click.Choice(list(TOOL_CONFIGS.keys())))
@click.option("--project", is_flag=True, help="Install to project-local path instead of user path.")
def skill_install(target: str, project: bool) -> None:
    """Install gsearch skill to TARGET tool directory."""
    cfg = TOOL_CONFIGS[target]

    if project:
        install_path = cfg.get("project")
        if not install_path:
            console.print(f"[red]No project path defined for {target}[/red]")
            raise SystemExit(1)
    else:
        install_path = cfg.get("user")
        if not install_path:
            install_path = cfg.get("project")

    _install_to(install_path)
    console.print(f"[green]Installed gsearch skill to {install_path}[/green]")


@skill_cmd.command("update")
def skill_update():
    """Update all installed skills with the latest version."""
    updated = []
    for tool_id, cfg in TOOL_CONFIGS.items():
        if tool_id == "other":
            continue
        if _is_installed(tool_id):
            _install_to(cfg["user"])
            updated.append(tool_id)
            console.print(f"  [green]Updated[/green] {tool_id} at {cfg['user']}")
    if not updated:
        console.print("[dim]No installed skills found. Run 'gsearch skill install <target>' first.[/dim]")
