/**
 * Agent状态管理
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/api'
import type { WorkflowNode, WorkflowEdge } from '@/types'

export interface Agent {
  id: string
  name: string
  description?: string
  workflow_config: {
    nodes: WorkflowNode[]
    edges: WorkflowEdge[]
  }
  version: number
  status: string
  user_id: string
  created_at: string
  updated_at: string
}

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

  // 获取Agent列表（支持搜索、筛选）
  const fetchAgents = async (options?: {
    search?: string
    status?: string
    skip?: number
    limit?: number
  }) => {
    loading.value = true
    try {
      const params: any = {}
      if (options?.search) params.search = options.search
      if (options?.status) params.status = options.status
      if (options?.skip !== undefined) params.skip = options.skip
      if (options?.limit !== undefined) params.limit = options.limit
      
      const response = await api.get('/api/v1/agents', { params })
      agents.value = response.data
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 创建Agent
  const createAgent = async (agentData: {
    name: string
    description?: string
    workflow_config: {
      nodes: WorkflowNode[]
      edges: WorkflowEdge[]
    }
  }) => {
    loading.value = true
    try {
      const response = await api.post('/api/v1/agents', agentData)
      agents.value.push(response.data)
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 获取Agent详情
  const fetchAgent = async (id: string) => {
    loading.value = true
    try {
      const response = await api.get(`/api/v1/agents/${id}`)
      currentAgent.value = response.data
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 更新Agent
  const updateAgent = async (id: string, agentData: Partial<Agent>) => {
    loading.value = true
    try {
      const response = await api.put(`/api/v1/agents/${id}`, agentData)
      const index = agents.value.findIndex(a => a.id === id)
      if (index !== -1) {
        agents.value[index] = response.data
      }
      if (currentAgent.value?.id === id) {
        currentAgent.value = response.data
      }
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 删除Agent
  const deleteAgent = async (id: string) => {
    loading.value = true
    try {
      await api.delete(`/api/v1/agents/${id}`)
      agents.value = agents.value.filter(a => a.id !== id)
      if (currentAgent.value?.id === id) {
        currentAgent.value = null
      }
    } finally {
      loading.value = false
    }
  }

  // 部署Agent
  const deployAgent = async (id: string) => {
    loading.value = true
    try {
      const response = await api.post(`/api/v1/agents/${id}/deploy`)
      const index = agents.value.findIndex(a => a.id === id)
      if (index !== -1) {
        agents.value[index] = response.data
      }
      if (currentAgent.value?.id === id) {
        currentAgent.value = response.data
      }
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 停止Agent
  const stopAgent = async (id: string) => {
    loading.value = true
    try {
      const response = await api.post(`/api/v1/agents/${id}/stop`)
      const index = agents.value.findIndex(a => a.id === id)
      if (index !== -1) {
        agents.value[index] = response.data
      }
      if (currentAgent.value?.id === id) {
        currentAgent.value = response.data
      }
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 复制Agent
  const duplicateAgent = async (id: string, name?: string) => {
    loading.value = true
    try {
      const requestData = name ? { name } : {}
      const response = await api.post(`/api/v1/agents/${id}/duplicate`, requestData)
      agents.value.unshift(response.data) // 添加到列表开头
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 设置当前Agent
  const setCurrentAgent = (agent: Agent | null) => {
    currentAgent.value = agent
  }

  // 导出Agent
  const exportAgent = async (agentId: string) => {
    try {
      const response = await api.get(`/api/v1/agents/${agentId}/export`)
      
      if (!response.data) {
        throw new Error('导出数据为空')
      }
      
      // 创建下载链接
      const dataStr = JSON.stringify(response.data, null, 2)
      const dataBlob = new Blob([dataStr], { type: 'application/json;charset=utf-8' })
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement('a')
      link.href = url
      
      // 处理文件名：移除特殊字符，避免下载失败
      const agentName = (response.data.name || 'agent')
        .replace(/[<>:"/\\|?*]/g, '_') // 移除Windows不允许的字符
        .replace(/\s+/g, '_') // 空格替换为下划线
        .substring(0, 50) // 限制长度
      
      link.download = `${agentName}_${Date.now()}.json`
      link.style.display = 'none'
      document.body.appendChild(link)
      
      // 触发下载
      link.click()
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
      }, 100)
      
      return response.data
    } catch (error: any) {
      console.error('导出Agent失败', error)
      const errorMessage = error.response?.data?.detail || error.message || '导出失败'
      throw new Error(errorMessage)
    }
  }

  // 导入Agent
  const importAgent = async (agentData: any) => {
    loading.value = true
    try {
      const response = await api.post('/api/v1/agents/import', agentData)
      agents.value.unshift(response.data) // 添加到列表开头
      return response.data
    } finally {
      loading.value = false
    }
  }

  return {
    agents,
    currentAgent,
    loading,
    fetchAgents,
    createAgent,
    fetchAgent,
    updateAgent,
    deleteAgent,
    deployAgent,
    stopAgent,
    duplicateAgent,
    setCurrentAgent,
    exportAgent,
    importAgent
  }
})
