/**
 * 测试Dify知识库检索功能
 * 用法: node test-dify-search.js <dataset_id> <query>
 */

const axios = require('axios');
require('dotenv').config();

const DIFY_API_KEY = process.env.DIFY_API_KEY;
const DIFY_API_BASE = process.env.DIFY_API_BASE || 'http://localhost/v1';

async function testDifySearch(datasetId, query) {
  console.log('🔍 测试Dify检索功能');
  console.log('📦 Dataset ID:', datasetId);
  console.log('💬 Query:', query);
  console.log('🔑 API Key:', DIFY_API_KEY ? '✅ 已配置' : '❌ 未配置');
  console.log('🌐 API Base:', DIFY_API_BASE);
  console.log('---');

  try {
    const url = `${DIFY_API_BASE}/datasets/${datasetId}/retrieve`;
    console.log('📡 请求URL:', url);
    
    const response = await axios.post(
      url,
      {
        query: query,
        retrieval_model: {
          search_method: 'semantic_search',
          top_k: 3,
          score_threshold_enabled: true,
          score_threshold: 0.3
        }
      },
      {
        headers: {
          'Authorization': `Bearer ${DIFY_API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );

    console.log('✅ 请求成功！');
    console.log('📊 返回数据:', JSON.stringify(response.data, null, 2));
    console.log('---');
    console.log('📈 统计信息:');
    console.log('  - 记录数量:', response.data.records?.length || 0);
    
    if (response.data.records && response.data.records.length > 0) {
      console.log('  - 第一条相关度:', response.data.records[0].score);
      console.log('  - 第一条内容预览:', response.data.records[0].segment.content.substring(0, 100) + '...');
    } else {
      console.log('  ⚠️ 没有检索到任何记录！');
      console.log('  可能原因：');
      console.log('    1. 文档还在索引中');
      console.log('    2. 索引失败');
      console.log('    3. 查询词与文档内容不匹配');
    }

  } catch (error) {
    console.error('❌ 请求失败！');
    if (error.response) {
      console.error('  状态码:', error.response.status);
      console.error('  错误信息:', error.response.data);
    } else {
      console.error('  错误:', error.message);
    }
  }
}

// 从命令行参数获取dataset_id和query
const datasetId = process.argv[2] || '83555127-ffe4-4232-ba75-67bd8aa7fe71';
const query = process.argv[3] || '阿尔兹海默症的症状';

testDifySearch(datasetId, query);


