/**
 * Skill API 服务
 */
import api from './api'

export interface Skill {
  id: string
  name: string
  version: string
  type: 'builtin' | 'user'
  category: string
  behavior_guide: string
  tags: string[]
  author?: string
  config?: Record<string, any>
  created_at?: string
}

export interface SkillTestRequest {
  test_input: string
  context?: Record<string, any>
  temperature?: number
}

export interface SkillTestResponse {
  skill_id: string
  skill_name: string
  response: string
  usage?: Record<string, number>
}

// AI 生成 Skill 相关类型
export interface SkillGenerateRequest {
  description: string
  category?: string
  tags?: string[]
  temperature?: number
}

export interface SkillGenerateResponse {
  suggested_id: string
  suggested_name: string
  skill_content: string
  category: string
  suggested_tags: string[]
  explanation: string
}

// AI 辅助 Skill 创建相关的类型定义（保留用于其他功能）

export interface SkillDraft {
  suggested_id: string
  suggested_name: string
  suggested_category: string
  behavior_guide: string
  suggested_tags: string[]
}

export interface ValidationResult {
  valid: boolean
  errors: string[]
  warnings: string[]
  suggestions: string[]
}

export interface SkillOptimizeResult {
  behavior_guide: string
  improvements: string[]
  suggestions: string[]
}

