import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as skillsApi from '@/api/skills'
import type { ISkillInfo, ISkillDetail, ICapabilityInfo } from '@/api/skills'

export const useSkillsStore = defineStore('skills', () => {
  // --- State ---
  const skills = ref<ISkillInfo[]>([])
  const capabilities = ref<ICapabilityInfo[]>([])
  const selectedSkill = ref<ISkillDetail | null>(null)
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  const totalSkills = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(20)
  const selectedCapability = ref<string | null>(null)

  // --- Getters ---
  const skillNames = computed(() => skills.value.map((s) => s.name))

  // --- Actions ---
  async function fetchSkills(capability?: string, page?: number): Promise<void> {
    isLoading.value = true
    error.value = null
    try {
      const cap = capability ?? selectedCapability.value ?? undefined
      const p = page ?? currentPage.value
      const data = await skillsApi.listSkills(cap, p, pageSize.value)
      skills.value = data.skills
      totalSkills.value = data.total
      currentPage.value = data.page
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取技能列表失败'
      console.error('Failed to fetch skills:', err)
    } finally {
      isLoading.value = false
    }
  }

  async function fetchCapabilities(): Promise<void> {
    try {
      const data = await skillsApi.listCapabilities()
      capabilities.value = data.capabilities
    } catch (err) {
      console.error('Failed to fetch capabilities:', err)
    }
  }

  async function fetchSkillDetail(skillName: string): Promise<void> {
    isLoading.value = true
    error.value = null
    try {
      const data = await skillsApi.getSkillDetail(skillName)
      selectedSkill.value = data
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取技能详情失败'
      console.error('Failed to fetch skill detail:', err)
    } finally {
      isLoading.value = false
    }
  }

  async function checkHealth(skillName: string): Promise<string> {
    try {
      const data = await skillsApi.checkSkillHealth(skillName)
      return data.status
    } catch (err) {
      console.error('Failed to check skill health:', err)
      return 'error'
    }
  }

  async function reloadSkill(skillName: string): Promise<void> {
    try {
      await skillsApi.reloadSkill(skillName)
      await fetchSkills()
      if (selectedSkill.value?.name === skillName) {
        await fetchSkillDetail(skillName)
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '重新加载技能失败'
      console.error('Failed to reload skill:', err)
      throw err
    }
  }

  function setCapabilityFilter(capability: string | null): void {
    selectedCapability.value = capability
    currentPage.value = 1
  }

  function clearSelectedSkill(): void {
    selectedSkill.value = null
  }

  return {
    // State
    skills,
    capabilities,
    selectedSkill,
    isLoading,
    error,
    totalSkills,
    currentPage,
    pageSize,
    selectedCapability,
    // Getters
    skillNames,
    // Actions
    fetchSkills,
    fetchCapabilities,
    fetchSkillDetail,
    checkHealth,
    reloadSkill,
    setCapabilityFilter,
    clearSelectedSkill,
  }
})
