/**
 * 执行状态管理
 */
import { defineStore } from 'pinia'
import { ref } from 'vue'
import api from '@/api'

export interface Execution {
  id: string
  workflow_id?: string
  agent_id?: string
  input_data?: any
  output_data?: any
  status: string
  error_message?: string
  execution_time?: number
  task_id?: string
  created_at: string
}

export const useExecutionStore = defineStore('execution', () => {
  const executions = ref<Execution[]>([])
  const currentExecution = ref<Execution | null>(null)
  const loading = ref(false)

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

  // 获取执行详情
  const fetchExecution = async (id: string) => {
    loading.value = true
    try {
      const response = await api.get(`/api/v1/executions/${id}`)
      currentExecution.value = response.data
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 创建执行任务
  const createExecution = async (data: {
    workflow_id?: string
    agent_id?: string
    input_data: any
  }) => {
    loading.value = true
    try {
      const response = await api.post('/api/v1/executions', data)
      executions.value.unshift(response.data)
      currentExecution.value = response.data
      return response.data
    } finally {
      loading.value = false
    }
  }

  // 获取执行状态
  const fetchExecutionStatus = async (id: string) => {
    try {
      const response = await api.get(`/api/v1/executions/${id}/status`)
      // 更新当前执行记录的状态
      if (currentExecution.value?.id === id) {
        currentExecution.value.status = response.data.status
      }
      // 更新列表中的状态
      const index = executions.value.findIndex(e => e.id === id)
      if (index !== -1) {
        executions.value[index].status = response.data.status
      }
      return response.data
    } catch (error) {
      console.error('获取执行状态失败', error)
      throw error
    }
  }

  // 设置当前执行记录
  const setCurrentExecution = (execution: Execution | null) => {
    currentExecution.value = execution
  }

  // 清除当前执行记录
  const clearCurrentExecution = () => {
    currentExecution.value = null
  }

  return {
    executions,
    currentExecution,
    loading,
    fetchExecutions,
    fetchExecution,
    createExecution,
    fetchExecutionStatus,
    setCurrentExecution,
    clearCurrentExecution
  }
})
