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

export interface CarrierRoute {
  carrierName: string;
  serviceType: string; // e.g., 'Express', 'Standard', 'Economy'
  estimatedDays: number;
  baseCost: number;
  fuelSurcharge: number;
  tax: number;
  totalCost: number;
  reliabilityScore: number; // 0-1
}

export interface RouteOptimizationResult {
  recommendedRoute: CarrierRoute;
  alternatives: CarrierRoute[];
  reason: string;
}

/**
 * [BIZ_TRADE_07] 跨境物流最优路由算法 (Logistics Route Optimizer)
 * @description 核心逻辑：基于实时报价、时效要求与历史履约评分，动态选择最优承运商。
 */
export class RouteOptimizerService {
  /**
   * 计算并优化发货路由
   */
  static async optimizeRoute(params: {
    originCountry: string;
    destCountry: string;
    weightKg: number;
    dimensionsCm?: { length: number; width: number; height: number };
    maxDays?: number; // 用户要求的最大时效
    priority: 'COST' | 'SPEED' | 'BALANCED';
  }, tenantId?: string): Promise<RouteOptimizationResult> {
    // Feature Flag Check
    if (!(await FeatureGovernanceService.isEnabled('BIZ_TRADE_ROUTE_OPT', tenantId))) {
      logger.info(`[Logistics] Route optimization is disabled via Feature Flag.`);
      // 返回一个默认的最便宜渠道作为降级方案
      return {
        recommendedRoute: {
          carrierName: 'Standard Shipping',
          serviceType: 'Postal',
          estimatedDays: 15,
          baseCost: 10.0,
          fuelSurcharge: 0,
          tax: 0,
          totalCost: 10.0,
          reliabilityScore: 0.8
        },
        alternatives: [],
        reason: 'Feature BIZ_TRADE_ROUTE_OPT disabled, using default standard shipping.'
      };
    }

    const { originCountry, destCountry, weightKg, priority, maxDays } = params;

    logger.info(`[Logistics] Optimizing route for ${weightKg}kg package: ${originCountry} -> ${destCountry}`);

    // 1. 获取所有可用渠道报价 (Mock 数据，实际应调用各货代 API)
    const availableRoutes: CarrierRoute[] = [
      {
        carrierName: 'DHL',
        serviceType: 'Express',
        estimatedDays: 3,
        baseCost: 25.0,
        fuelSurcharge: 5.0,
        tax: 2.0,
        totalCost: 32.0,
        reliabilityScore: 0.98
      },
      {
        carrierName: 'FedEx',
        serviceType: 'Priority',
        estimatedDays: 4,
        baseCost: 22.0,
        fuelSurcharge: 4.5,
        tax: 1.5,
        totalCost: 28.0,
        reliabilityScore: 0.96
      },
      {
        carrierName: 'YunExpress',
        serviceType: 'Special Line',
        estimatedDays: 8,
        baseCost: 12.0,
        fuelSurcharge: 2.0,
        tax: 1.0,
        totalCost: 15.0,
        reliabilityScore: 0.92
      },
      {
        carrierName: 'China Post',
        serviceType: 'E-Packet',
        estimatedDays: 15,
        baseCost: 8.0,
        fuelSurcharge: 1.0,
        tax: 0.5,
        totalCost: 9.5,
        reliabilityScore: 0.85
      }
    ];

    // 2. 过滤掉不符合时效要求的渠道
    let filteredRoutes = availableRoutes;
    if (maxDays) {
      filteredRoutes = availableRoutes.filter(r => r.estimatedDays <= maxDays);
    }

    if (filteredRoutes.length === 0) {
      throw new Error('No logistics routes available for the given constraints.');
    }

    // 3. 多因子加权排序算法 (Weighting Multi-Factor Sorting)
    const sortedRoutes = [...filteredRoutes].sort((a, b) => {
      if (priority === 'COST') {
        return a.totalCost - b.totalCost;
      } else if (priority === 'SPEED') {
        return a.estimatedDays - b.estimatedDays;
      } else {
        // BALANCED: 综合考虑成本 (50%)、速度 (30%)、可靠性 (20%)
        const scoreA = (1 / a.totalCost) * 0.5 + (1 / a.estimatedDays) * 0.3 + a.reliabilityScore * 0.2;
        const scoreB = (1 / b.totalCost) * 0.5 + (1 / b.estimatedDays) * 0.3 + b.reliabilityScore * 0.2;
        return scoreB - scoreA;
      }
    });

    const recommended = sortedRoutes[0];
    const reason = `Optimized for ${priority} with ${recommended.estimatedDays} days delivery and $${recommended.totalCost} cost.`;

    return {
      recommendedRoute: recommended,
      alternatives: sortedRoutes.slice(1),
      reason
    };
  }

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable('cf_optimized_routes');
    if (!hasTable) {
      logger.info('📦 Creating cf_optimized_routes table...');
      await db.schema.createTable('cf_optimized_routes', (table) => {
        table.string('id', 64).primary();
        table.string('origin', 50).notNullable();
        table.string('destination', 50).notNullable();
        table.json('segments');
        table.float('totalCost');
        table.integer('totalTransitTime');
        table.timestamp('createdAt').defaultTo(db.fn.now());
        table.index(['origin', 'destination']);
      });
    }
  }
}
