"""Skill installer — detects, copies, and prompts for agent skill installation."""

import shutil
from pathlib import Path

from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt

BUNDLED_DIR = Path(__file__).parent / "bundled_skills"

SKILLS = [
    {"name": "openspec", "label": "OpenSpec", "desc": "spec-driven change workflow"},
    {"name": "beads", "label": "Beads", "desc": "task graph & agent memory"},
]

CONFIG_DIR = Path.home() / ".config" / "hangar"
NO_PROMPT_MARKER = CONFIG_DIR / "no-prompt"

console = Console()


def detect_skills(project_path: Path) -> dict[str, bool]:
    """Check which skills are installed in the project."""
    return {
        s["name"]: (project_path / ".claude" / "skills" / s["name"] / "SKILL.md").is_file()
        for s in SKILLS
    }


def install_skills(target: Path) -> int:
    """Copy bundled skills into target/.claude/skills/. Returns count installed."""
    count = 0
    for skill in SKILLS:
        src = BUNDLED_DIR / skill["name"] / "SKILL.md"
        dst = target / ".claude" / "skills" / skill["name"] / "SKILL.md"
        dst.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(src, dst)
        console.print(f"    .claude/skills/{skill['name']}/SKILL.md", end="")
        console.print("  [green]✓[/green]")
        count += 1
    return count


def set_no_prompt() -> None:
    """Write the no-prompt marker so the wizard never runs again."""
    CONFIG_DIR.mkdir(parents=True, exist_ok=True)
    NO_PROMPT_MARKER.touch()


def should_prompt() -> bool:
    """Check if the wizard should run (no marker file exists)."""
    return not NO_PROMPT_MARKER.exists()


def run_wizard(project_path: Path) -> None:
    """Interactive wizard for first-run skill installation."""
    status = detect_skills(project_path)

    if all(status.values()):
        # All skills present — show status line, no wizard
        parts = []
        for s in SKILLS:
            parts.append(f"[green]✓[/green] {s['name']}")
        console.print(f"  Skills:  {'  '.join(parts)}")
        return

    if not should_prompt():
        return

    # Build the info box
    skill_lines = ""
    for s in SKILLS:
        skill_lines += f"    [cyan]◆[/cyan] [bold]{s['label']}[/bold]  — {s['desc']}\n"

    box_text = (
        "[dim]Agent skills not found in this project.[/dim]\n"
        "\n"
        "Hangar bundles Claude Code skills for:\n"
        f"{skill_lines}"
        "\n"
        "[dim]Skills are installed as .claude/skills/ in your\n"
        "project directory.[/dim]"
    )
    console.print()
    console.print(Panel(box_text, border_style="dim", width=55, padding=(0, 2)))

    short_path = str(project_path).replace(str(Path.home()), "~")
    console.print(f"\n  Project: [bold white]{short_path}[/bold white]\n")

    choices = {
        "1": "Install to this project",
        "2": "Choose a different directory",
        "3": "Skip for now",
        "4": "Skip and don't ask again",
    }

    for k, v in choices.items():
        console.print(f"    [cyan]{k}[/cyan]  {v}")
    console.print()

    choice = Prompt.ask(
        "  [cyan]?[/cyan] Install agent skills",
        choices=list(choices.keys()),
        default="1",
    )

    if choice == "1":
        console.print(f"\n  Installing skills to [bold white]{short_path}[/bold white] ...\n")
        count = install_skills(project_path)
        console.print(f"\n  [green]✔[/green] {count} skills installed\n")

    elif choice == "2":
        raw = Prompt.ask("  [cyan]?[/cyan] Target directory")
        target = Path(raw).expanduser().resolve()
        if not target.is_dir():
            console.print(f"  [red]✗[/red] Directory does not exist: {target}\n")
            return
        target_short = str(target).replace(str(Path.home()), "~")
        console.print(f"\n  Installing skills to [bold white]{target_short}[/bold white] ...\n")
        count = install_skills(target)
        console.print(f"\n  [green]✔[/green] {count} skills installed\n")

    elif choice == "3":
        console.print(
            "\n  Skipped. Run [bold]hangar --install-skills[/bold] anytime to install later.\n"
        )

    elif choice == "4":
        set_no_prompt()
        console.print(
            "\n  Got it. Run [bold]hangar --install-skills[/bold] to install manually.\n"
        )


def install_skills_standalone(target: Path) -> None:
    """Non-interactive skill installation (for --install-skills flag)."""
    short_path = str(target).replace(str(Path.home()), "~")
    console.print(f"\n  Installing skills to [bold white]{short_path}[/bold white] ...\n")
    count = install_skills(target)
    console.print(f"\n  [green]✔[/green] {count} skills installed\n")
