import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getAgentsApi, getAgentDetail, executeAgentApi, updateAgentApi, type AIAgent } from '../api/agents'

export const useAgentStore = defineStore('agent', () => {
  const agents = ref<AIAgent[]>([])
  const currentAgent = ref<AIAgent | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const enabledAgents = computed(() => agents.value.filter((agent: any) => agent.enabled))
  const activeAgents = computed(() => agents.value.filter((agent: any) => agent.status === '进行中'))
  const completedAgents = computed(() => agents.value.filter((agent: any) => agent.status === '已完成'))

  // 获取AI Agent列表
  const fetchAgents = async () => {
    loading.value = true
    error.value = null
    try {
      agents.value = await getAgentsApi()
    } catch (err: any) {
      error.value = err.message || '获取AI Agent列表失败'
      console.error('获取AI Agent列表失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 获取单个AI Agent
  const fetchAgent = async (name: string) => {
    loading.value = true
    error.value = null
    try {
      const agentData = await getAgentDetail(name)
      currentAgent.value = agentData
    } catch (err: any) {
      error.value = err.message || '获取AI Agent详情失败'
      console.error('获取AI Agent详情失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 执行AI Agent
  const executeAgent = async (name: string) => {
    loading.value = true
    error.value = null
    try {
      const result = await executeAgentApi(name)
      if (result.success) {
        // 执行成功后刷新列表
        await fetchAgents()
        return { success: true, message: result.message }
      } else {
        throw new Error(result.message || '执行失败')
      }
    } catch (err: any) {
      error.value = err.message || '执行AI Agent失败'
      console.error('执行AI Agent失败:', err)
      return { success: false, error: err.message }
    } finally {
      loading.value = false
    }
  }

  // 根据状态获取Agent数量
  const getAgentCountByStatus = (status: string) => {
    return agents.value.filter((agent: any) => agent.status === status).length
  }

  // 根据触发模式获取Agent数量
  const getAgentCountByTriggerMode = (triggerMode: string) => {
    return agents.value.filter((agent: any) => agent.trigger_mode === triggerMode).length
  }

  // 更新AI Agent
  const updateAgent = async (name: string, data: Partial<AIAgent>) => {
    loading.value = true
    error.value = null
    try {
      await updateAgentApi(name, data)
      // 更新成功后，手动更新本地状态
      if (currentAgent.value && currentAgent.value.name === name) {
        currentAgent.value = { ...currentAgent.value, ...data }
      }
      // 更新列表中的agent
      const index = agents.value.findIndex((agent: any) => agent.name === name)
      if (index !== -1) {
        agents.value[index] = { ...agents.value[index], ...data }
      }
      return { success: true }
    } catch (err: any) {
      error.value = err.message || '更新AI Agent失败'
      console.error('更新AI Agent失败:', err)
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    // 状态
    agents,
    currentAgent,
    loading,
    error,
    
    // 计算属性
    enabledAgents,
    activeAgents,
    completedAgents,
    
    // 方法
    fetchAgents,
    fetchAgent,
    executeAgent,
    updateAgent,
    getAgentCountByStatus,
    getAgentCountByTriggerMode
  }
})
