import { logger } from '../utils/logger';

export interface TransportLeg {
  mode: 'SEA' | 'AIR' | 'LAND' | 'RAIL';
  origin: string;
  destination: string;
  days: number;
  cost: number;
  carbonEmissions: number; // kg CO2
}

export interface MultiModalPath {
  id: string;
  legs: TransportLeg[];
  totalDays: number;
  totalCost: number;
  totalCarbon: number;
  riskScore: number; // 0-100
}

/**
 * [BIZ_TRADE_08] 跨境多式联运路径模拟与比价引擎
 * @description 实现海陆空多模态路径计算与成本预估，支持 ESG (碳排放) 评估
 */
export class PathSimulatorService {
  /**
   * 模拟多式联运路径
   */
  static async simulatePath(origin: string, destination: string, weightKg: number): Promise<MultiModalPath[]> {
    logger.info(`[PathSimulator] Simulating paths from ${origin} to ${destination} for ${weightKg}kg`);

    // 1. 模拟方案 A：海铁联运 (Cost Efficient)
    const seaRailPath: MultiModalPath = {
      id: 'path_sea_rail',
      legs: [
        { mode: 'SEA', origin: 'Shanghai', destination: 'Los Angeles', days: 15, cost: weightKg * 1.5, carbonEmissions: weightKg * 0.5 },
        { mode: 'RAIL', origin: 'Los Angeles', destination: 'Chicago', days: 3, cost: weightKg * 0.8, carbonEmissions: weightKg * 0.1 }
      ],
      totalDays: 18,
      totalCost: weightKg * 2.3,
      totalCarbon: weightKg * 0.6,
      riskScore: 15
    };

    // 2. 模拟方案 B：空卡联运 (Time Sensitive)
    const airTruckPath: MultiModalPath = {
      id: 'path_air_truck',
      legs: [
        { mode: 'AIR', origin: 'Shanghai', destination: 'New York', days: 2, cost: weightKg * 8.5, carbonEmissions: weightKg * 4.2 },
        { mode: 'LAND', origin: 'New York', destination: 'Chicago', days: 1, cost: weightKg * 0.5, carbonEmissions: weightKg * 0.2 }
      ],
      totalDays: 3,
      totalCost: weightKg * 9.0,
      totalCarbon: weightKg * 4.4,
      riskScore: 5
    };

    // 3. 模拟方案 C：纯海运 (Ultra Low Cost)
    const pureSeaPath: MultiModalPath = {
      id: 'path_pure_sea',
      legs: [
        { mode: 'SEA', origin: 'Shanghai', destination: 'New York', days: 35, cost: weightKg * 1.2, carbonEmissions: weightKg * 0.8 }
      ],
      totalDays: 35,
      totalCost: weightKg * 1.2,
      totalCarbon: weightKg * 0.8,
      riskScore: 25
    };

    return [seaRailPath, airTruckPath, pureSeaPath].sort((a, b) => a.totalCost - b.totalCost);
  }

  /**
   * 推荐最优路径
   */
  static async recommendBestPath(origin: string, destination: string, weightKg: number, strategy: 'COST' | 'TIME' | 'ESG'): Promise<MultiModalPath> {
    const paths = await this.simulatePath(origin, destination, weightKg);
    
    switch (strategy) {
      case 'TIME':
        return paths.sort((a, b) => a.totalDays - b.totalDays)[0];
      case 'ESG':
        return paths.sort((a, b) => a.totalCarbon - b.totalCarbon)[0];
      case 'COST':
      default:
        return paths.sort((a, b) => a.totalCost - b.totalCost)[0];
    }
  }
}
