"""
完整的数据模型和 API，实现 Skills 与 LLM 的深度结合
"""
from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any, Union
from datetime import datetime
from enum import Enum


# ============================================================================
# Skill 与 LLM 结合的核心模型
# ============================================================================

class SkillTriggerType(str, Enum):
    """Skill 触发类型"""
    # LLM 根据 description 自动选择
    AUTO = "auto"
    # 用户/Agent 显式指定
    EXPLICIT = "explicit"
    # Agent 工作流固定使用
    FIXED = "fixed"


class SkillMetadata(BaseModel):
    """Skill 元数据（用于触发和选择）"""
    name: str
    # 关键：description 用于 LLM 理解何时使用此 Skill
    description: str  # 应包含：功能、触发条件、使用场景
    category: str
    tags: List[str]
    trigger_type: SkillTriggerType

    # 可选的触发关键词（用于精确匹配）
    keywords: List[str] = Field(default_factory=list)

    # 适用场景（用于 AI 匹配）
    use_cases: List[str] = Field(default_factory=list)

    # 依赖的其他 Skills
    dependencies: List[str] = Field(default_factory=list)

    # 权重（用于多 Skill 选择时的排序）
    priority: float = 1.0


class SkillReferenceFile(BaseModel):
    """参考文件定义"""
    filename: str
    filetype: str  # md, txt, json, yaml, py, sh
    content: str
    description: Optional[str] = None
    size_bytes: int


class SkillScript(BaseModel):
    """脚本定义"""
    filename: str
    language: str  # python, bash, javascript
    code: str
    description: str
    parameters: Dict[str, Any] = Field(default_factory=dict)


class SkillAsset(BaseModel):
    """资产定义（模板、图标等）"""
    filename: str
    filetype: str
    content: str  # base64 或文本
    description: str


class SkillStructure(BaseModel):
    """完整的 Skill 结构（符合 skill-creator 标准）"""
    # SKILL.md
    frontmatter: Dict[str, Any]  # YAML frontmatter: name, description
    behavior_guide: str  # Markdown 内容

    # 可选资源
    scripts: List[SkillScript] = Field(default_factory=list)
    references: List[SkillReferenceFile] = Field(default_factory=list)
    assets: List[SkillAsset] = Field(default_factory=list)


# ============================================================================
# AI 生成 Skill 的完整流程
# ============================================================================

class SkillGenerationRequest(BaseModel):
    """
    AI 生成 Skill 请求

    按照 skill-creator 的完整流程：
    Step 1: Understanding - 理解需求
    Step 2: Planning - 规划资源
    Step 3: Initialize - 生成结构
    Step 4: Edit - 用户调整
    Step 5: Package - 打包
    """
    # Step 1: 用户意图
    user_intent: str = Field(
        ...,
        description="用户想要创建的 Skill 的意图描述"
    )
    use_cases: List[str] = Field(
        default_factory=list,
        description="具体用例示例，如 ['用户说：帮我写一段古风对话', '用户说：审核这段内容的一致性']"
    )

    # 可选约束
    preferred_category: Optional[str] = None
    preferred_tags: Optional[List[str]] = None
    trigger_type: SkillTriggerType = SkillTriggerType.AUTO

    # 生成选项
    include_scripts: bool = False  # 是否生成脚本
    include_references: bool = False  # 是否生成参考文档模板
    include_assets: bool = False  # 是否生成资产模板
    temperature: float = Field(0.7, ge=0, le=1)


class SkillAnalysis(BaseModel):
    """Step 1: 需求分析结果"""
    skill_type: str  # 如 "对话创作", "内容审核", "文件处理"
    core_functionality: str
    intended_users: List[str]
    key_features: List[str]
    suggested_complexity: str  # "simple", "medium", "complex"


class SkillPlanning(BaseModel):
    """Step 2: 资源规划结果"""
    needs_scripts: bool
    suggested_scripts: List[Dict[str, str]]  # [{filename, purpose}]
    needs_references: bool
    suggested_references: List[Dict[str, str]]
    needs_assets: bool
    suggested_assets: List[Dict[str, str]]

    # Degree of freedom 建议
    suggested_freedom: str  # "high", "medium", "low"