export const skillService = {
  // ========================================
  // AI 生成 Skill（类似 Claude Code 的 skill-creator）
  // ========================================

  /**
   * 使用 AI 生成 Skill
   * @param request 包含描述、分类、标签的请求
   * @returns AI 生成的 Skill 内容和建议
   */
  generateSkill: async (request: SkillGenerateRequest): Promise<SkillGenerateResponse> => {
    return await api.post<SkillGenerateResponse>('/skills/generate', request)
  },

  // ========================================
  // 基于文档生成 Skill（skill-creator 工作流）
  // ========================================

  /**
   * 获取文档内容（用于预览或生成 Skill）
   * @param url 文档 URL
   * @param selector 可选的 CSS 选择器
   */
  fetchDoc: async (url: string, selector?: string): Promise<{ success: boolean; title?: string; content?: string; word_count?: number; char_count?: number; url?: string; error?: string }> => {
    return await api.post('/skills/fetch-doc', { url, selector })
  },

  /**
   * 获取 GitHub 文档内容
   * @param repoUrl GitHub 仓库 URL
   * @param docsPath 文档路径
   */
  fetchGithubDoc: async (repoUrl: string, docsPath: string): Promise<{ success: boolean; repo_url?: string; docs_path?: string; content?: string; word_count?: number; char_count?: number; error?: string }> => {
    return await api.post('/skills/fetch-github-doc', { repo_url: repoUrl, docs_path: docsPath })
  },

  /**
   * 基于文档生成 Skill（完整工作流）
   * @param request 包含技能名称、文档来源等
   * @returns 生成的 Skill 内容和预览 ID
   */
  generateSkillFromDocs: async (request: {
    skill_name: string
    description?: string
    category?: string
    tags?: string[]
    doc_urls?: string[]
    github_repos?: Array<{ repo_url: string; docs_path: string }>
    uploaded_references?: Record<string, string>
    include_doc_summary?: boolean
    temperature?: number
  }): Promise<{
    success: boolean
    preview_id: string
    skill_content: string
    skill_name: string
    suggested_id: string
    category: string
    tags: string[]
    doc_summary: string
    references_count: number
    explanation: string
  }> => {
    return await api.post('/skills/generate-from-docs', request)
  },

  /**
   * 预览 Skill（验证和解析）
   * @param request 包含 SKILL.md 内容
   * @returns 预览 ID 和解析结果
   */
  previewSkill: async (request: {
    skill_content: string
    skill_name?: string
    category?: string
    tags?: string[]
  }): Promise<{
    preview_id: string
    skill_content: string
    parsed_metadata: Record<string, any>
    validation_warnings: string[]
    word_count: number
    estimated_tokens: number
  }> => {
    return await api.post('/skills/preview', request)
  },

  /**
   * 使用 AI 调整/优化 Skill
   * @param skillContent 原始 SKILL.md 内容
   * @param refinementPrompt 调整需求
   * @param temperature 温度
   * @returns 调整后的内容
   */
  refineSkill: async (skillContent: string, refinementPrompt: string, temperature?: number): Promise<{
    success: boolean
    refined_content: string
    changes_summary: string
    original_length: number
    new_length: number
  }> => {
    return await api.post('/skills/refine', {
      skill_content: skillContent,
      refinement_prompt: refinementPrompt,
      temperature: temperature || 0.7
    })
  },

  /**
   * 从预览保存 Skill 到系统
   * @param previewId 预览 ID
   * @param skillId Skill ID
   * @param skillContent SKILL.md 内容
   * @param references 可选的 references 文件
   */
  saveSkillFromPreview: async (previewId: string, skillId: string, skillContent: string, references?: Record<string, string>): Promise<Skill> => {
    return await api.post<Skill>('/skills/save-from-preview', {
      preview_id: previewId,
      skill_id: skillId,
      skill_content: skillContent,
      references: references
    })
  },

  /**
   * 获取预览数据
   * @param previewId 预览 ID
   */
  getPreview: async (previewId: string): Promise<{
    preview: Record<string, any>
    references: Record<string, string>
    references_count: number
  }> => {
    return await api.get(`/skills/preview/${previewId}`)
  },

  /**
   * 删除预览数据
   * @param previewId 预览 ID
   */
  deletePreview: async (previewId: string): Promise<void> => {
    return await api.delete(`/skills/preview/${previewId}`)
  },

  /**
   * 获取 Skill 及其参考文件
   * @param skillId Skill ID
   * @param includeReferences 是否包含参考文件内容
   */
  getSkillWithReferences: async (skillId: string, includeReferences = true): Promise<{
    skill: Skill
    references?: Record<string, string>
  }> => {
    return await api.get(`/skills/${skillId}/with-references`, { include_references: includeReferences })
  },

  // ========================================
  // 基础 CRUD 方法
  // ========================================

  /**
   * 列出所有 Skills
   */
  listSkills: async (params?: { skill_type?: string; category?: string }) => {
    return await api.get<Skill[]>('/skills', { params })
  },

  /**
   * 获取 Skill 详情
   */
  getSkill: async (skillId: string) => {
    return await api.get<Skill>(`/skills/${skillId}`)
  },

  /**
   * 测试 Skill
   */
  testSkill: async (skillId: string, data: SkillTestRequest) => {
    return await api.post<SkillTestResponse>(`/skills/${skillId}/test`, data)
  },

  /**
   * 创建 Skill (ID 由后端自动生成)
   */
  createSkill: async (data: { name: string; content: string; category?: string }) => {
    return await api.post<Skill>('/skills', data)
  },

  /**
   * 更新 Skill
   */
  updateSkill: async (skillId: string, data: { name?: string; content?: string }) => {
    return await api.put<Skill>(`/skills/${skillId}`, data)
  },

  /**
   * 更新 Skill 及其 References
   * @param skillId Skill ID
   * @param skillContent SKILL.md 内容
   * @param references 参考文件对象 (可选)
   */
  updateSkillWithReferences: async (
    skillId: string,
    skillContent: string,
    references?: Record<string, string>
  ): Promise<Skill> => {
    return await api.put<Skill>(`/skills/${skillId}/with-references`, {
      preview_id: '',  // 不需要preview_id，编辑模式
      skill_id: skillId,
      skill_content: skillContent,
      references: references || {}
    })
  },

  /**
   * 删除 Skill
   */
  deleteSkill: async (skillId: string) => {
    return await api.delete(`/skills/${skillId}`)
  },

  // ========================================
  // Agent-Skill 生命周期方法（使用 skill-creator 脚本）
  // ========================================

  /**
   * 初始化 Skill 模板（使用 skill-creator 的 init_skill.py 脚本）
   * @param skillName Skill 名称（hyphen-case，如 'my-awesome-skill'）
   * @param outputPath 可选的输出路径
   * @returns 执行结果
   */
  initSkillTemplate: async (skillName: string, outputPath?: string): Promise<{ success: boolean; message: string; output?: string }> => {
    return await api.post('/skills/init', {
      skill_name: skillName,
      output_path: outputPath
    })
  },

  /**
   * 验证 Skill 结构（使用 skill-creator 的 quick_validate.py 脚本）
   * @param skillId 要验证的 Skill ID
   * @returns 验证结果
   */
  validateSkillScript: async (skillId: string): Promise<{ success: boolean; valid: boolean; message?: string; error?: string }> => {
    return await api.post('/skills/validate-script', {
      skill_id: skillId
    })
  },

  /**
   * 打包 Skill（使用 skill-creator 的 package_skill.py 脚本）
   * @param skillId 要打包的 Skill ID
   * @param outputDir 可选的输出目录
   * @returns 打包结果
   */
  packageSkill: async (skillId: string, outputDir?: string): Promise<{ success: boolean; message: string; output?: string }> => {
    return await api.post('/skills/package', {
      skill_id: skillId,
      output_dir: outputDir
    })
  },

  /**
   * 列出所有已注册的工具（Agent-Skill 生命周期：注册阶段）
   * @returns 所有已注册工具的 JSON Schema
   */
  listAvailableTools: async (): Promise<any[]> => {
    return await api.get('/skills/tools')
  },

  /**
   * 执行工具（Agent-Skill 生命周期：路由 → 执行 → 反馈）
   * @param toolName 工具名称
   * @param parameters 工具参数
   * @returns 执行结果
   */
  executeTool: async (toolName: string, parameters: Record<string, any>): Promise<any> => {
    return await api.post('/skills/execute-tool', null, {
      params: { tool_name: toolName },
      data: parameters
    })
  },

  // ========================================
  // LLM 自动选择 Skills（智能路由）
  // ========================================

  /**
   * LLM 根据描述自动选择最合适的 Skills
   * @param userIntent 用户意图描述
   * @param context 可选的上下文信息
   * @param excludeSkills 要排除的 Skills
   * @param requiredCategory 必需的分类
   * @param requiredTags 必需的标签
   * @returns 选择结果
   */
  selectSkills: async (request: {
    user_intent: string
    context?: Record<string, any>
    exclude_skills?: string[]
    required_category?: string
    required_tags?: string[]
  }): Promise<{
    selected_skills: Array<{
      id: string
      name: string
      description: string
      category: string
      tags: string[]
    }>
    selection_reason: string
    confidence_scores: Record<string, number>
  }> => {
    return await api.post('/skills/select-skills', request)
  },

  /**
   * 配置 Agent 工作流的 Skill 使用方式
   * @param config 工作流配置
   * @returns 配置结果
   */
  configureAgentWorkflow: async (config: {
    workflow_type: 'sequential' | 'parallel' | 'adaptive'
    default_skills?: string[]
    steps?: Array<{
      step_name: string
      skills: string[]
      enabled: boolean
    }>
  }): Promise<{
    success: boolean
    message: string
    config: Record<string, any>
  }> => {
    return await api.post('/skills/agent-workflow/configure', config)
  }
}
