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

export interface ArbitrageAnalysis {
  productId: string;
  sourcePrice: number; // 1688 采购价 (CNY)
  targetPrices: {
    platform: string;
    price: number; // 目标平台售价 (USD)
    estimatedProfit: number;
    roi: number;
  }[];
  potentialScore: number;
  recommendation: string;
}

export class ArbitrageService {
  private static readonly EXCHANGE_RATE = 7.2; // CNY to USD

  /**
   * [BIZ_EXT_07] 跨平台利差雷达 (Arbitrage Radar)
   * @description 分析产品在不同平台的利差与 ROI
   */
  static async analyzeArbitrage(productId: string, sourcePrice: number): Promise<ArbitrageAnalysis> {
    logger.info(`Analyzing arbitrage for product: ${productId}, source price: ${sourcePrice} CNY`);

    // 1. 多源价格比对 (Mock 数据，实际需调用采集服务)
    const targetPlatforms = ['Amazon', 'Temu', 'TikTok'];
    const analysis: ArbitrageAnalysis = {
      productId,
      sourcePrice,
      targetPrices: [],
      potentialScore: 0,
      recommendation: ''
    };

    for (const platform of targetPlatforms) {
      // 模拟获取目标平台价格
      const targetPrice = this.mockGetTargetPrice(sourcePrice, platform);
      
      // 使用统一净利引擎
      const sourcePriceUSD = sourcePrice / this.EXCHANGE_RATE;
      const profitSnapshot = await PricingService.calculateNetProfit({
        sellingPrice: targetPrice,
        purchasePrice: sourcePriceUSD,
        platform,
        countryCode: 'US', // 示例默认美国
        logisticsCost: 5.0, // 示例默认物流
        isB2B: false // 默认 B2C
      });

      analysis.targetPrices.push({
        platform,
        price: targetPrice,
        estimatedProfit: profitSnapshot.netProfit,
        roi: profitSnapshot.roi
      });
    }

    // 2. 选品打分引擎
    analysis.potentialScore = this.calculatePotentialScore(analysis);
    analysis.recommendation = analysis.potentialScore > 70 ? 'Highly Recommended' : 'Low Potential';

    return analysis;
  }

  /**
   * @deprecated 使用 PricingService.calculateNetProfit
   */
  private static async calculateNetProfit(sourcePriceCNY: number, targetPriceUSD: number, platform: string) {
    const sourcePriceUSD = sourcePriceCNY / this.EXCHANGE_RATE;
    const snapshot = await PricingService.calculateNetProfit({
      sellingPrice: targetPriceUSD,
      purchasePrice: sourcePriceUSD,
      platform,
      countryCode: 'US',
      logisticsCost: 5.0
    });

    return {
      profit: snapshot.netProfit,
      roi: snapshot.roi
    };
  }

  private static calculatePotentialScore(analysis: ArbitrageAnalysis): number {
    // 基于最高 ROI 和平台覆盖度打分
    const maxROI = Math.max(...analysis.targetPrices.map(p => p.roi));
    let score = maxROI * 100; // 30% ROI -> 30分
    
    if (maxROI > 0.3) score += 40; // 利润达标奖励
    if (analysis.targetPrices.length >= 3) score += 10; // 跨平台能力奖励

    return Math.min(Math.round(score), 100);
  }

  private static mockGetTargetPrice(sourcePriceCNY: number, platform: string): number {
    const sourcePriceUSD = sourcePriceCNY / this.EXCHANGE_RATE;
    const multiplier = platform === 'Amazon' ? 3.5 : 2.2; // 亚马逊溢价更高
    return Number((sourcePriceUSD * multiplier).toFixed(2));
  }
}
