import { logger } from '../../utils/logger';
import { FeatureGovernanceService } from '../governance/FeatureGovernanceService';
import db from '../../config/database';

/**
 * [AI_CHAT_01] 智能客服机器人
 * @description 基于大语言模型的智能客服，支持多轮对话、意图识别、知识库集成
 */
export class ChatBotService {
  private static readonly CHAT_TABLE = 'cf_ai_chatbot';
  private static readonly INTENT_TABLE = 'cf_ai_chatbot_intent';

  /**
   * 初始化表结构
   */
  static async initTable() {
    // 创建聊天记录表
    const hasChatTable = await db.schema.hasTable(this.CHAT_TABLE);
    if (!hasChatTable) {
      console.log(`📦 Creating ${this.CHAT_TABLE} table...`);
      await db.schema.createTable(this.CHAT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable();
        table.string('session_id', 100).notNullable();
        table.string('user_message', 1000).notNullable();
        table.string('bot_response', 1000).notNullable();
        table.json('intent_info');
        table.string('status', 16).defaultTo('COMPLETED');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.index(['tenant_id', 'session_id']);
      });
      console.log(`✅ Table ${this.CHAT_TABLE} created`);
    }

    // 创建意图表
    const hasIntentTable = await db.schema.hasTable(this.INTENT_TABLE);
    if (!hasIntentTable) {
      console.log(`📦 Creating ${this.INTENT_TABLE} table...`);
      await db.schema.createTable(this.INTENT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('intent_name', 100).notNullable();
        table.string('description', 500);
        table.json('keywords');
        table.json('responses');
        table.timestamp('created_at').defaultTo(db.fn.now());
        table.unique(['intent_name']);
      });
      console.log(`✅ Table ${this.INTENT_TABLE} created`);
    }
  }

  /**
   * 处理用户消息
   */
  static async handleMessage(params: {
    tenantId: string;
    sessionId: string;
    userMessage: string;
  }): Promise<{
    response: string;
    intent: string;
    confidence: number;
  }> {
    if (!(await FeatureGovernanceService.isEnabled('AI_CHATBOT', params.tenantId))) {
      throw new Error('ChatBot feature is disabled');
    }

    logger.info(`[ChatBotService] Handling message for session ${params.sessionId}`);

    try {
      // 1. 识别意图
      const intentResult = await this.recognizeIntent(params.userMessage);

      // 2. 生成回复
      const response = await this.generateResponse(intentResult.intent, params.userMessage);

      // 3. 存储聊天记录
      await db(this.CHAT_TABLE).insert({
        tenant_id: params.tenantId,
        session_id: params.sessionId,
        user_message: params.userMessage,
        bot_response: response,
        intent_info: JSON.stringify(intentResult),
        status: 'COMPLETED'
      });

      return {
        response,
        intent: intentResult.intent,
        confidence: intentResult.confidence
      };
    } catch (err: any) {
      logger.error(`[ChatBotService] Message handling failed: ${err.message}`);
      throw err;
    }
  }

  /**
   * 识别用户意图
   */
  private static async recognizeIntent(userMessage: string): Promise<{
    intent: string;
    confidence: number;
  }> {
    // 模拟意图识别
    const intents = [
      { name: 'greeting', keywords: ['hello', 'hi', 'hey', 'good morning', 'good afternoon'] },
      { name: 'product_info', keywords: ['product', 'item', 'price', 'cost', 'feature'] },
      { name: 'order_status', keywords: ['order', 'status', 'tracking', 'shipping'] },
      { name: 'return_policy', keywords: ['return', 'refund', 'exchange', 'policy'] },
      { name: 'support', keywords: ['help', 'support', 'assistance', 'problem'] }
    ];

    let bestIntent = 'unknown';
    let bestConfidence = 0;

    for (const intent of intents) {
      const confidence = this.calculateConfidence(userMessage, intent.keywords);
      if (confidence > bestConfidence) {
        bestIntent = intent.name;
        bestConfidence = confidence;
      }
    }

    return {
      intent: bestIntent,
      confidence: bestConfidence
    };
  }

  /**
   * 计算意图匹配置信度
   */
  private static calculateConfidence(userMessage: string, keywords: string[]): number {
    const lowerMessage = userMessage.toLowerCase();
    const matchedKeywords = keywords.filter(keyword => 
      lowerMessage.includes(keyword.toLowerCase())
    );
    return matchedKeywords.length / keywords.length;
  }

  /**
   * 生成回复
   */
  private static async generateResponse(intent: string, userMessage: string): Promise<string> {
    // 基于意图生成回复
    const responses: Record<string, string> = {
      greeting: 'Hello! How can I help you today?',
      product_info: 'Our products are designed with high quality and competitive prices. Would you like more specific information about a particular item?',
      order_status: 'To check your order status, please provide your order number. I can help you track it.',
      return_policy: 'Our return policy allows returns within 30 days of purchase for unused items. Would you like to initiate a return?',
      support: 'I\'m here to help. Please describe your issue in more detail and I\'ll assist you.',
      unknown: 'I understand you have a question. Could you please provide more details so I can better assist you?'
    };

    return responses[intent] || responses.unknown;
  }

  /**
   * 获取聊天历史
   */
  static async getChatHistory(tenantId: string, sessionId: string): Promise<any[]> {
    return db(this.CHAT_TABLE)
      .where({ tenant_id: tenantId, session_id: sessionId })
      .orderBy('created_at', 'asc');
  }

  /**
   * 训练意图模型
   */
  static async trainIntentModel(tenantId: string, trainingData: {
    userMessage: string;
    intent: string;
  }[]) {
    // 模拟模型训练
    logger.info(`[ChatBotService] Training intent model with ${trainingData.length} examples`);
    // 实际实现中，这里可以调用LLM API进行微调
    return { status: 'success', message: 'Model trained successfully' };
  }
}