/**
 * RAG检索优化使用示例
 * 展示如何使用新的RAG配置优化功能
 */

import { RagGroundingConfig, DEFAULT_RAG_GROUNDING_CONFIG } from '../apps/desktop/src/types/ragGrounding';
import { RagConfigOptimizer } from '../apps/desktop/src/utils/ragConfigOptimizer';
import { queryRagGrounding } from '../apps/desktop/src/services/ragGroundingService';

/**
 * 示例 1: 使用预定义优化场景
 */
async function scenarioBasedOptimization() {
  console.log('=== 场景化优化示例 ===');
  
  const baseConfig = DEFAULT_RAG_GROUNDING_CONFIG;
  
  // 高召回率场景 - 适用于需要更多参考信息的查询
  const highRecallConfig = RagConfigOptimizer.applyScenario(
    baseConfig, 
    RagConfigOptimizer.SCENARIOS.HIGH_RECALL
  );
  
  console.log('高召回率配置:', {
    max_retrieval_results: highRecallConfig.max_retrieval_results,
    relevance_threshold: highRecallConfig.relevance_threshold,
    include_summary: highRecallConfig.include_summary
  });
  
  const result = await queryRagGrounding(
    "请详细介绍各种牛仔裤的搭配方案", 
    { customConfig: highRecallConfig }
  );
  
  if (result.success) {
    console.log('检索到更多相关信息:', result.data?.grounding_metadata?.sources?.length);
  }
}

/**
 * 示例 2: 自动优化配置
 */
async function autoOptimization() {
  console.log('=== 自动优化示例 ===');
  
  const queries = [
    "牛仔裤配什么上衣？", // 简单查询 -> 快速响应模式
    "请详细分析不同场合下牛仔裤的搭配技巧，包括颜色、款式、配饰等方面", // 复杂查询 -> 深度搜索模式
    "有哪些适合春季的牛仔裤搭配方案？", // 列举查询 -> 高召回率模式
    "比较直筒牛仔裤和紧身牛仔裤的搭配区别" // 比较查询 -> 高召回率模式
  ];
  
  for (const query of queries) {
    const optimizedConfig = RagConfigOptimizer.autoOptimize(query, DEFAULT_RAG_GROUNDING_CONFIG);
    
    console.log(`查询: "${query}"`);
    console.log('自动优化配置:', {
      max_retrieval_results: optimizedConfig.max_retrieval_results,
      relevance_threshold: optimizedConfig.relevance_threshold
    });
    
    const result = await queryRagGrounding(query, { customConfig: optimizedConfig });
    
    if (result.success) {
      console.log(`检索结果数量: ${result.data?.grounding_metadata?.sources?.length || 0}`);
      console.log(`响应时间: ${result.totalTime}ms\n`);
    }
  }
}

/**
 * 示例 3: 基于反馈的动态调整
 */
async function feedbackBasedOptimization() {
  console.log('=== 反馈优化示例 ===');
  
  let currentConfig = DEFAULT_RAG_GROUNDING_CONFIG;
  const query = "夏季牛仔裤搭配建议";
  
  // 第一次查询
  let result = await queryRagGrounding(query, { customConfig: currentConfig });
  console.log('初始查询结果数量:', result.data?.grounding_metadata?.sources?.length || 0);
  
  // 模拟用户反馈：结果太少
  currentConfig = RagConfigOptimizer.adjustBasedOnFeedback(currentConfig, 'too_few_results');
  console.log('调整后配置 (结果太少):', {
    max_retrieval_results: currentConfig.max_retrieval_results,
    relevance_threshold: currentConfig.relevance_threshold
  });
  
  // 第二次查询
  result = await queryRagGrounding(query, { customConfig: currentConfig });
  console.log('调整后查询结果数量:', result.data?.grounding_metadata?.sources?.length || 0);
  
  // 模拟用户反馈：结果不相关
  currentConfig = RagConfigOptimizer.adjustBasedOnFeedback(currentConfig, 'irrelevant_results');
  console.log('再次调整后配置 (结果不相关):', {
    max_retrieval_results: currentConfig.max_retrieval_results,
    relevance_threshold: currentConfig.relevance_threshold
  });
  
  // 第三次查询
  result = await queryRagGrounding(query, { customConfig: currentConfig });
  console.log('最终查询结果数量:', result.data?.grounding_metadata?.sources?.length || 0);
}

