import db from '../../config/database';
import { logger } from '../../utils/logger';
import { SovereignCrisisService } from '../Trade/SovereignCrisisService';
import { CustomerService } from '../Customer/CustomerService';

export interface LogisticAnomaly {
  orderId: string;
  trackingNumber: string;
  type: 'STALLED_TRACKING' | 'CUSTOMS_HOLD' | 'DELIVERY_FAILURE' | 'REROUTED';
  severity: 'LOW' | 'MEDIUM' | 'HIGH';
  lastStatus: string;
  daysSinceUpdate: number;
}

/**
 * [BIZ_LOG_15] 最后一公里派送异常主动预警 (Last-mile AI)
 * @description 核心逻辑：基于 AGI 识别物流轨迹异常（如长时间未更新、清关扣留），自动触发客服话术生成或危机预警。
 */
export class LastMileAIService {
  private static readonly ANOMALY_TABLE = 'cf_logistic_anomalies';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.ANOMALY_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.ANOMALY_TABLE} table...`);
      await db.schema.createTable(this.ANOMALY_TABLE, (table) => {
        table.increments('id').primary();
        table.string('orderId', 64).notNullable();
        table.string('trackingNumber', 64).notNullable();
        table.string('type', 32).notNullable();
        table.string('severity', 16).notNullable();
        table.string('lastStatus', 32);
        table.integer('daysSinceUpdate');
        table.string('resolutionStatus', 20).defaultTo('PENDING'); // PENDING, NOTIFIED, RESOLVED
        table.timestamps(true, true);
        table.index(['orderId', 'type']);
      });
    }
  }

  /**
   * 扫描并识别异常 (通常由定时任务触发)
   */
  static async scanForAnomalies(tenantId: string) {
    logger.info(`[LastMileAI] Scanning for logistic anomalies for tenant: ${tenantId}`);

    // 1. 查找超过 3 天未更新轨迹的订单
    const staleOrders = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId })
      .whereNotIn('logistic_status', ['DELIVERED', 'REFUNDED'])
      .andWhere('last_logistic_update', '<', db.raw('DATE_SUB(NOW(), INTERVAL 3 DAY)'));

    for (const order of staleOrders) {
      await this.processAnomaly({
        orderId: order.id,
        trackingNumber: order.tracking_number || 'N/A',
        type: 'STALLED_TRACKING',
        severity: 'MEDIUM',
        lastStatus: order.logistic_status,
        daysSinceUpdate: 3 // 模拟，实际应根据当前日期计算
      });
    }

    // 2. 查找清关状态异常
    const customsHolds = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, logistic_status: 'CUSTOMS' })
      .andWhere('last_logistic_update', '<', db.raw('DATE_SUB(NOW(), INTERVAL 2 DAY)'));

    for (const order of customsHolds) {
      await this.processAnomaly({
        orderId: order.id,
        trackingNumber: order.tracking_number || 'N/A',
        type: 'CUSTOMS_HOLD',
        severity: 'HIGH',
        lastStatus: 'CUSTOMS',
        daysSinceUpdate: 2
      });
    }
  }

  /**
   * 处理异常逻辑
   */
  private static async processAnomaly(anomaly: LogisticAnomaly) {
    logger.warn(`[LastMileAI] ANOMALY detected: ${anomaly.type} for Order: ${anomaly.orderId}`);

    // 1. 记录到异常表
    await db(this.ANOMALY_TABLE)
      .insert({
        ...anomaly,
        created_at: new Date(),
        updated_at: new Date()
      })
      .onConflict(['orderId', 'type'])
      .merge();

    // 2. 联动 AGI 生成客服话术并通知客户
    const order = await db('cf_consumer_orders').where({ id: anomaly.orderId }).first();
    if (order) {
      const csMessage = this.generateCSMessage(anomaly, order.customer_name);
      
      // 联动 CustomerService (BIZ_CSM_20)
      await CustomerService.createSupportTicket({
        tenantId: order.tenant_id,
        orderId: order.id,
        type: 'LOGISTICS_DELAY',
        message: csMessage,
        priority: anomaly.severity === 'HIGH' ? 'URGENT' : 'NORMAL'
      });
    }

    // 3. 如果是高频异常 (如大面积港口停摆)，触发 SovereignCrisisService
    const count = await db(this.ANOMALY_TABLE)
      .where({ type: anomaly.type, resolutionStatus: 'PENDING' })
      .andWhere('created_at', '>', db.raw('DATE_SUB(NOW(), INTERVAL 1 HOUR)'))
      .count('* as total')
      .first();

    if (count && Number(count.total) > 10) { // 简单阈值：1小时内超过10单同类异常
      await SovereignCrisisService.triggerCrisis({
        type: 'LOGISTICS_HALT',
        severity: 'HIGH',
        affectedTenants: [order.tenant_id],
        description: `Massive logistics stall detected: ${anomaly.type} affecting ${count.total} orders.`,
        status: 'DETECTED'
      });
    }
  }

  /**
   * AGI 驱动的客服话术生成 (Mock)
   */
  private static generateCSMessage(anomaly: LogisticAnomaly, customerName: string): string {
    const templates = {
      'STALLED_TRACKING': `Dear ${customerName}, we noticed your package hasn't updated in 3 days. We're investigating with the carrier.`,
      'CUSTOMS_HOLD': `Dear ${customerName}, your package is currently being processed by customs. It might take slightly longer.`,
      'DELIVERY_FAILURE': `Dear ${customerName}, the delivery attempt failed. Please contact your local post office.`,
      'REROUTED': `Dear ${customerName}, your package has been rerouted due to logistical issues. We'll update you soon.`
    };
    return templates[anomaly.type] || `Dear ${customerName}, there's a slight delay with your order.`;
  }
}
