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

export interface ProfitSnapshot {
  sellingPrice: number;
  purchasePrice: number;
  platformFee: number;
  logisticsCost: number;
  tax: number;
  fxHedging: number;
  afterSalesLoss: number;
  adAmortization: number;
  netProfit: number;
  roi: number;
  profitRate: number;
  timestamp: number;
}

export interface PricingParams {
  sellingPrice: number;
  purchasePrice: number;
  platform: string;
  countryCode: string;
  logisticsCost: number;
  adBudget?: number;
  afterSalesRate?: number; // 售后损耗率 (默认 0.02)
  isB2B?: boolean;
}

/**
 * [BIZ_ARB_01] 套利净利引擎 (Net Profit Arbitrage Engine)
 * 统一净利计算口径：售价 - 采购 - 平台费 - 物流 - 税费 - 汇率对冲 - 售后损耗 - 广告摊销
 */
export class PricingService {
  private static readonly PLATFORM_FEE_RATES: Record<string, number> = {
    'Amazon': 0.15,
    'Temu': 0.05,
    'TikTok': 0.05,
    'Shopee': 0.08,
    'Lazada': 0.08,
    'Default': 0.10
  };

  /**
   * 统一净利计算逻辑 (BIZ_FIN_03 异步化以支持动态对冲)
   */
  static async calculateNetProfit(params: PricingParams): Promise<ProfitSnapshot> {
    const {
      sellingPrice,
      purchasePrice,
      platform,
      countryCode,
      logisticsCost,
      adBudget = 0,
      afterSalesRate = 0.02,
      isB2B = false
    } = params;

    // 1. 平台费 (Platform Fee)
    const feeRate = this.PLATFORM_FEE_RATES[platform] || this.PLATFORM_FEE_RATES['Default'];
    const platformFee = sellingPrice * feeRate;

    // 2. 调用 TaxService 进行税务计提 (BIZ_FIN_02)
    const taxResult = TaxService.calculateTax({
      countryCode: countryCode,
      baseAmount: sellingPrice,
      currency: 'USD',
      isB2B: isB2B
    });
    const tax = taxResult.totalTax;

    // 3. 汇率对冲 (FX Hedging) - 调用 FXHedgingService 获取动态安全边际 (BIZ_FIN_03)
    const safetyMargin = await FXHedgingService.getDynamicSafetyMargin('USD/CNY');
    const fxHedging = sellingPrice * safetyMargin;

    // 4. 售后损耗 (After-sales Loss)
    const afterSalesLoss = sellingPrice * afterSalesRate;

    // 5. 广告摊销 (Ad Amortization)
    const adAmortization = adBudget;

    // 6. 统一净利公式
    // 净利 = 售价 - 采购 - 平台费 - 物流 - 税费 - 汇率对冲 - 售后损耗 - 广告摊销
    const netProfit = sellingPrice - purchasePrice - platformFee - logisticsCost - tax - fxHedging - afterSalesLoss - adAmortization;

    // 7. ROI 与利润率
    const costBasis = purchasePrice + logisticsCost;
    const roi = costBasis > 0 ? netProfit / costBasis : 0;
    const profitRate = sellingPrice > 0 ? netProfit / sellingPrice : 0;

    const snapshot: ProfitSnapshot = {
      sellingPrice,
      purchasePrice,
      platformFee: Number(platformFee.toFixed(2)),
      logisticsCost,
      tax: Number(tax.toFixed(2)),
      fxHedging: Number(fxHedging.toFixed(2)),
      afterSalesLoss: Number(afterSalesLoss.toFixed(2)),
      adAmortization,
      netProfit: Number(netProfit.toFixed(2)),
      roi: Number(roi.toFixed(4)),
      profitRate: Number(profitRate.toFixed(4)),
      timestamp: Date.now()
    };

    logger.info(`[Pricing] Profit calculated for ${platform}: Net Profit=${snapshot.netProfit}, ROI=${(snapshot.roi * 100).toFixed(2)}%`);
    
    return snapshot;
  }

  /**
   * 风险检查 (BIZ_ARB_01 阈值策略)
   * B2B < 15% 拦截，B2C < 20% 触发风控
   */
  static checkRisk(snapshot: ProfitSnapshot, isB2B: boolean): { isRisk: boolean; message?: string; level: 'BLOCK' | 'WARN' | 'PASS' } {
    const profitRate = snapshot.profitRate;
    
    if (isB2B) {
      if (profitRate < 0.15) {
        return { 
          isRisk: true, 
          message: `B2B profit rate (${(profitRate * 100).toFixed(1)}%) is below 15% threshold`, 
          level: 'BLOCK' 
        };
      }
    } else {
      if (profitRate < 0.20) {
        return { 
          isRisk: true, 
          message: `B2C profit rate (${(profitRate * 100).toFixed(1)}%) is below 20% threshold`, 
          level: 'WARN' 
        };
      }
    }

    return { isRisk: false, level: 'PASS' };
  }

  /**
   * 统一机会评分算法
   * @param profitSnapshot 利润快照
   * @param options 选项
   * @returns 评分 (0-100)
   */
  static calculateOpportunityScore(
    profitSnapshot: ProfitSnapshot,
    options?: { 
      priceDiffPercent?: number; 
      netProfit?: number 
    }
  ): number {
    const profitRateScore = Math.min(profitSnapshot.profitRate * 200, 40);
    const roiScore = Math.min(profitSnapshot.roi * 50, 30);
    
    // 优先使用价格差异，其次使用净利润
    const thirdScore = options?.priceDiffPercent 
      ? Math.min(options.priceDiffPercent, 30)
      : Math.min((options?.netProfit || profitSnapshot.netProfit) / 10, 30);
    
    return Math.round(profitRateScore + roiScore + thirdScore);
  }
}