/**
 * 示例 4: 领域特定过滤器
 */
async function domainSpecificFiltering() {
  console.log('=== 领域过滤示例 ===');
  
  const baseConfig = DEFAULT_RAG_GROUNDING_CONFIG;
  
  // 应用时尚领域过滤器
  const fashionConfig: RagGroundingConfig = {
    ...baseConfig,
    search_filter: RagConfigOptimizer.createDomainFilter('fashion'),
    max_retrieval_results: 25,
    relevance_threshold: 0.4
  };
  
  console.log('时尚领域配置:', {
    search_filter: fashionConfig.search_filter,
    max_retrieval_results: fashionConfig.max_retrieval_results
  });
  
  const result = await queryRagGrounding(
    "职场穿搭建议", 
    { customConfig: fashionConfig }
  );
  
  if (result.success) {
    console.log('领域过滤后的结果数量:', result.data?.grounding_metadata?.sources?.length || 0);
  }
}

/**
 * 示例 5: 性能对比测试
 */
async function performanceComparison() {
  console.log('=== 性能对比示例 ===');
  
  const query = "牛仔裤搭配技巧";
  const configs = [
    { name: '默认配置', config: DEFAULT_RAG_GROUNDING_CONFIG },
    { name: '快速响应', config: RagConfigOptimizer.applyScenario(DEFAULT_RAG_GROUNDING_CONFIG, RagConfigOptimizer.SCENARIOS.FAST_RESPONSE) },
    { name: '高召回率', config: RagConfigOptimizer.applyScenario(DEFAULT_RAG_GROUNDING_CONFIG, RagConfigOptimizer.SCENARIOS.HIGH_RECALL) },
    { name: '深度搜索', config: RagConfigOptimizer.applyScenario(DEFAULT_RAG_GROUNDING_CONFIG, RagConfigOptimizer.SCENARIOS.DEEP_SEARCH) }
  ];
  
  for (const { name, config } of configs) {
    const startTime = Date.now();
    const result = await queryRagGrounding(query, { customConfig: config });
    const endTime = Date.now();
    
    console.log(`${name}:`, {
      检索数量: result.data?.grounding_metadata?.sources?.length || 0,
      响应时间: `${endTime - startTime}ms`,
      配置: {
        max_results: config.max_retrieval_results,
        threshold: config.relevance_threshold
      }
    });
  }
}

/**
 * 示例 6: 配置解释和建议
 */
function configurationGuidance() {
  console.log('=== 配置指导示例 ===');
  
  const scenarios = Object.entries(RagConfigOptimizer.SCENARIOS);
  
  scenarios.forEach(([key, scenario]) => {
    const config = RagConfigOptimizer.applyScenario(DEFAULT_RAG_GROUNDING_CONFIG, scenario);
    const explanation = RagConfigOptimizer.getConfigExplanation(config);
    
    console.log(`${scenario.name}:`);
    console.log(`  描述: ${scenario.description}`);
    console.log(`  配置说明: ${explanation}`);
    console.log(`  适用场景: ${getUseCaseExamples(key)}\n`);
  });
}

function getUseCaseExamples(scenarioKey: string): string {
  const examples = {
    HIGH_RECALL: "复杂查询、研究分析、需要全面信息的场景",
    HIGH_PRECISION: "精确匹配、专业咨询、质量优于数量的场景", 
    BALANCED: "日常对话、一般性查询、大多数应用场景",
    FAST_RESPONSE: "实时聊天、快速问答、移动端应用",
    DEEP_SEARCH: "学术研究、详细分析、专业报告生成"
  };
  
  return examples[scenarioKey as keyof typeof examples] || "通用场景";
}

// 运行示例
async function runAllExamples() {
  try {
    await scenarioBasedOptimization();
    await autoOptimization();
    await feedbackBasedOptimization();
    await domainSpecificFiltering();
    await performanceComparison();
    configurationGuidance();
  } catch (error) {
    console.error('示例运行失败:', error);
  }
}

// 导出示例函数
export {
  scenarioBasedOptimization,
  autoOptimization,
  feedbackBasedOptimization,
  domainSpecificFiltering,
  performanceComparison,
  configurationGuidance,
  runAllExamples
};
