import db from '../config/database';
import { logger } from '../utils/logger';
import { DecisionExplainabilityEngine } from '../core/ai/DecisionExplainabilityEngine';
import { AdviceService } from '../domains/Strategy/AdviceService';

/**
 * [BIZ_OPS_133] 批量物流异常自动发起纠纷建议 (Auto Dispute)
 * @description 核心逻辑：分析 cf_logistic_telemetry 中的异常点（如长时间未揽收、轨迹中断），自动建议发起纠纷。
 */
export class DisputeAdvisorService {
  private static readonly DISPUTE_AUDIT_TABLE = 'cf_dispute_audit'; // 新增纠纷审计表

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.DISPUTE_AUDIT_TABLE);
    if (!hasTable) {
      await db.schema.createTable(this.DISPUTE_AUDIT_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('order_id', 64).index();
        table.string('tracking_number', 128);
        table.string('anomaly_type', 64);
        table.string('reason', 255);
        table.string('status', 32).defaultTo('PENDING_REVIEW');
        table.timestamp('created_at').defaultTo(db.fn.now());
      });
    }
  }

  /**
   * 分析轨迹异常并生成纠纷建议 (BIZ_OPS_133)
   */
  static async analyzeTrackingAnomalies(tenantId: string): Promise<any> {
    logger.info(`[DisputeAdvisor] Analyzing tracking anomalies for Tenant: ${tenantId}`);

    try {
      // 1. 获取近 30 天的订单及其最新物流状态 (模拟查询)
      const orders = await db('cf_consumer_orders')
        .where({ tenant_id: tenantId })
        .whereIn('logistic_status', ['PENDING_PICKUP', 'IN_TRANSIT'])
        .where('created_at', '>', new Date(Date.now() - 30 * 24 * 3600 * 1000));

      const suggestions = [];

      for (const order of orders) {
        // 2. 检查最后更新时间 (如果超过 5 天未更新，则认为轨迹异常)
        const lastUpdate = order.last_logistic_update || order.created_at;
        const diffDays = (Date.now() - new Date(lastUpdate).getTime()) / (1000 * 3600 * 24);

        if (diffDays > 5) {
          const reason = `No tracking update for ${diffDays.toFixed(1)} days (Threshold: 5 days). Current status: ${order.logistic_status}.`;
          
          // 3. 记录到统一建议包 (AdviceService)
          const suggestionId = await AdviceService.recordAdvice({
            tenantId,
            shopId: order.shop_id || 'DEFAULT',
            traceId: 'dispute-audit-' + Date.now(),
            insight: {
              type: 'LOGISTICS',
              title: `Tracking Anomaly: ${order.tracking_number}`,
              description: reason,
              impact: 'medium',
              confidence: 0.9,
              suggestedAction: 'INITIATE_DISPUTE',
              metadata: { orderId: order.id, trackingNumber: order.tracking_number }
            }
          });

          // 4. [UX_XAI_01] 记录决策证据链
          await DecisionExplainabilityEngine.logDecision({
            tenantId,
            module: 'LOGISTICS_DISPUTE',
            resourceId: String(suggestionId),
            decisionType: 'AUTO_DISPUTE_SUGGESTION',
            causalChain: reason,
            factors: [
              { name: 'DaysSinceLastUpdate', value: diffDays, weight: 0.7, impact: 'NEGATIVE' },
              { name: 'CurrentStatus', value: order.logistic_status, weight: 0.3, impact: 'NEUTRAL' }
            ],
            traceId: 'dispute-audit-' + Date.now()
          });

          suggestions.push({ orderId: order.id, suggestionId, reason });
        }
      }

      return { 
        success: true, 
        count: suggestions.length, 
        suggestions,
        status: 'PENDING_REVIEW' 
      };
    } catch (err: any) {
      logger.error(`[DisputeAdvisor][WARN] Analysis failed: ${err.message}`);
      return { success: false, error: err.message };
    }
  }
}
