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

export const useAgentStore = defineStore('agent', () => {
  const currentAgent = ref<AIAgent | null>(null)
  const currentPageType = ref<string>('')

  // 获取单个AI Agent
  const fetchAgent = async (name: string, pageType: string) => {
    try {
      const agentData = await getAgentDetail(name, pageType)
      currentAgent.value = agentData
      currentPageType.value = pageType
    } catch (err: any) {
      console.error('获取AI Agent详情失败:', err)
      throw err
    }
  }

  // 更新AI Agent
  const updateAgent = async (name: string, data: Partial<AIAgent>, pageType: string) => {
    try {
      await updateAgentApi(name, data, pageType)
      // 更新成功后，手动更新本地状态
      if (currentAgent.value && currentAgent.value.name === name) {
        currentAgent.value = { ...currentAgent.value, ...data }
      }
      return { success: true }
    } catch (err: any) {
      console.error('更新AI Agent失败:', err)
      throw err
    }
  }

  return {
    // 状态
    currentAgent,
    currentPageType,
    
    // 方法
    fetchAgent,
    updateAgent
  }
})
