"""Skill discovery — scans for SKILL.md and instantiates SkillBase."""

from pathlib import Path

import structlog

from fliiq.runtime.package_data import bundled_skills_dir
from fliiq.runtime.skills.base import SkillBase

log = structlog.get_logger()

# Default search locations relative to project root
_DEFAULT_SKILLS_DIRS = ["skills/core", "skills/coding", "skills/tutoring", ".fliiq/skills"]


def discover_skills(skills_dir: Path | None = None, project_root: Path | None = None) -> dict[str, SkillBase]:
    """Scan for skills with SKILL.md. Returns name→SkillBase dict."""
    if project_root is None:
        from fliiq.runtime.config import resolve_fliiq_dir

        try:
            root = resolve_fliiq_dir().parent
        except FileNotFoundError:
            root = Path.cwd()
    else:
        root = project_root
    skills: dict[str, SkillBase] = {}

    if skills_dir:
        search_dirs = [skills_dir]
    else:
        search_dirs = [root / d for d in _DEFAULT_SKILLS_DIRS]
        # Bundled fallback: if skills/core doesn't exist locally, use package-bundled
        if not (root / "skills" / "core").is_dir():
            bundled = bundled_skills_dir()
            if bundled.is_dir():
                search_dirs.insert(0, bundled)

    # Add global ~/.fliiq/skills/ if it exists
    from fliiq.runtime.config import global_fliiq_dir

    global_skills = global_fliiq_dir() / "skills"
    if global_skills.is_dir() and global_skills not in search_dirs:
        search_dirs.append(global_skills)

    for search_dir in search_dirs:
        if not search_dir.is_dir():
            continue
        for skill_md in search_dir.rglob("SKILL.md"):
            skill_dir = skill_md.parent
            try:
                skill = SkillBase(str(skill_dir))
                skills[skill.name] = skill
                log.debug("skill_discovered", name=skill.name, path=str(skill_dir))
            except Exception as e:
                log.warning("skill_load_failed", path=str(skill_dir), error=str(e))

    return skills
