import axios from 'axios'
import { get_session_api_headers } from './auth'
import { deleteRecords, createRecord, getFieldSelectOptions } from './common'

const jingrowServerUrl = import.meta.env.VITE_JINGROW_SERVER_URL || ''

// 使用通用函数，这里可以保留别名或直接使用
export { getFieldSelectOptions as getNodeFieldSelectOptions } from './common'

export const getNodeGroups = () => getFieldSelectOptions('Local Ai Node', 'node_group')
export const getNodeComponents = () => getFieldSelectOptions('Local Ai Node', 'node_component')
export const getNodeStatusOptions = () => getFieldSelectOptions('Local Ai Node', 'status')

// 检查 node_type 是否已存在（后端返回布尔值）
export const checkNodeTypeExists = async (nodeType: string): Promise<boolean> => {
  if (!nodeType) return false
  try {
    const response = await axios.post(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.check_node_type_exists`,
      { node_type: nodeType },
      { headers: get_session_api_headers(), withCredentials: true }
    )
    // 后端布尔值通常包在 message 中
    return Boolean(response.data?.message === true || response.data === true)
  } catch {
    return false
  }
}

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

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

// 获取节点记录（根据name）
export const getNodeRecord = async (name: string): Promise<any> => {
  try {
    const response = await axios.get(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.get_node_record`,
      { 
        params: { name },
        headers: get_session_api_headers(), 
        withCredentials: true 
      }
    )
    return response.data?.message || response.data
  } catch (error) {
    console.error('获取节点记录失败:', error)
    throw error
  }
}

// 更新节点
export const updateNode = async (name: string, nodeData: any): Promise<any> => {
  try {
    const response = await axios.post(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.update_node`,
      { name, node_data: nodeData },
      { headers: get_session_api_headers(), withCredentials: true }
    )
    return response.data
  } catch (error) {
    console.error('更新节点失败:', error)
    throw error
  }
}

// 根据节点类型获取节点信息
export const getNodeByType = async (nodeType: string): Promise<any> => {
  try {
    const response = await axios.post(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.get_node_by_type`,
      { node_type: nodeType },
      { headers: get_session_api_headers(), withCredentials: true }
    )
    return response.data?.message || response.data
  } catch (error) {
    console.error('根据类型获取节点失败:', error)
    throw error
  }
}

// 获取节点Schema字段
export const getNodeSchemaFields = async (nodeType: string): Promise<any[]> => {
  try {
    const response = await axios.post(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.get_node_schema_fields`,
      { node_type: nodeType },
      { headers: get_session_api_headers(), withCredentials: true }
    )
    return response.data?.message || []
  } catch (error) {
    console.error('获取节点Schema字段失败:', error)
    return []
  }
}

// 获取节点列表
export const getNodeList = async (page: number = 1, pageSize: number = 10): Promise<any> => {
  try {
    const params = new URLSearchParams({
      page: page.toString(),
      page_size: pageSize.toString()
    })
    
    const response = await axios.get(
      `${jingrowServerUrl}/api/action/jingrow.ai.utils.jlocal.get_node_list?${params}`,
      { headers: get_session_api_headers(), withCredentials: true }
    )
    return response.data?.message || response.data
  } catch (error) {
    console.error('获取节点列表失败:', error)
    throw error
  }
}

export const exportNodeDefinition = async (payload: { metadata: any; schema: any }): Promise<{ success: boolean; path?: string }> => {
  try {
    const response = await axios.post(
      `/jingrow/node-definitions/export`,
      payload,
      { headers: get_session_api_headers(), withCredentials: true }
    )
    return response.data
  } catch (error) {
    console.error('导出节点定义失败:', error)
    throw error
  }
}


// 一键导入本地节点（由后端扫描并创建）
export const importLocalNodes = async (): Promise<{ success: boolean; matched: number; imported: number; skipped_existing: number; errors?: string[] }> => {
  try {
    const response = await axios.post(
      `/jingrow/node-definitions/import-local`,
      {},
      { headers: get_session_api_headers(), withCredentials: true }
    )
    return response.data
  } catch (error) {
    console.error('导入本地节点失败:', error)
    throw error
  }
}

