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

export interface SupportTicket {
  id: string;
  tenant_id: string;
  customer_id: string;
  subject: string;
  message: string;
  language: string;
  sentiment: 'POSITIVE' | 'NEUTRAL' | 'NEGATIVE' | 'ANGRY';
  status: 'OPEN' | 'PENDING' | 'CLOSED';
  auto_reply_sent: boolean;
  reply_message?: string;
  created_at: Date;
}

/**
 * [BIZ_CSM_20] 多语言 AGI 智能客服 (Support Engine)
 * @description 核心逻辑：实现 RAG 驱动的工单自动回复、情感极性预警及全量多语言支持。
 */
export class SupportService {
  private static readonly TABLE_NAME = 'cf_support_tickets';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('customer_id', 64).notNullable();
        table.string('subject', 255);
        table.text('message');
        table.string('language', 16).defaultTo('en');
        table.string('sentiment', 16).defaultTo('NEUTRAL');
        table.string('status', 16).defaultTo('OPEN');
        table.boolean('auto_reply_sent').defaultTo(false);
        table.text('reply_message');
        table.timestamps(true, true);
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * 处理新工单并触发 AGI 自动回复
   */
  static async processNewTicket(tenantId: string, ticketId: string): Promise<void> {
    const ticket = await db(this.TABLE_NAME).where({ id: ticketId, tenant_id: tenantId }).first();
    if (!ticket) throw new Error(`Ticket ${ticketId} not found`);

    logger.info(`[Support] Processing new ticket ${ticketId} for Tenant: ${tenantId}`);

    // 1. 情感分析 (Sentiment Analysis)
    const sentiment = await this.analyzeSentiment(ticket.message);
    
    // 2. 情感极性预警 (Negative/Angry)
    if (sentiment === 'NEGATIVE' || sentiment === 'ANGRY') {
      logger.warn(`[Support] High risk sentiment detected in ticket ${ticketId}: ${sentiment}`);
    }

    // 3. RAG 驱动自动回复 (AGI Auto-Reply)
    const reply = await this.generateAutoReply(tenantId, ticket.message, ticket.language);
    
    // 4. 更新工单
    await db(this.TABLE_NAME).where({ id: ticketId }).update({
      sentiment,
      auto_reply_sent: true,
      reply_message: reply,
      status: 'PENDING',
      updated_at: new Date()
    });

    logger.info(`[Support] Auto-reply sent for ticket ${ticketId}`);
  }

  /**
   * 情感分析逻辑
   */
  private static async analyzeSentiment(message: string): Promise<SupportTicket['sentiment']> {
    // 实际业务中应调用 LLM (e.g., GPT-4o) 进行分类
    if (message.includes('terrible') || message.includes('angry')) return 'ANGRY';
    if (message.includes('bad') || message.includes('problem')) return 'NEGATIVE';
    return 'NEUTRAL';
  }

  /**
   * RAG 驱动的回复生成 (BIZ_CSM_20)
   */
  private static async generateAutoReply(tenantId: string, message: string, lang: string): Promise<string> {
    // 1. RAG 知识检索 (Retrieval) - 模拟
    const knowledgeBase = [
      'Return policy: 30 days money-back guarantee.',
      'Shipping time: 5-7 business days for international orders.'
    ];

    // 2. LLM 生成 (Generation)
    const greeting = lang === 'zh' ? '您好，感谢联系客服。' : 'Hello, thank you for contacting support.';
    const body = lang === 'zh' ? '关于您的问题，我们正在核查。我们的退货政策是 30 天。' : 'Regarding your issue, we are checking. Our return policy is 30 days.';
    
    return `${greeting} ${body}`;
  }

  /**
   * 获取租户工单统计
   */
  static async getTicketStats(tenantId: string) {
    const stats = await db(this.TABLE_NAME)
      .where({ tenant_id: tenantId })
      .select('status', 'sentiment')
      .count('id as count')
      .groupBy('status', 'sentiment');

    return stats;
  }
}
