/**
 * RAG配置优化工具
 * 提供不同场景下的RAG检索配置优化方案
 */

import { RagGroundingConfig } from '../types/ragGrounding';

export interface RagOptimizationScenario {
  name: string;
  description: string;
  config: Partial<RagGroundingConfig>;
}

/**
 * RAG配置优化器
 */
export class RagConfigOptimizer {
  
  /**
   * 预定义的优化场景
   */
  static readonly SCENARIOS: Record<string, RagOptimizationScenario> = {
    // 高召回率场景 - 获取更多相关数据
    HIGH_RECALL: {
      name: "高召回率",
      description: "降低相关性阈值，增加检索结果数量，适用于需要更多参考信息的场景",
      config: {
        max_retrieval_results: 30,
        relevance_threshold: 0.2,
        include_summary: true,
      }
    },
    
    // 高精度场景 - 获取最相关的数据
    HIGH_PRECISION: {
      name: "高精度",
      description: "提高相关性阈值，减少检索结果数量，适用于需要精确匹配的场景",
      config: {
        max_retrieval_results: 10,
        relevance_threshold: 0.7,
        include_summary: true,
      }
    },
    
    // 平衡场景 - 默认配置
    BALANCED: {
      name: "平衡模式",
      description: "平衡检索数量和相关性，适用于大多数场景",
      config: {
        max_retrieval_results: 20,
        relevance_threshold: 0.4,
        include_summary: true,
      }
    },
    
    // 快速响应场景 - 减少检索数量提高速度
    FAST_RESPONSE: {
      name: "快速响应",
      description: "减少检索结果数量，提高响应速度，适用于实时对话场景",
      config: {
        max_retrieval_results: 8,
        relevance_threshold: 0.5,
        include_summary: false,
      }
    },
    
    // 深度搜索场景 - 最大化检索范围
    DEEP_SEARCH: {
      name: "深度搜索",
      description: "最大化检索结果数量和范围，适用于复杂查询和研究场景",
      config: {
        max_retrieval_results: 50, // Vertex AI Search 最大值
        relevance_threshold: 0.1,
        include_summary: true,
      }
    }
  };

  /**
   * 根据查询类型自动选择最佳配置
   */
  static autoOptimize(query: string, baseConfig: RagGroundingConfig): RagGroundingConfig {
    // 检测查询特征
    const isComplexQuery = query.length > 50 || query.includes('详细') || query.includes('具体');
    const isSimpleQuery = query.length < 20;
    const isComparisonQuery = query.includes('比较') || query.includes('对比') || query.includes('区别');
    const isListQuery = query.includes('有哪些') || query.includes('列举') || query.includes('所有');
    
    let scenario: RagOptimizationScenario;
    
    if (isListQuery || isComparisonQuery) {
      // 列举或比较类查询需要更多数据
      scenario = this.SCENARIOS.HIGH_RECALL;
    } else if (isComplexQuery) {
      // 复杂查询使用深度搜索
      scenario = this.SCENARIOS.DEEP_SEARCH;
    } else if (isSimpleQuery) {
      // 简单查询使用快速响应
      scenario = this.SCENARIOS.FAST_RESPONSE;
    } else {
      // 默认使用平衡模式
      scenario = this.SCENARIOS.BALANCED;
    }
    
    return this.applyScenario(baseConfig, scenario);
  }

  /**
   * 应用优化场景到配置
   */
  static applyScenario(baseConfig: RagGroundingConfig, scenario: RagOptimizationScenario): RagGroundingConfig {
    return {
      ...baseConfig,
      ...scenario.config
    };
  }

  /**
   * 根据用户反馈动态调整配置
   */
  static adjustBasedOnFeedback(
    currentConfig: RagGroundingConfig, 
    feedback: 'too_few_results' | 'too_many_results' | 'irrelevant_results' | 'good'
  ): RagGroundingConfig {
    const adjustedConfig = { ...currentConfig };
    
    switch (feedback) {
      case 'too_few_results':
        // 增加检索数量，降低相关性阈值
        adjustedConfig.max_retrieval_results = Math.min((adjustedConfig.max_retrieval_results || 20) + 10, 50);
        adjustedConfig.relevance_threshold = Math.max((adjustedConfig.relevance_threshold || 0.4) - 0.1, 0.1);
        break;
        
      case 'too_many_results':
        // 减少检索数量
        adjustedConfig.max_retrieval_results = Math.max((adjustedConfig.max_retrieval_results || 20) - 5, 5);
        break;
        
      case 'irrelevant_results':
        // 提高相关性阈值
        adjustedConfig.relevance_threshold = Math.min((adjustedConfig.relevance_threshold || 0.4) + 0.1, 0.9);
        break;
        
      case 'good':
        // 保持当前配置
        break;
    }
    
    return adjustedConfig;
  }

  /**
   * 为特定领域创建过滤器
   */
  static createDomainFilter(domain: 'fashion' | 'general'): string | undefined {
    switch (domain) {
      case 'fashion':
        return 'category: ANY("服装", "搭配", "时尚", "穿搭")';
      case 'general':
      default:
        return undefined;
    }
  }

  /**
   * 获取推荐的配置说明
   */
  static getConfigExplanation(config: RagGroundingConfig): string {
    const maxResults = config.max_retrieval_results || 20;
    const threshold = config.relevance_threshold || 0.4;
    
    let explanation = `当前配置将检索最多 ${maxResults} 个结果，`;
    
    if (threshold < 0.3) {
      explanation += "使用较低的相关性阈值以获取更多可能相关的信息";
    } else if (threshold > 0.6) {
      explanation += "使用较高的相关性阈值以确保结果的精确性";
    } else {
      explanation += "使用平衡的相关性阈值";
    }
    
    if (config.include_summary) {
      explanation += "，并包含结果摘要信息";
    }
    
    return explanation + "。";
  }
}

/**
 * RAG配置预设管理器
 */
export class RagConfigPresets {
  private static readonly STORAGE_KEY = 'rag_config_presets';
  
  /**
   * 保存自定义预设
   */
  static savePreset(name: string, config: RagGroundingConfig): void {
    const presets = this.getPresets();
    presets[name] = config;
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(presets));
  }
  
  /**
   * 获取所有预设
   */
  static getPresets(): Record<string, RagGroundingConfig> {
    const stored = localStorage.getItem(this.STORAGE_KEY);
    return stored ? JSON.parse(stored) : {};
  }
  
  /**
   * 删除预设
   */
  static deletePreset(name: string): void {
    const presets = this.getPresets();
    delete presets[name];
    localStorage.setItem(this.STORAGE_KEY, JSON.stringify(presets));
  }
  
  /**
   * 获取预设
   */
  static getPreset(name: string): RagGroundingConfig | undefined {
    const presets = this.getPresets();
    return presets[name];
  }
}
