"""SkillSpec - Skill 标准接口规范定义

定义 Skill 的元数据、输入输出 Schema、依赖声明、质量门禁配置等标准规范，
确保 7 项能力以 Skill 插件形式统一接入。
"""

from __future__ import annotations

import logging
from dataclasses import dataclass, field
from typing import Any

logger = logging.getLogger(__name__)


@dataclass
class DependencyDecl:
    """依赖声明 - 声明 Skill/Tool 依赖

    Attributes:
        name: 依赖的 Skill 或 Tool 名称
        version_constraint: 可选的版本约束（如 ">=1.0.0,<2.0.0"）
        type: 依赖类型，"skill" 或 "tool"
        required: 是否为必需依赖（默认 True）
    """

    name: str
    version_constraint: str = ""
    type: str = "skill"  # "skill" | "tool"
    required: bool = True


@dataclass
class CapabilityTag:
    """能力标签 - 用于 Skill 能力查询

    Attributes:
        tag: 标签名（如 "rag", "terminal", "computer_use"）
        description: 标签描述
    """

    tag: str
    description: str = ""


@dataclass
class SkillSpec:
    """Skill 标准接口规范

    定义 Skill 的完整元数据、输入输出 Schema、依赖声明和质量门禁配置。
    用于 Skill 注册时的标准化描述和校验。

    Attributes:
        name: Skill 唯一标识名
        version: 语义版本号（遵循 semver）
        description: Skill 功能描述
        capabilities: 能力标签列表，用于按能力查询
        dependencies: 依赖声明列表
        input_schema: 输入 JSON Schema
        output_schema: 输出 JSON Schema
        quality_gate: 质量门禁配置
        metadata: 扩展元数据
    """

    name: str
    version: str = "1.0.0"
    description: str = ""
    capabilities: list[CapabilityTag] = field(default_factory=list)
    dependencies: list[DependencyDecl] = field(default_factory=list)
    input_schema: dict[str, Any] | None = None
    output_schema: dict[str, Any] | None = None
    quality_gate: dict[str, Any] | None = None
    metadata: dict[str, Any] = field(default_factory=dict)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> SkillSpec:
        """从字典创建 SkillSpec"""
        capabilities = [
            CapabilityTag(**cap) if isinstance(cap, dict) else cap
            for cap in data.get("capabilities", [])
        ]
        dependencies = [
            DependencyDecl(**dep) if isinstance(dep, dict) else dep
            for dep in data.get("dependencies", [])
        ]
        return cls(
            name=data["name"],
            version=data.get("version", "1.0.0"),
            description=data.get("description", ""),
            capabilities=capabilities,
            dependencies=dependencies,
            input_schema=data.get("input_schema"),
            output_schema=data.get("output_schema"),
            quality_gate=data.get("quality_gate"),
            metadata=data.get("metadata", {}),
        )

    def to_dict(self) -> dict[str, Any]:
        """序列化为字典"""
        d: dict[str, Any] = {
            "name": self.name,
            "version": self.version,
            "description": self.description,
            "capabilities": [
                {"tag": c.tag, "description": c.description}
                for c in self.capabilities
            ],
            "dependencies": [
                {
                    "name": dep.name,
                    "version_constraint": dep.version_constraint,
                    "type": dep.type,
                    "required": dep.required,
                }
                for dep in self.dependencies
            ],
            "metadata": self.metadata,
        }
        if self.input_schema is not None:
            d["input_schema"] = self.input_schema
        if self.output_schema is not None:
            d["output_schema"] = self.output_schema
        if self.quality_gate is not None:
            d["quality_gate"] = self.quality_gate
        return d

    @property
    def capability_tags(self) -> list[str]:
        """返回所有能力标签名列表"""
        return [c.tag for c in self.capabilities]

    @property
    def required_dependencies(self) -> list[DependencyDecl]:
        """返回所有必需依赖"""
        return [dep for dep in self.dependencies if dep.required]

    @property
    def skill_dependencies(self) -> list[DependencyDecl]:
        """返回所有 Skill 类型依赖"""
        return [dep for dep in self.dependencies if dep.type == "skill"]

    @property
    def tool_dependencies(self) -> list[DependencyDecl]:
        """返回所有 Tool 类型依赖"""
        return [dep for dep in self.dependencies if dep.type == "tool"]


@dataclass
class HealthCheckResult:
    """依赖健康检查结果

    Attributes:
        skill_name: 被检查的 Skill 名称
        skill_version: 被检查的 Skill 版本
        healthy: 是否健康（所有必需依赖已满足）
        missing_dependencies: 缺失的依赖列表
        version_mismatches: 版本不匹配的依赖列表
        warnings: 警告信息列表
    """

    skill_name: str
    skill_version: str = ""
    healthy: bool = True
    missing_dependencies: list[str] = field(default_factory=list)
    version_mismatches: list[str] = field(default_factory=list)
    warnings: list[str] = field(default_factory=list)

    def to_dict(self) -> dict[str, Any]:
        return {
            "skill_name": self.skill_name,
            "skill_version": self.skill_version,
            "healthy": self.healthy,
            "missing_dependencies": self.missing_dependencies,
            "version_mismatches": self.version_mismatches,
            "warnings": self.warnings,
        }
