import { logger } from '../../utils/logger';
import { SupplyChainService } from '../../services/SupplyChainService';
import { AIService } from '../../services/AIService';

export interface SourcingSource {
  platform: '1688' | 'Temu';
  supplierName: string;
  price: number;
  currency: string;
  rating: number; // 0-5
  estimatedDaysToWarehouse: number;
  moq: number; // Minimum Order Quantity
  isDirectFactory: boolean;
  matchConfidence: number;
}

export interface SourcingOptimizationResult {
  recommendedSource: SourcingSource;
  alternatives: SourcingSource[];
  routingReason: string;
  savingsVsMarketAverage: number;
}

/**
 * [BIZ_SUP_15] 多源供应比价与路由优化引擎 (Sourcing Routing Engine)
 * @description 核心逻辑：在 1688、Temu 等多源供应端自动比价，基于价格、评分、时效与起订量动态选择最优采购路径。
 */
export class SourcingRoutingService {
  /**
   * 执行多源比价与路由优化
   */
  static async optimizeSourcing(params: {
    productTitle: string;
    imageUrl?: string;
    targetQuantity: number;
    maxDays?: number;
    priority: 'PRICE' | 'SPEED' | 'QUALITY' | 'BALANCED';
    tenantId?: string;
  }): Promise<SourcingOptimizationResult> {
    logger.info(`[SourcingRouting] Optimizing sourcing for: ${params.productTitle}, Quantity: ${params.targetQuantity}`);

    // 1. 获取各平台供应数据 (模拟调用各平台 API)
    const sources: SourcingSource[] = await this.fetchMultiSourceData(params);

    if (sources.length === 0) {
      throw new Error(`No sourcing options found for: ${params.productTitle}`);
    }

    // 2. 过滤不符合条件的供应源 (如 MOQ 超过目标数量，或时效过慢)
    let filteredSources = sources.filter(s => s.moq <= params.targetQuantity);
    if (params.maxDays !== undefined) {
      filteredSources = filteredSources.filter(s => s.estimatedDaysToWarehouse <= params.maxDays!);
    }

    if (filteredSources.length === 0) {
      logger.warn(`[SourcingRouting] All sources filtered out for ${params.productTitle}. Reverting to original list.`);
      filteredSources = sources; // 降级：如果全部被过滤，返回原始列表进行人工决策
    }

    // 3. AGI 路由评分模型 (Sourcing Routing Model)
    const sortedSources = [...filteredSources].sort((a, b) => {
      const scoreA = this.calculateSourcingScore(a, params.priority);
      const scoreB = this.calculateSourcingScore(b, params.priority);
      return scoreB - scoreA;
    });

    const recommended = sortedSources[0];
    
    // 4. 计算节省额 (对比平均价格)
    const avgPrice = sources.reduce((sum, s) => sum + s.price, 0) / sources.length;
    const savings = (avgPrice - recommended.price) * params.targetQuantity;

    const routingReason = `Selected ${recommended.platform} (${recommended.supplierName}) based on ${params.priority} priority. ` +
      `Price: ${recommended.price} ${recommended.currency}, Rating: ${recommended.rating}, Days: ${recommended.estimatedDaysToWarehouse}.`;

    return {
      recommendedSource: recommended,
      alternatives: sortedSources.slice(1),
      routingReason,
      savingsVsMarketAverage: Number(savings.toFixed(2))
    };
  }

  /**
   * 模拟从 1688 和 Temu 获取数据
   */
  private static async fetchMultiSourceData(params: { 
    productTitle: string; 
    imageUrl?: string 
  }): Promise<SourcingSource[]> {
    // 实际应调用 1688 Open API 或 Temu Sourcing API
    // 此处结合 SupplyChainService 的模拟数据
    
    const results: SourcingSource[] = [
      {
        platform: '1688',
        supplierName: 'Yiwu Smart Manufacturing Co.',
        price: 12.5,
        currency: 'CNY',
        rating: 4.8,
        estimatedDaysToWarehouse: 3,
        moq: 10,
        isDirectFactory: true,
        matchConfidence: 0.95
      },
      {
        platform: '1688',
        supplierName: 'Ningbo Global Trade Ltd.',
        price: 11.8,
        currency: 'CNY',
        rating: 4.2,
        estimatedDaysToWarehouse: 5,
        moq: 50,
        isDirectFactory: true,
        matchConfidence: 0.88
      },
      {
        platform: 'Temu',
        supplierName: 'Direct Sourcing Hub',
        price: 2.1, // USD
        currency: 'USD',
        rating: 4.5,
        estimatedDaysToWarehouse: 7,
        moq: 1,
        isDirectFactory: false,
        matchConfidence: 0.92
      }
    ];

    // 统一货币单位进行比价 (假设 1 USD = 7.2 CNY)
    results.forEach(s => {
      if (s.currency === 'USD') {
        s.price = s.price * 7.2;
        s.currency = 'CNY';
      }
    });

    return results;
  }

  /**
   * 核心评分算法 (Weighting Multi-Factor Scoring)
   */
  private static calculateSourcingScore(source: SourcingSource, priority: string): number {
    const weights = {
      price: 0.4,
      rating: 0.3,
      speed: 0.2,
      factory: 0.1
    };

    if (priority === 'PRICE') {
      weights.price = 0.7; weights.rating = 0.1; weights.speed = 0.1; weights.factory = 0.1;
    } else if (priority === 'SPEED') {
      weights.price = 0.2; weights.rating = 0.1; weights.speed = 0.6; weights.factory = 0.1;
    } else if (priority === 'QUALITY') {
      weights.price = 0.1; weights.rating = 0.6; weights.speed = 0.1; weights.factory = 0.2;
    }

    // 归一化处理 (假设价格 100 为上限，天数 30 为上限，评分为 5)
    const priceScore = Math.max(0, 1 - source.price / 100);
    const speedScore = Math.max(0, 1 - source.estimatedDaysToWarehouse / 30);
    const ratingScore = source.rating / 5;
    const factoryScore = source.isDirectFactory ? 1 : 0;

    return (priceScore * weights.price) + 
           (ratingScore * weights.rating) + 
           (speedScore * weights.speed) + 
           (factoryScore * weights.factory);
  }
}
