"""Helpers for scanning Claude slash commands from command folders."""

from pathlib import Path


def _extract_command_description(content: str, command_name: str) -> str:
    """Extract the best available description from command markdown."""
    description = ""
    lines = content.split("\n")

    # Check for YAML-style front matter.
    if lines and lines[0].strip() == "---":
        end_index = None
        for idx in range(1, len(lines)):
            if lines[idx].strip() == "---":
                end_index = idx
                break

        if end_index:
            for front_line in lines[1:end_index]:
                parts = front_line.split(":", 1)
                if len(parts) != 2:
                    continue
                key, value = parts[0].strip().lower(), parts[1].strip()
                if key == "description" and value:
                    description = value.strip("'\" ")
                    break

    # Fallback to first non-empty content or heading line.
    if not description:
        for line in lines:
            stripped = line.strip()
            if not stripped:
                continue
            if stripped.startswith("#"):
                description = stripped.lstrip("#").strip()
            else:
                description = stripped
            break

    if not description:
        description = f"Custom command: {command_name}"

    return description


def _scan_commands_dir(commands_dir: Path) -> dict:
    """Scan one commands directory and return command metadata."""
    commands = {}
    if not commands_dir.exists():
        return commands

    for file_path in sorted(commands_dir.rglob("*.md")):
        if not file_path.is_file():
            continue

        rel_path = file_path.relative_to(commands_dir)
        command_parts = list(rel_path.parts[:-1]) + [file_path.stem]
        command_name = ":".join(command_parts)
        try:
            with open(file_path, "r", encoding="utf-8") as f:
                content = f.read()

            description = _extract_command_description(content, command_name)
            commands[command_name] = {"description": description}
        except Exception as e:
            print(f"Warning: Could not read command file {file_path}: {e}")

    return commands


def _scan_skills_dir(skills_dir: Path) -> dict:
    """Scan one skills directory and return skill metadata keyed as slash commands."""
    skills = {}
    if not skills_dir.exists():
        return skills

    for skill_file in sorted(skills_dir.rglob("SKILL.md")):
        if not skill_file.is_file():
            continue

        rel_skill_dir = skill_file.parent.relative_to(skills_dir)
        skill_name = ":".join(rel_skill_dir.parts)
        if not skill_name:
            continue

        try:
            with open(skill_file, "r", encoding="utf-8") as f:
                content = f.read()

            description = _extract_command_description(content, skill_name)
            skills[skill_name] = {"description": description}
        except Exception as e:
            print(f"Warning: Could not read skill file {skill_file}: {e}")

    return skills


def scan_claude_commands(agent_type: str = "claude") -> dict:
    """Scan Claude command directories for custom user slash commands.

    Args:
        agent_type: Agent type ('claude', 'codex', or 'opencode')

    Returns:
        Dict of commands {command_name: {description: ...}}
    """
    _ = agent_type  # Reserved for future per-agent command source behavior.

    commands = {}
    claude_roots = [
        Path.home() / ".claude",
        Path.cwd() / ".claude",
    ]
    for claude_root in claude_roots:
        if not claude_root.exists():
            continue

        scanned_commands = _scan_commands_dir(claude_root / "commands")
        # Local ./.claude commands overwrite same-named global commands.
        commands.update(scanned_commands)

        # Scan skills as slash commands as well.
        # Example: .claude/skills/foo/SKILL.md -> /foo
        # Nested skills are represented with ':' separators for parity with commands.
        scanned_skills = _scan_skills_dir(claude_root / "skills")
        # Keep explicit commands authoritative when names collide.
        for skill_name, skill_metadata in scanned_skills.items():
            if skill_name in commands:
                continue
            commands[skill_name] = skill_metadata

    return commands
