import { logger } from '../utils/logger';
import { PricingService, ProfitSnapshot } from './PricingService';
import { ArbitrageService } from './ArbitrageService';
import { CompetitorService } from './CompetitorService';

export interface PricingDecision {
  productId: string;
  currentPrice: number;
  recommendedPrice: number;
  priceChange: number;
  priceChangePercent: number;
  confidence: number;
  reason: string;
  expectedImpact: {
    profitChange: number;
    volumeChange: number;
    competitionPosition: string;
  };
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH';
  shouldExecute: boolean;
}

export interface MarketData {
  productId: string;
  competitorPrices: Array<{ competitor: string; price: number; date: string }>;
  marketDemand: number;
  priceElasticity: number;
  seasonality: number;
  inventoryLevel: number;
  lastPriceChange: string;
}

/**
 * [BIZ_ARB_02] 定价与利润决策闭环 - 自动调价决策
 * Task ID: AI-D001
 * 
 * 功能：
 * 1. 基于套利机会生成调价建议
 * 2. 竞争对手价格分析
 * 3. 需求弹性和季节性分析
 * 4. 利润率红线校验
 * 5. 风险评估与决策建议
 */
export class PricingDecisionService {
  /**
   * 分析市场数据并生成定价决策
   */
  static async analyzeAndDecide(marketData: MarketData): Promise<PricingDecision> {
    const {
      productId,
      competitorPrices,
      marketDemand,
      priceElasticity,
      seasonality,
      inventoryLevel,
      lastPriceChange
    } = marketData;

    logger.info(`[PricingDecision] Analyzing pricing for product ${productId}`);

    // 1. 获取套利机会
    const arbitrageOpportunity = await ArbitrageService.analyzeOpportunity(productId);
    
    // 2. 分析竞争对手价格
    const avgCompetitorPrice = competitorPrices.reduce((sum, p) => sum + p.price, 0) / competitorPrices.length;
    const minCompetitorPrice = Math.min(...competitorPrices.map(p => p.price));
    const maxCompetitorPrice = Math.max(...competitorPrices.map(p => p.price));
    
    // 3. 计算当前利润率
    const currentProfit = await PricingService.calculateNetProfit({
      sellingPrice: marketData.currentPrice,
      purchasePrice: arbitrageOpportunity.costPrice,
      platform: 'Amazon',
      countryCode: 'US',
      logisticsCost: arbitrageOpportunity.logisticsCost,
      isB2B: false
    });

    // 4. 生成推荐价格
    const recommendedPrice = this.calculateRecommendedPrice({
      currentPrice: marketData.currentPrice,
      avgCompetitorPrice,
      minCompetitorPrice,
      marketDemand,
      priceElasticity,
      seasonality,
      inventoryLevel,
      targetProfitRate: 0.25
    });

    // 5. 计算推荐价格的利润率
    const recommendedProfit = await PricingService.calculateNetProfit({
      sellingPrice: recommendedPrice,
      purchasePrice: arbitrageOpportunity.costPrice,
      platform: 'Amazon',
      countryCode: 'US',
      logisticsCost: arbitrageOpportunity.logisticsCost,
      isB2B: false
    });

    // 6. 风险检查
    const riskCheck = PricingService.checkRisk(recommendedProfit, false);

    // 7. 生成决策
    const priceChange = recommendedPrice - marketData.currentPrice;
    const priceChangePercent = (priceChange / marketData.currentPrice) * 100;
    const confidence = this.calculateConfidence({
      competitorPrices,
      marketDemand,
      inventoryLevel
    });

    const decision: PricingDecision = {
      productId,
      currentPrice: marketData.currentPrice,
      recommendedPrice,
      priceChange,
      priceChangePercent,
      confidence,
      reason: this.generateReason({
        arbitrageOpportunity,
        competitorPrices,
        marketDemand,
        priceElasticity,
        seasonality
      }),
      expectedImpact: {
        profitChange: recommendedProfit.netProfit - currentProfit.netProfit,
        volumeChange: this.estimateVolumeChange({
          priceChangePercent,
          priceElasticity,
          marketDemand
        }),
        competitionPosition: this.getCompetitionPosition(recommendedPrice, competitorPrices)
      },
      riskLevel: this.assessRiskLevel({
        priceChangePercent,
        confidence,
        inventoryLevel
      }),
      shouldExecute: riskCheck.level !== 'BLOCK' && confidence > 0.7
    };

    logger.info(`[PricingDecision] Decision generated: ${JSON.stringify({
      productId,
      currentPrice: decision.currentPrice,
      recommendedPrice: decision.recommendedPrice,
      change: decision.priceChangePercent.toFixed(2) + '%',
      confidence: (decision.confidence * 100).toFixed(0) + '%',
      riskLevel: decision.riskLevel,
      shouldExecute: decision.shouldExecute
    })}`);

    return decision;
  }

