# -*- coding: utf-8 -*-
"""Skills 加载器，支持渐进式披露。"""

from pathlib import Path
from typing import Iterator

from .skill import Skill


class SkillsLoader:
    """
    从目录加载 Skills，支持渐进式披露：
    - 扫描时只解析每个 SKILL.md 的 frontmatter（轻量）
    - 完整内容在 agent 选择该 skill 后才加载
    """

    def __init__(self, directory: str | Path):
        self.dir = Path(directory)
        self._skills: dict[str, Skill] = {}
        self._load_skill_index()

    def _load_skill_index(self) -> None:
        """仅加载 frontmatter 索引，不加载完整内容。"""
        for skill_dir in self.dir.iterdir():
            if skill_dir.is_dir():
                md_path = skill_dir / "SKILL.md"
                if md_path.exists():
                    try:
                        skill = Skill(skill_dir)
                        self._skills[skill.name] = skill
                    except (ValueError, FileNotFoundError):
                        continue

    @property
    def skills(self) -> dict[str, Skill]:
        return self._skills

    def get_skill(self, name: str) -> Skill | None:
        """按 name 获取 skill。"""
        return self._skills.get(name)

    def list_skill_names(self) -> list[str]:
        """列出所有 skill 名称（仅 metadata，无额外 I/O）。"""
        return list(self._skills.keys())

    def get_skill_summaries(self) -> list[dict]:
        """
        返回所有 skills 的简要信息，用于构造 load_skill 的 description。
        仅使用已加载的 metadata，不触发完整内容加载。
        """
        return [
            {
                "name": s.name,
                "description": s.description,
                "version": s.version,
            }
            for s in self._skills.values()
        ]

    def load_skill_content(self, skill_name: str) -> str | None:
        """
        按需加载指定 skill 的完整内容。
        实现渐进式披露：仅在 agent 选择该 skill 时调用。
        """
        skill = self.get_skill(skill_name)
        if skill is None:
            return None
        return skill.get_full_skill_text()

    def __iter__(self) -> Iterator[Skill]:
        return iter(self._skills.values())

    def to_langchain_tools(self):
        """转为 LangChain Tools（load_skill Tool，渐进式披露）。"""
        from .langchain_integration import to_langchain_tools
        return to_langchain_tools(self)

    @classmethod
    def from_directory(cls, dir_path: str | Path) -> "SkillsLoader":
        return cls(dir_path)