class SkillGenerationResponse(BaseModel):
    """
    AI 生成 Skill 的完整响应

    包含完整的 skill-creator 流程结果
    """
    # Step 1: 分析结果
    analysis: SkillAnalysis

    # Step 2: 规划结果
    planning: SkillPlanning

    # Step 3: 完整的 Skill 结构
    skill_structure: SkillStructure

    # 元数据建议
    suggested_metadata: SkillMetadata

    # 实现建议
    implementation_steps: List[str]
    best_practices: List[str]

    # 验证结果
    validation_passed: bool
    validation_warnings: List[str] = Field(default_factory=list)
    validation_errors: List[str] = Field(default_factory=list)


# ============================================================================
# Skill 调整/优化请求
# ============================================================================

class SkillRefinementRequest(BaseModel):
    """对已生成的 Skill 进行调整"""
    skill_id: str
    current_content: str

    # 调整需求
    refinement_type: str  # "optimize", "extend", "fix", "adapt"
    refinement_description: str

    # 上下文
    user_feedback: Optional[str] = None
    use_case_update: Optional[str] = None

    temperature: float = Field(0.7, ge=0, le=1)


class SkillRefinementResponse(BaseModel):
    """调整后的 Skill"""
    updated_structure: SkillStructure
    changes_made: List[str]
    improvement_suggestions: List[str]


# ============================================================================
# Skill 选择和路由（LLM 与 Skills 结合）
# ============================================================================

class SkillSelectionCriteria(BaseModel):
    """Skill 选择条件"""
    # 用户意图
    user_intent: str

    # 上下文信息
    context: Dict[str, Any] = Field(default_factory=dict)

    # 约束条件
    required_category: Optional[str] = None
    required_tags: Optional[List[str]] = None
    exclude_skills: List[str] = Field(default_factory=list)

    # 选择模式
    selection_mode: str = "auto"  # "auto", "fixed", "hybrid"


class SkillSelectionResult(BaseModel):
    """Skill 选择结果"""
    selected_skills: List[SkillMetadata]
    selection_reason: str
    confidence_scores: Dict[str, float]
    alternative_skills: List[SkillMetadata] = Field(default_factory=list)


class SkillExecutionContext(BaseModel):
    """Skill 执行上下文"""
    skill_id: str
    skill_metadata: SkillMetadata
    execution_mode: str  # "integrated", "standalone", "chained"

    # 上下文数据
    user_input: str
    context_data: Dict[str, Any] = Field(default_factory=dict)

    # 参考文件（已加载）
    loaded_references: Dict[str, str] = Field(default_factory=dict)

    # 执行参数
    temperature: float = 0.7
    max_tokens: Optional[int] = None


class SkillExecutionResponse(BaseModel):
    """Skill 执行结果"""
    skill_id: str
    execution_success: bool
    result: str

    # 使用的信息
    references_used: List[str]
    scripts_executed: List[str]

    # 反馈信息
    execution_time_ms: int
    tokens_used: Dict[str, int]

    # 建议
    improvement_suggestions: List[str] = Field(default_factory=list)


# ============================================================================
# Agent 工作流中的 Skill 配置
# ============================================================================

class AgentWorkflowStep(BaseModel):
    """Agent 工作流步骤"""
    step_name: str
    step_number: int

    # Skill 配置
    skill_id: Optional[str] = None  # None 表示不使用 Skill
    skill_mode: str = "required"  # "required", "optional", "conditional"

    # 条件（用于 conditional 模式）
    condition: Optional[str] = None

    # 回退行为
    fallback_skill_id: Optional[str] = None
    fallback_behavior: Optional[str] = None


class AgentWorkflowConfig(BaseModel):
    """Agent 工作流配置（定义哪些步骤使用哪些 Skills）"""
    agent_id: str
    agent_name: str

    # 工作流步骤
    steps: List[AgentWorkflowStep]

    # 全局配置
    default_temperature: float = 0.7
    allow_skill_substitution: bool = False
    require_all_skills: bool = True


# ============================================================================
# 批量 Skill 操作
# ============================================================================

class BatchSkillOperation(BaseModel):
    """批量 Skill 操作"""
    operation: str  # "validate", "package", "deploy"
    skill_ids: List[str]
    options: Dict[str, Any] = Field(default_factory=dict)


class BatchSkillOperationResponse(BaseModel):
    """批量操作结果"""
    operation: str
    total_skills: int
    successful_skills: List[str]
    failed_skills: List[Dict[str, str]]
    summary: Dict[str, Any]