  /**
   * 计算推荐价格
   */
  private static calculateRecommendedPrice(params: {
    currentPrice: number;
    avgCompetitorPrice: number;
    minCompetitorPrice: number;
    marketDemand: number;
    priceElasticity: number;
    seasonality: number;
    inventoryLevel: number;
    targetProfitRate: number;
  }): number {
    const {
      currentPrice,
      avgCompetitorPrice,
      minCompetitorPrice,
      marketDemand,
      priceElasticity,
      seasonality,
      inventoryLevel,
      targetProfitRate
    } = params;

    // 基础价格：竞争对手平均价格
    let recommendedPrice = avgCompetitorPrice;

    // 需求调整：高需求时可以提价
    if (marketDemand > 0.8) {
      recommendedPrice *= 1.05;
    }

    // 弹性调整：弹性低时可以提价
    if (priceElasticity < 0.5) {
      recommendedPrice *= 1.03;
    }

    // 季节性调整：旺季提价
    if (seasonality > 0.7) {
      recommendedPrice *= 1.04;
    }

    // 库存调整：库存高时降价
    if (inventoryLevel > 0.8) {
      recommendedPrice *= 0.95;
    }

    // 确保不低于最低竞争对手价格
    recommendedPrice = Math.max(recommendedPrice, minCompetitorPrice * 0.98);

    // 确保不超过当前价格太多
    const maxChange = currentPrice * 1.15;
    recommendedPrice = Math.min(recommendedPrice, maxChange);

    return Number(recommendedPrice.toFixed(2));
  }

  /**
   * 计算置信度
   */
  private static calculateConfidence(params: {
    competitorPrices: Array<{ competitor: string; price: number; date: string }>;
    marketDemand: number;
    inventoryLevel: number;
  }): number {
    const { competitorPrices, marketDemand, inventoryLevel } = params;

    let confidence = 0.5;

    // 竞争对手数据越多，置信度越高
    if (competitorPrices.length >= 3) confidence += 0.15;
    else if (competitorPrices.length >= 2) confidence += 0.1;

    // 需求明确时置信度高
    if (marketDemand > 0.7) confidence += 0.1;

    // 库存数据完整时置信度高
    if (inventoryLevel >= 0) confidence += 0.1;

    return Math.min(confidence, 1.0);
  }

  /**
   * 估算销量变化
   */
  private static estimateVolumeChange(params: {
    priceChangePercent: number;
    priceElasticity: number;
    marketDemand: number;
  }): number {
    const { priceChangePercent, priceElasticity, marketDemand } = params;

    // 使用弹性公式：销量变化 = 价格变化 * 弹性 * 需求因子
    const volumeChange = priceChangePercent * priceElasticity * marketDemand;

    return Number(volumeChange.toFixed(2));
  }

  /**
   * 获取竞争位置
   */
  private static getCompetitionPosition(
    price: number,
    competitorPrices: Array<{ competitor: string; price: number; date: string }>
  ): string {
    const sortedPrices = [...competitorPrices, { price, competitor: 'Current' }]
      .sort((a, b) => a.price - b.price);

    const position = sortedPrices.findIndex(p => p.price === price);
    const total = sortedPrices.length;

    if (position === 0) return 'Lowest';
    if (position <= total * 0.25) return 'Low';
    if (position <= total * 0.5) return 'Average';
    if (position <= total * 0.75) return 'High';
    return 'Highest';
  }

  /**
   * 评估风险等级
   */
  private static assessRiskLevel(params: {
    priceChangePercent: number;
    confidence: number;
    inventoryLevel: number;
  }): 'LOW' | 'MEDIUM' | 'HIGH' {
    const { priceChangePercent, confidence, inventoryLevel } = params;

    let riskScore = 0;

    // 价格变化幅度大时风险高
    if (Math.abs(priceChangePercent) > 10) riskScore += 2;
    else if (Math.abs(priceChangePercent) > 5) riskScore += 1;

    // 置信度低时风险高
    if (confidence < 0.6) riskScore += 2;
    else if (confidence < 0.8) riskScore += 1;

    // 库存异常时风险高
    if (inventoryLevel > 0.9) riskScore += 1;

    if (riskScore >= 4) return 'HIGH';
    if (riskScore >= 2) return 'MEDIUM';
    return 'LOW';
  }

  /**
   * 生成调价原因
   */
  private static generateReason(params: {
    arbitrageOpportunity: any;
    competitorPrices: Array<{ competitor: string; price: number; date: string }>;
    marketDemand: number;
    priceElasticity: number;
    seasonality: number;
  }): string {
    const reasons: string[] = [];

    if (params.arbitrageOpportunity.hasOpportunity) {
      reasons.push(`Arbitrage opportunity detected: ${params.arbitrageOpportunity.profitMargin.toFixed(1)}% margin`);
    }

    if (params.marketDemand > 0.8) {
      reasons.push('High market demand detected');
    }

    if (params.seasonality > 0.7) {
      reasons.push('Peak season pricing adjustment');
    }

    if (params.priceElasticity < 0.5) {
      reasons.push('Low price elasticity allows premium pricing');
    }

    if (params.competitorPrices.length > 0) {
      const avgPrice = params.competitorPrices.reduce((sum, p) => sum + p.price, 0) / params.competitorPrices.length;
      reasons.push(`Competitor average price: $${avgPrice.toFixed(2)}`);
    }

    return reasons.join('; ');
  }

  /**
   * 批量分析多个商品
   */
  static async batchAnalyze(marketDataList: MarketData[]): Promise<PricingDecision[]> {
    logger.info(`[PricingDecision] Batch analyzing ${marketDataList.length} products`);

    const decisions = await Promise.all(
      marketDataList.map(data => this.analyzeAndDecide(data))
    );

    const executeCount = decisions.filter(d => d.shouldExecute).length;
    const blockCount = decisions.filter(d => !d.shouldExecute).length;

    logger.info(`[PricingDecision] Batch analysis complete: ${executeCount} recommended, ${blockCount} blocked`);

    return decisions;
  }
}
