import axios from 'axios'

// 内部函数：调用文本转向量API
const callEmbeddingApi = async (texts: string[]) => {
  try {
    const response = await axios.post(
      `/jingrow/embedding/batch`, { texts })

    return {
      success: true,
      data: response.data?.data || []
    }
  } catch (error: any) {
    console.error('调用 Embedding API 异常:', error)
    return {
      success: false,
      message: error.response?.data?.detail || error.message || '调用API失败'
    }
  }
}

// 内部函数：向量搜索
const searchVectors = async (
  queryVector: number[],
  collectionName: string = 'knowledge_base',
  limit: number = 10,
  scoreThreshold: number = 0.7
) => {
  try {
    const response = await axios.post(
      `/jingrow/embedding/search`,
      {
        collection_name: collectionName,
        query_vector: queryVector,
        limit,
        score_threshold: scoreThreshold
      },
      {
      }
    )

    return {
      success: true,
      data: response.data?.data || []
    }
  } catch (error: any) {
    console.error('向量搜索失败:', error)
    return {
      success: false,
      message: error.response?.data?.detail || error.message || '搜索失败'
    }
  }
}

/**
 * 文本搜索接口（先转换为向量再搜索）
 * 
 * @param queryText 查询文本
 * @param collectionName 集合名称
 * @param limit 返回结果数量限制
 * @param scoreThreshold 相似度阈值
 * @returns 搜索结果
 */
export const searchText = async (
  queryText: string,
  collectionName: string = 'knowledge_base',
  limit: number = 10,
  scoreThreshold: number = 0.7
): Promise<{
  success: boolean
  data?: Array<{
    id: string
    score: number
    payload: Record<string, any>
  }>
  message?: string
}> => {
  try {
    // 先将查询文本转换为向量
    const embeddingResult = await callEmbeddingApi([queryText])
    if (!embeddingResult.success || !embeddingResult.data?.[0]?.embedding) {
      return {
        success: false,
        message: 'Text to vector conversion failed'
      }
    }

    // 使用向量进行搜索
    return await searchVectors(
      embeddingResult.data[0].embedding,
      collectionName,
      limit,
      scoreThreshold
    )
  } catch (error: any) {
    return {
      success: false,
      message: error.message || ''
    }
  }
}
