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

export interface CongestionIndex {
  portCode: string;
  portName: string;
  congestionLevel: number; // 0-100
  avgWaitDays: number;
  status: 'FLUID' | 'CONGESTED' | 'CRITICAL';
}

/**
 * [BIZ_OPS_160] 全球物流拥堵指数与航线优化建议 (Logistics Routing)
 * @description 核心逻辑：监控全球主要枢纽港口（如 LA, Rotterdam, Ningbo）的拥堵指数，在发生罢工或突发拥堵时建议自动绕路或切换为空运。
 */
export class SeaFreightAdvisor {
  /**
   * 执行航线优化审计
   */
  static async auditRoutes(tenantId: string, indices: CongestionIndex[]): Promise<any> {
    logger.info(`[SeaFreightAdvisor] Auditing routes for tenant: ${tenantId}`);

    try {
      const routingSuggestions = [];

      for (const index of indices) {
        // 1. 识别严重拥堵 (Level > 70)
        if (index.congestionLevel > 70 || index.status === 'CRITICAL') {
          const reason = `Port ${index.portName} (${index.portCode}) is experiencing CRITICAL congestion. ` +
            `Average vessel waiting time has reached ${index.avgWaitDays} days.`;

          // 2. 识别受影响的在途订单
          const affectedOrders = await db('cf_consumer_orders')
            .where({ tenant_id: tenantId, logistic_status: 'IN_TRANSIT' })
            .where('tracking_number', 'like', `%${index.portCode}%`) // 模拟关联港口代码
            .select('id', 'tracking_number');

          if (affectedOrders.length > 0) {
            const advice = `${reason} Affecting ${affectedOrders.length} active shipments. ` +
              `Suggesting: 1. Reroute upcoming shipments to alternative ports; 2. Switch urgent SKUs to Air Freight; 3. Proactively notify consumers of a ${index.avgWaitDays}-day delay.`;

            // 3. [UX_XAI_01] 记录决策证据链
            await DecisionExplainabilityEngine.logDecision({
              tenantId,
              module: 'LOGISTICS_STRATEGY',
              resource_id: index.portCode,
              decisionType: 'ROUTE_FAILOVER_SUGGESTION',
              causalChain: advice,
              factors: [
                { name: 'CongestionLevel', value: index.congestionLevel, weight: 0.7, impact: 'NEGATIVE' },
                { name: 'AffectedOrderCount', value: affectedOrders.length, weight: 0.3, impact: 'NEGATIVE' }
              ],
              traceId: `sea-freight-${Date.now()}`
            });

            routingSuggestions.push({
              port: index.portName,
              affectedCount: affectedOrders.length,
              advice
            });
          }
        }
      }

      return { success: true, count: routingSuggestions.length, routingSuggestions };
    } catch (err: any) {
      logger.error(`[SeaFreightAdvisor][FATAL] Audit failed: ${err.message}`);
      throw {
        category: 'Logic Conflict',
        rootCause: 'Failed to cross-reference port congestion with order flow',
        mitigation: 'Verify order tracking location mapping'
      };
    }
  }
}
