import axios from 'axios'

import type { AIAgent, AgentExecutionResult } from '../types'
import { deleteRecords, createRecord, updateRecord, getFieldSelectOptions, getRecord } from './common'

// 重新导出类型，供其他模块使用
export type { AIAgent, AgentExecutionResult }

// 使用相对路径，通过Vite代理转发到后端
const jingrowServerUrl = import.meta.env.VITE_JINGROW_SERVER_URL || ''

// 获取Jingrow API鉴权头部
function get_jingrow_api_headers() {
  const apiKey = (import.meta as any).env.VITE_JINGROW_API_KEY
  const apiSecret = (import.meta as any).env.VITE_JINGROW_API_SECRET
  
  // 如果没有设置API密钥，暂时返回基本头部
  if (!apiKey || !apiSecret) {
    console.warn('API密钥未设置，使用基本头部')
    return {
      'Content-Type': 'application/json'
    }
  }
  
  return {
    'Authorization': `token ${apiKey}:${apiSecret}`,
    'Content-Type': 'application/json'
  }
}

// 获取AI Agent列表
export const getAgentsApi = async (): Promise<AIAgent[]> => {
  try {
    const url = `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.get_local_ai_agents_list`
    
    const requestData = {
      filters: [],
      fields: ['name', 'agent_name', 'status', 'enabled', 'trigger_mode', 'trigger_time', 'progress', 'ai_repeat', 'creation', 'modified', 'modified_by'],
      order_by: 'modified desc',
      limit_start: 0,
      limit_page_length: 20
    }
    
    const response = await axios.post(
      url,
      requestData,
      {
        headers: get_jingrow_api_headers(),
        withCredentials: true
      }
    )
   
    const message = response.data.message
    if (message?.error) {
      const errorMsg = typeof message.error === 'object' ? JSON.stringify(message.error) : message.error
      throw new Error(errorMsg)
    }

    // 根据你提供的API响应，数据直接在message字段中，不是message.data
    const agents = Array.isArray(message) ? message : (message?.data || [])
    return agents
  } catch (error: any) {
    console.error("Error in getAgentsApi:", error)
    throw new Error(error.response?.data?.message || error.message || '获取AI Agent列表失败')
  }
}

// 获取单个AI Agent详情
export const getAgentDetail = async (name: string): Promise<AIAgent> => {
  try {
    const result = await getRecord('Local Ai Agent', name)
    
    if (!result.success) {
      throw new Error(result.message || '获取AI Agent详情失败')
    }
    
    return result.data
  } catch (error: any) {
    throw new Error(error.message || '获取AI Agent详情失败')
  }
}

// 执行AI Agent
export const executeAgentApi = async (name: string): Promise<{ success: boolean; message?: string }> => {
  try {
    const response = await axios.post(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.execute_local_ai_agent`,
      {
        name: name
      },
      {
        headers: get_jingrow_api_headers(),
        withCredentials: true
      }
    )

    const message = response.data.message
    if (message?.error) {
      const errorMsg = typeof message.error === 'object' ? JSON.stringify(message.error) : message.error
      throw new Error(errorMsg)
    }

    return {
      success: message?.success || true,
      message: message?.message || '执行成功'
    }
  } catch (error: any) {
    console.error("Error in executeAgentApi:", error)
    return {
      success: false,
      message: error.response?.data?.message || error.message || '执行失败'
    }
  }
}

// 更新AI Agent
export const updateAgentApi = async (name: string, data: Partial<AIAgent>): Promise<AIAgent> => {
  try {
    const response = await axios.post(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.update_local_ai_agent`,
      {
        name: name,
        data: data
      },
      {
        headers: get_jingrow_api_headers(),
        withCredentials: true
      }
    )

    const message = response.data.message
    if (message?.error) {
      const errorMsg = typeof message.error === 'object' ? JSON.stringify(message.error) : message.error
      throw new Error(errorMsg)
    }

    // 检查更新是否成功
    if (!message?.success) {
      throw new Error(message?.message || '更新失败')
    }

    return message
  } catch (error: any) {
    console.error("Error in updateAgentApi:", error)
    throw new Error(error.response?.data?.message || error.message || '更新AI Agent失败')
  }
}

// 创建智能体（使用通用函数）
export const createAgent = async (data: Record<string, any>): Promise<{ success: boolean; data?: any; message?: string }> => {
  return createRecord('Local Ai Agent', data)
}

// 更新智能体（使用通用函数）
export const updateAgent = async (name: string, data: Record<string, any>): Promise<{ success: boolean; data?: any; message?: string }> => {
  return updateRecord('Local Ai Agent', name, data)
}

// 删除智能体（支持批量删除）
export const deleteAgents = async (names: string[]): Promise<{ success: boolean; message?: string }> => {
  return deleteRecords('Local Ai Agent', names)
}

// 获取智能体选项（参考节点实现）
export const getAgentStatusOptions = () => getFieldSelectOptions('Local Ai Agent', 'status')
export const getAgentTriggerModeOptions = () => getFieldSelectOptions('Local Ai Agent', 'trigger_mode')