import axios from 'axios'

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

// 获取节点Schema字段
export const getNodeSchemaFields = async (nodeType: string): Promise<any[]> => {
  try {
    const response = await axios.get(
      `/jingrow/node/schema-fields/${encodeURIComponent(nodeType)}`)
    return response.data?.fields || []
  } catch (error) {
    console.error('获取节点Schema字段失败:', error)
    return []
  }
}

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

// 打包节点为zip文件
export const packageNode = async (nodeType: string): Promise<{ blob: Blob; filename: string }> => {
  try {
    const response = await axios.post(
      `/jingrow/node/package/${encodeURIComponent(nodeType)}`,
      {},
      {
        responseType: 'blob'
      }
    )
    
    // 从 Content-Disposition header 中提取文件名
    let filename = `${nodeType}.zip`
    const contentDisposition = response.headers['content-disposition']
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      if (filenameMatch && filenameMatch[1]) {
        filename = filenameMatch[1].replace(/['"]/g, '')
        // 处理 URL 编码的文件名
        try {
          filename = decodeURIComponent(filename)
        } catch {
          // 如果解码失败，使用原始值
        }
      }
    }
    
    return {
      blob: response.data,
      filename
    }
  } catch (error) {
    console.error('打包节点失败:', error)
    throw error
  }
}

// 发布节点到节点市场
export const publishNodeToMarketplace = async (data: {
  node_type: string
  title: string
  subtitle?: string
  description?: string
  file_url: string
  repository_url?: string
  node_image?: string
}): Promise<{ success: boolean; message?: string }> => {
  try {
    const formData = new FormData()
    formData.append('node_type', data.node_type)
    formData.append('title', data.title)
    if (data.subtitle) formData.append('subtitle', data.subtitle)
    if (data.description) formData.append('description', data.description)
    formData.append('file_url', data.file_url)
    if (data.repository_url) formData.append('repository_url', data.repository_url)
    if (data.node_image) formData.append('node_image', data.node_image)
    
    const response = await axios.post(
      `/jingrow/node/publish`,
      formData,
      { 
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }
    )
    return response.data
  } catch (error: any) {
    console.error('发布节点失败:', error)
    throw error
  }
}

