import { api } from './common'

// 统一使用相对路径，通过 Vite 代理转发到后端

// 获取节点Schema字段
export const getNodeSchemaFields = async (nodeType: string): Promise<any[]> => {
  try {
    const res = await api.call('jingrow.ai.utils.jlocal.get_node_schema_fields', {
      node_type: nodeType
    })
    // Jingrow whitelist 函数返回值被包装在 message 字段中
    const data = res?.message || res
    return data?.fields || []
  } catch (error) {
    return []
  }
}

// 一键导入本地节点（由后端扫描并创建）
export const importLocalNodes = async (): Promise<{ success: boolean; matched: number; imported: number; skipped_existing: number; errors?: string[] }> => {
  try {
    const res = await api.call('jingrow.ai.utils.jlocal.import_local_nodes')
    const data = res?.message || res
    return data || { success: false, matched: 0, imported: 0, skipped_existing: 0 }
  } catch (error) {
    console.error('导入本地节点失败:', error)
    throw error
  }
}

// 打包节点为zip文件
export const packageNode = async (nodeType: string): Promise<{ blob: Blob; filename: string }> => {
  try {
    const res = await api.call('jingrow.ai.utils.jlocal.package_node', {
      node_type: nodeType
    })
    
    // Jingrow whitelist 函数返回值被包装在 message 字段中
    const data = res?.message || res
    
    if (!data?.success || !data?.content) {
      throw new Error('打包失败')
    }
    
    // 将base64编码的内容转换为Blob
    const binaryString = atob(data.content)
    const bytes = new Uint8Array(binaryString.length)
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i)
    }
    const blob = new Blob([bytes], { type: 'application/zip' })
    
    return {
      blob,
      filename: data.filename || `${nodeType}.zip`
    }
  } catch (error) {
    console.error('打包节点失败:', error)
    throw error
  }
}

