"""``sfc skills doctor`` — validate skill files and check for issues."""

from __future__ import annotations

import sys

from launcher.skills._scanner import _read_text_safe, find_skills_dir, parse_frontmatter


def run_doctor() -> None:
    """Check skill health and report issues."""
    skills_dir = find_skills_dir()

    if not skills_dir.is_dir():
        print("No .claude/skills/ directory found.")
        print("Run 'sfc skills init' to set up your project.")
        return

    issues: list[str] = []
    checked = 0

    for skill_dir in sorted(skills_dir.iterdir()):
        if not skill_dir.is_dir():
            continue

        checked += 1
        skill_file = skill_dir / "SKILL.md"

        if not skill_file.is_file():
            issues.append(f"  {skill_dir.name}: Missing SKILL.md")
            continue

        content = _read_text_safe(skill_file)
        if content is None:
            issues.append(f"  {skill_dir.name}: Could not read SKILL.md (encoding or permission issue)")
            continue

        meta = parse_frontmatter(content)

        if not meta.get("name"):
            issues.append(f"  {skill_dir.name}: Missing 'name' in frontmatter")
        if not meta.get("description"):
            issues.append(f"  {skill_dir.name}: Missing 'description' in frontmatter")
        elif len(meta["description"]) < 20:
            issues.append(f"  {skill_dir.name}: Description too short (should contain trigger conditions)")
        if not meta.get("version"):
            issues.append(f"  {skill_dir.name}: Missing 'version' in frontmatter")

    if checked == 0:
        print("No skills found in .claude/skills/")
        print("Run 'sfc skills create <name>' to create one.")
        return

    if issues:
        try:
            from rich.console import Console

            console = Console()
            console.print(f"[yellow]Found {len(issues)} issue(s) across {checked} skill(s):[/yellow]")
            for issue in issues:
                console.print(f"[red]{issue}[/red]")
        except ImportError:
            print(f"Found {len(issues)} issue(s) across {checked} skill(s):")
            for issue in issues:
                print(issue)
        sys.exit(1)
    else:
        try:
            from rich.console import Console

            console = Console()
            console.print(f"[green]All {checked} skill(s) are healthy.[/green]")
        except ImportError:
            print(f"All {checked} skill(s) are healthy.")
