import { IntentResult, IntentType, INTENT_KEYWORDS, INTENT_AGENT_MAPPING } from "@/types/intent";

export class IntentService {
  // 意图识别 - 使用本地关键词匹配（后端intent-recognition函数已删除）
  static async recognizeIntent(
    message: string, 
    context?: {
      conversationHistory?: any[];
      userProfile?: any;
      currentAgent?: string;
    }
  ): Promise<IntentResult> {
    console.log('Running local intent recognition for:', message);
    return this.fallbackIntentRecognition(message);
  }

  // 本地备用意图识别（基于关键词匹配）
  static fallbackIntentRecognition(message: string): IntentResult {
    console.log('Running fallback intent recognition for:', message);
    const lowerMessage = message.toLowerCase();
    
    // 遍历所有意图关键词进行匹配
    for (const [intent, keywords] of Object.entries(INTENT_KEYWORDS)) {
      const matchedKeywords = keywords.filter(keyword => 
        lowerMessage.includes(keyword.toLowerCase())
      );
      
      if (matchedKeywords.length > 0) {
        const confidence = Math.min(0.8, 0.6 + (matchedKeywords.length * 0.1));
        
        console.log(`Matched intent: ${intent} with confidence: ${confidence}, keywords: ${matchedKeywords.join(', ')}`);
        
        return {
          intent,
          confidence,
          entities: this.extractEntities(message, intent),
          suggestedAgent: INTENT_AGENT_MAPPING[intent] || 'general',
          metadata: {
            method: 'keyword_matching',
            matchedKeywords,
            fallback: true
          }
        };
      }
    }

    // 默认返回一般咨询
    console.log('No keywords matched, returning default general_inquiry intent');
    return {
      intent: IntentType.GENERAL_INQUIRY,
      confidence: 0.3,
      entities: {},
      suggestedAgent: 'general',
      metadata: {
        method: 'default',
        fallback: true
      }
    };
  }

  // 简单的实体提取
  static extractEntities(message: string, intent: string): Record<string, any> {
    const entities: Record<string, any> = {};
    
    // 提取商品名称
    const productMatches = message.match(/(手机|电脑|耳机|咖啡机|水杯|运动鞋|笔记本)/g);
    if (productMatches) {
      entities.product_name = productMatches[0];
    }

    // 提取订单号
    const orderMatches = message.match(/#?\d{10,}/g);
    if (orderMatches) {
      entities.order_number = orderMatches[0];
    }

    // 提取价格范围
    const priceMatches = message.match(/(\d+(?:\.\d+)?)\s*(?:元|块|万)/g);
    if (priceMatches) {
      entities.price_range = priceMatches[0];
    }

    // 提取数量
    const quantityMatches = message.match(/(\d+)\s*(?:个|件|台|部)/g);
    if (quantityMatches) {
      entities.quantity = quantityMatches[0];
    }

    return entities;
  }

  // 根据意图和置信度判断是否需要切换Agent
  static shouldSwitchAgent(
    intentResult: IntentResult, 
    currentAgentId: string,
    threshold: number = 0.7
  ): boolean {
    const { suggestedAgent, confidence } = intentResult;
    
    // 如果置信度低，不切换
    if (confidence < threshold) {
      return false;
    }
    
    // 如果建议的Agent与当前Agent相同，不切换
    if (suggestedAgent === currentAgentId) {
      return false;
    }
    
    // 如果当前是general agent，且建议切换到专业agent，则切换
    if (currentAgentId === 'general' && suggestedAgent !== 'general') {
      return true;
    }
    
    // 如果意图变化明显（不同类别），则切换
    const currentAgentIntents = this.getAgentIntents(currentAgentId);
    const isIntentMatch = currentAgentIntents.includes(intentResult.intent);
    
    return !isIntentMatch && confidence > 0.8;
  }

  // 获取特定Agent处理的意图类型
  static getAgentIntents(agentId: string): string[] {
    const agentIntents: Record<string, string[]> = {
      shopping: [
        IntentType.PRODUCT_INQUIRY,
        IntentType.PRODUCT_RECOMMENDATION,
        IntentType.PRODUCT_COMPARISON,
        IntentType.PRICE_INQUIRY
      ],
      service: [
        IntentType.ORDER_STATUS,
        IntentType.ORDER_CANCEL,
        IntentType.ORDER_MODIFY,
        IntentType.AFTER_SALES,
        IntentType.RETURN_REFUND,
        IntentType.WARRANTY,
        IntentType.COMPLAINT,
        IntentType.SHIPPING_INQUIRY,
        IntentType.DELIVERY_TIME,
        IntentType.PAYMENT_ISSUE,
        IntentType.REFUND_STATUS
      ],
      general: [
        IntentType.GREETING,
        IntentType.HELP,
        IntentType.GENERAL_INQUIRY,
        IntentType.ACCOUNT_INFO,
        IntentType.PASSWORD_RESET,
        IntentType.UNKNOWN
      ]
    };
    
    return agentIntents[agentId] || [];
  }

  // 基于意图生成个性化回复
  static generateContextualResponse(intentResult: IntentResult, context?: any): string {
    const { intent, entities, confidence } = intentResult;
    
    // 高置信度的个性化回复
    if (confidence > 0.8) {
      switch (intent) {
        case IntentType.PRODUCT_INQUIRY:
          const productName = entities.product_name;
          return productName 
            ? `我来为您详细介绍${productName}的相关信息：`
            : '我来为您详细介绍这款产品的相关信息：';
            
        case IntentType.PRODUCT_RECOMMENDATION:
          return '根据您的需求，我为您精选了以下热门商品推荐：';
          
        case IntentType.ORDER_STATUS:
          const orderNumber = entities.order_number;
          return orderNumber 
            ? `正在为您查询订单${orderNumber}的最新状态：`
            : '正在为您查询订单的最新状态：';
            
        case IntentType.AFTER_SALES:
          return '我来帮您处理售后问题，请详细描述您遇到的情况：';
          
        case IntentType.RETURN_REFUND:
          return '我来协助您办理退货退款，请提供相关订单信息：';
          
        default:
          return '我来为您提供专业的服务，请告诉我具体需要什么帮助：';
      }
    }
    
    // 中等置信度的通用回复
    if (confidence > 0.5) {
      if (intentResult.suggestedAgent === 'shopping') {
        return '我是购物助理，专门为您提供商品咨询和购买建议。请问您需要什么帮助？';
      } else if (intentResult.suggestedAgent === 'service') {
        return '我是客服助理，专门处理售后和订单问题。请问遇到了什么困难？';
      }
    }
    
    // 低置信度的默认回复
    return '我是智能助理，很高兴为您服务！请告诉我您需要什么帮助？';
  }
}