# -*- coding: utf-8 -*-
"""单个 Skill 的表示，支持渐进式披露（按需加载完整内容）。"""

from pathlib import Path
from typing import Any

import ruamel.yaml

yaml_loader = ruamel.yaml.YAML(typ="safe")


def _parse_skill_file(path: Path) -> tuple[dict[str, Any], str]:
    """解析 SKILL.md，返回 (frontmatter, body)。"""
    content = path.read_text(encoding="utf-8")
    parts = content.split("---", 2)
    if len(parts) != 3:
        raise ValueError(f"Invalid SKILL.md format: {path}")
    _, yaml_part, md_part = parts
    metadata = yaml_loader.load(yaml_part) or {}
    return dict(metadata), md_part.strip()


class Skill:
    """
    表示一个 Skill，支持渐进式披露：
    - 初始化时只加载 frontmatter（name, description 等）
    - 调用 content 或 full_content 时才加载完整 Markdown 内容
    """

    def __init__(self, skill_dir: Path):
        self._dir = Path(skill_dir)
        self._path = self._dir / "SKILL.md"
        if not self._path.exists():
            raise FileNotFoundError(f"SKILL.md not found in {skill_dir}")

        # 只解析 frontmatter，不加载 body（渐进式披露）
        metadata, _ = _parse_skill_file(self._path)
        self._metadata = metadata
        self._full_content: str | None = None  # 懒加载

    @property
    def name(self) -> str:
        return self._metadata.get("name", self._dir.name)

    @property
    def description(self) -> str:
        return self._metadata.get("description", "")

    @property
    def version(self) -> str:
        return self._metadata.get("version", "1.0")

    @property
    def metadata(self) -> dict[str, Any]:
        return dict(self._metadata)

    @property
    def directory(self) -> Path:
        return self._dir

    def load_content(self) -> str:
        """加载完整 Skill 内容（Markdown body）。按需调用以实现渐进式披露。"""
        if self._full_content is None:
            _, body = _parse_skill_file(self._path)
            self._full_content = body
        return self._full_content

    @property
    def content(self) -> str:
        """完整 Markdown 内容（触发懒加载）。"""
        return self.load_content()

    def get_full_skill_text(self) -> str:
        """
        返回完整 Skill 文本（frontmatter + body），用于注入到 agent 上下文。
        实现渐进式披露时，仅在 agent 选择该 skill 后调用。
        """
        content = self.path.read_text(encoding="utf-8")
        return content

    @property
    def path(self) -> Path:
        return self._path

    def __repr__(self) -> str:
        return f"Skill(name={self.name!r}, description={self.description[:50]!r}...)"
