"""
Skill 数据模型
"""

from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, Any, List, Optional
import uuid


@dataclass
class Skill:
    """
    技能 - 从 Markdown 文件加载的领域知识

    技能可以形成层次结构（通过 parent_id）
    """
    skill_id: str
    scope: str  # "agent:{type}" 或 "user:{uid}"

    name: str
    description: str
    category: str  # 分类，如 "search", "reasoning", "writing"

    # 层次结构
    parent_id: Optional[str] = None

    # 内容
    content: Optional[str] = None  # 完整的 skill 内容（Markdown）
    guidelines: List[str] = field(default_factory=list)
    derived_from: List[str] = field(default_factory=list)

    # 版本
    version: int = 1

    # 时间
    created_at: datetime = field(default_factory=datetime.now)
    updated_at: datetime = field(default_factory=datetime.now)

    @classmethod
    def create(
        cls,
        scope: str,
        name: str,
        description: str,
        category: str = "general",
        content: Optional[str] = None,
        guidelines: List[str] = None,
        derived_from: List[str] = None,
        parent_id: Optional[str] = None,
    ) -> "Skill":
        """创建新的 Skill"""
        now = datetime.now()
        return cls(
            skill_id=str(uuid.uuid4()),
            scope=scope,
            name=name,
            description=description,
            category=category,
            parent_id=parent_id,
            content=content,
            guidelines=guidelines or [],
            derived_from=derived_from or [],
            created_at=now,
            updated_at=now,
        )

    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            "skill_id": self.skill_id,
            "scope": self.scope,
            "name": self.name,
            "description": self.description,
            "category": self.category,
            "parent_id": self.parent_id,
            "content": self.content,
            "guidelines": self.guidelines,
            "derived_from": self.derived_from,
            "version": self.version,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }

    def to_prompt_text(self) -> str:
        """
        转换为可注入 Prompt 的文本

        优先使用完整的 content（如果有），否则使用 description + guidelines
        """
        if self.content:
            return self.content.strip()

        lines = [f"### {self.name}", self.description]
        if self.guidelines:
            lines.append("指导原则：")
            for g in self.guidelines:
                lines.append(f"- {g}")
        return "\n".join(lines)
