"""
Skill 数据模型

Skill 是平台的核心概念：可配置的行为指导单元
"""
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any, List
from datetime import datetime


class SkillTool(BaseModel):
    """Skill 工具定义（仅内置 Skill 支持）"""
    name: str
    description: str
    script: str  # 脚本文件名
    parameters: Dict[str, Dict[str, Any]] = Field(default_factory=dict)


class SkillConfig(BaseModel):
    """Skill 配置"""
    # 风格预设
    preset: Optional[str] = None

    # 可调节参数
    parameters: Dict[str, Dict[str, Any]] = Field(default_factory=dict)

    # 权重配置
    weights: Optional[Dict[str, float]] = None


class Skill(BaseModel):
    """Skill 模型"""
    id: str
    name: str
    version: str = "1.0.0"
    author: str = "未知"

    # 类型：builtin 或 user
    type: str = "user"

    # 核心内容 - 行为指导
    behavior_guide: str = ""  # 直接影响 Agent 行为

    # 配置
    config: SkillConfig = Field(default_factory=SkillConfig)

    # 提示词模板（可选）
    template: Optional[str] = None

    # 工具定义（仅内置 Skill）
    tools: Optional[List[SkillTool]] = None

    # 元数据
    category: str = "通用"
    tags: List[str] = Field(default_factory=list)
    visibility: str = "private"  # private 或 public

    # 文件路径（用于内部追踪）
    file_path: Optional[str] = None

    # 时间戳
    created_at: Optional[datetime] = None
    updated_at: Optional[datetime] = None


class SkillCreate(BaseModel):
    """创建 Skill 请求"""
    id: Optional[str] = None  # ID 可选，不传则自动生成
    name: str
    content: str  # Markdown 格式的完整 Skill 内容
    category: str = "通用"
    tags: List[str] = Field(default_factory=list)


class SkillUpdate(BaseModel):
    """更新 Skill 请求"""
    name: Optional[str] = None
    content: Optional[str] = None
    category: Optional[str] = None
    tags: Optional[List[str]] = None


class SkillConfigUpdate(BaseModel):
    """更新 Skill 配置请求"""
    preset: Optional[str] = None
    parameters: Optional[Dict[str, Dict[str, Any]]] = None
    weights: Optional[Dict[str, float]] = None


class SkillTestRequest(BaseModel):
    """测试 Skill 请求"""
    test_input: str
    context: Optional[Dict[str, Any]] = None
    temperature: float = 0.7


class SkillTestResponse(BaseModel):
    """测试 Skill 响应"""
    skill_id: str
    skill_name: str
    response: str
    usage: Optional[Dict[str, int]] = None


class SkillGenerateRequest(BaseModel):
    """AI 生成 Skill 请求"""
    description: str = Field(..., description="用户对想要创建的 Skill 的描述")
    category: Optional[str] = None
    tags: Optional[List[str]] = None
    temperature: float = Field(0.7, ge=0, le=1)


class SkillGenerateResponse(BaseModel):
    """AI 生成 Skill 响应"""
    suggested_id: str
    suggested_name: str
    skill_content: str
    category: str
    suggested_tags: List[str]
    explanation: str  # AI 对生成的 Skill 的说明


# ============================================================================
# 新增：文档驱动的 Skill 生成模型
# ============================================================================

class DocFetchRequest(BaseModel):
    """文档获取请求"""
    url: str = Field(..., description="文档 URL")
    selector: Optional[str] = Field(None, description="CSS 选择器（可选）")


class GitHubDocFetchRequest(BaseModel):
    """GitHub 文档获取请求"""
    repo_url: str = Field(..., description="GitHub 仓库 URL")
    docs_path: str = Field("README.md", description="文档路径")


class SkillGenerateFromDocsRequest(BaseModel):
    """基于文档生成 Skill 请求"""
    skill_name: str = Field(..., description="Skill 名称")
    description: Optional[str] = Field(None, description="Skill 描述（可选）")
    category: Optional[str] = Field(None, description="分类")
    tags: Optional[List[str]] = Field(None, description="标签")
    # 文档来源
    doc_urls: List[str] = Field(default_factory=list, description="文档 URL 列表")
    github_repos: List[GitHubDocFetchRequest] = Field(default_factory=list, description="GitHub 仓库列表")
    uploaded_references: Dict[str, str] = Field(default_factory=dict, description="用户上传的 references {文件名: 内容}")
    # 生成选项
    temperature: float = Field(0.7, ge=0, le=1, description="LLM 温度")
    include_doc_summary: bool = Field(True, description="是否包含文档摘要")


class SkillGenerateFromDocsResponse(BaseModel):
    """基于文档生成 Skill 响应"""
    success: bool
    preview_id: str = Field(..., description="预览 ID（用于后续保存）")
    skill_content: str = Field(..., description="生成的 SKILL.md 内容")
    skill_name: str
    suggested_id: str
    category: str
    tags: List[str]
    doc_summary: Optional[str] = Field(None, description="文档摘要")
    references_count: int = Field(0, description="生成的 reference 文件数")
    explanation: str


class SkillPreviewRequest(BaseModel):
    """Skill 预览请求"""
    skill_content: str
    skill_name: str
    category: Optional[str] = None
    tags: Optional[List[str]] = None


class SkillPreviewResponse(BaseModel):
    """Skill 预览响应"""
    preview_id: str
    skill_content: str
    parsed_metadata: Dict[str, Any]
    validation_warnings: List[str] = Field(default_factory=list)
    word_count: int
    estimated_tokens: int


class SkillSaveFromPreviewRequest(BaseModel):
    """从预览保存 Skill 请求"""
    preview_id: str
    skill_id: str = Field(..., description="要保存的 Skill ID")
    skill_content: str
    references: Optional[Dict[str, str]] = Field(None, description="要保存的 references")


class SkillRefineRequest(BaseModel):
    """AI 调整 Skill 请求"""
    skill_content: str
    refinement_prompt: str = Field(..., description="调整提示词")
    temperature: float = Field(0.7, ge=0, le=1)


class SkillRefineResponse(BaseModel):
    """AI 调整 Skill 响应"""
    success: bool
    refined_content: str
    changes_summary: str
    original_length: int
    new_length: int
