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

// 商户数据接口
export interface MerchantData {
  merchant_id: string;
  company_name: string;
  tenant_id: string;
  tier: 'BASIC' | 'PRO' | 'ENTERPRISE';
  status: 'PENDING' | 'ACTIVE' | 'SUSPENDED' | 'TERMINATED';
  registration_date: Date;
  contact_email: string;
  contact_phone: string;
  business_license: string;
}

// 交易数据接口
export interface TransactionData {
  transaction_id: string;
  merchant_id: string;
  order_id: string;
  amount: number;
  transaction_date: Date;
  transaction_type: 'SALE' | 'REFUND' | 'FEE' | 'SETTLEMENT';
  status: 'PENDING' | 'COMPLETED' | 'FAILED';
}

// 商户价值评估结果接口
export interface MerchantValueResult {
  merchant_id: string;
  company_name: string;
  value_score: number;
  value_level: 'LOW' | 'MEDIUM' | 'HIGH' | 'EXCELLENT';
  total_revenue: number;
  transaction_count: number;
  average_transaction_value: number;
  active_days: number;
  growth_rate: number;
  risk_score: number;
  recommendations: string[];
  factors: {
    [key: string]: number;
  };
  timestamp: Date;
}

// 商户行为数据接口
export interface MerchantBehaviorData {
  merchant_id: string;
  login_history: {
    login_date: Date;
    duration: number; // 登录时长（分钟）
  }[];
  order_history: {
    order_date: Date;
    order_amount: number;
    items_count: number;
  }[];
  feature_usage: {
    feature_id: string;
    usage_count: number;
    last_used: Date;
  }[];
  support_tickets: {
    ticket_id: string;
    created_date: Date;
    priority: 'LOW' | 'MEDIUM' | 'HIGH';
    status: 'OPEN' | 'CLOSED';
  }[];
}

// 商户行为预测结果接口
export interface MerchantBehaviorPrediction {
  merchant_id: string;
  prediction_type: 'ACTIVITY' | 'SALES' | 'RETENTION' | 'RISK';
  prediction_value: number;
  confidence: number;
  factors: {
    [key: string]: number;
  };
  recommendations: string[];
  timestamp: Date;
}

// 结算数据接口
export interface SettlementData {
  settlement_id: string;
  merchant_id: string;
  period_start: Date;
  period_end: Date;
  total_amount: number;
  fee_amount: number;
  net_amount: number;
  status: 'PENDING' | 'PROCESSING' | 'COMPLETED';
  created_date: Date;
}

// 费用数据接口
export interface FeeData {
  fee_id: string;
  merchant_id: string;
  fee_type: 'MONTHLY' | 'TRANSACTION' | 'FEATURE' | 'PENALTY';
  amount: number;
  billing_period: string;
  created_date: Date;
}

// 结算优化建议接口
export interface SettlementOptimization {
  merchant_id: string;
  current_settlement: SettlementData;
  optimization_score: number;
  potential_savings: number;
  recommended_changes: {
    change_type: string;
    description: string;
    impact: number;
  }[];
  fee_analysis: {
    fee_type: string;
    current_amount: number;
    optimal_amount: number;
    savings: number;
  }[];
  timestamp: Date;
}

export default class MerchantAnalysisService {
  private static instance: MerchantAnalysisService;

  static getInstance(): MerchantAnalysisService {
    if (!MerchantAnalysisService.instance) {
      MerchantAnalysisService.instance = new MerchantAnalysisService();
    }
    return MerchantAnalysisService.instance;
  }

  /**
   * AI-MV001: 商户价值评估
   * 基于商户数据和交易数据评估商户价值
   */
  async evaluateMerchantValue(
    merchantData: MerchantData,
    transactionData: TransactionData[],
    trace_id: string
  ): Promise<MerchantValueResult> {
    try {
      logger.info(`[MerchantAnalysisService] Evaluating merchant value: merchantId=${merchantData.merchant_id}, traceId=${trace_id}`);

      // 计算总营收
      const totalRevenue = transactionData
        .filter(t => t.transaction_type === 'SALE' && t.status === 'COMPLETED')
        .reduce((sum, t) => sum + t.amount, 0);

      // 计算交易次数
      const transactionCount = transactionData
        .filter(t => t.status === 'COMPLETED')
        .length;

      // 计算平均交易价值
      const averageTransactionValue = transactionCount > 0 ? totalRevenue / transactionCount : 0;

      // 计算活跃天数
      const activeDays = this.calculateActiveDays(transactionData);

      // 计算增长率
      const growthRate = this.calculateGrowthRate(transactionData);

      // 计算风险评分
      const riskScore = this.calculateRiskScore(merchantData, transactionData);

      // 计算价值评分
      const valueScore = this.calculateValueScore({
        totalRevenue,
        transactionCount,
        averageTransactionValue,
        activeDays,
        growthRate,
        riskScore,
        tier: merchantData.tier,
        status: merchantData.status
      });

      // 确定价值等级
      const valueLevel = this.getValueLevel(valueScore);

      // 生成推荐
      const recommendations = this.generateValueRecommendations(valueLevel, growthRate, riskScore);

      // 计算影响因素
      const factors = {
        revenue: this.normalizeValue(totalRevenue, 0, 1000000) * 30,
        transactionCount: this.normalizeValue(transactionCount, 0, 1000) * 20,
        avgTransactionValue: this.normalizeValue(averageTransactionValue, 0, 10000) * 15,
        activeDays: this.normalizeValue(activeDays, 0, 365) * 10,
        growthRate: this.normalizeValue(growthRate, -1, 2) * 15,
        riskScore: (1 - this.normalizeValue(riskScore, 0, 100)) * 10
      };

      logger.info(`[MerchantAnalysisService] Merchant value evaluation completed: score=${valueScore}, level=${valueLevel}, traceId=${trace_id}`);

      return {
        merchant_id: merchantData.merchant_id,
        company_name: merchantData.company_name,
        value_score: valueScore,
        value_level: valueLevel,
        total_revenue: totalRevenue,
        transaction_count: transactionCount,
        average_transaction_value: averageTransactionValue,
        active_days: activeDays,
        growth_rate: growthRate,
        risk_score: riskScore,
        recommendations,
        factors,
        timestamp: new Date()
      };
    } catch (error: any) {
      logger.error(`[MerchantAnalysisService] Failed to evaluate merchant value: ${error.message}, traceId=${trace_id}`);
      return {
        merchant_id: merchantData.merchant_id,
        company_name: merchantData.company_name,
        value_score: 0,
        value_level: 'LOW',
        total_revenue: 0,
        transaction_count: 0,
        average_transaction_value: 0,
        active_days: 0,
        growth_rate: 0,
        risk_score: 100,
        recommendations: ['无法评估商户价值，数据不足'],
        factors: {},
        timestamp: new Date()
      };
    }
  }

  /**
   * AI-MV002: 商户行为预测
   * 基于历史行为数据预测商户行为
   */
  async predictMerchantBehavior(
    behaviorData: MerchantBehaviorData,
    predictionType: 'ACTIVITY' | 'SALES' | 'RETENTION' | 'RISK',
    trace_id: string
  ): Promise<MerchantBehaviorPrediction> {
    try {
      logger.info(`[MerchantAnalysisService] Predicting merchant behavior: merchantId=${behaviorData.merchant_id}, type=${predictionType}, traceId=${trace_id}`);

      let predictionValue = 0;
      let confidence = 0.5;
      const factors: { [key: string]: number } = {};
      const recommendations: string[] = [];

      switch (predictionType) {
        case 'ACTIVITY':
          predictionValue = this.predictActivity(behaviorData);
          confidence = this.calculateActivityConfidence(behaviorData);
          factors.activity_score = predictionValue;
          recommendations.push(...this.generateActivityRecommendations(predictionValue));
          break;

        case 'SALES':
          predictionValue = this.predictSales(behaviorData);
          confidence = this.calculateSalesConfidence(behaviorData);
          factors.sales_prediction = predictionValue;
          recommendations.push(...this.generateSalesRecommendations(predictionValue));
          break;

        case 'RETENTION':
          predictionValue = this.predictRetention(behaviorData);
          confidence = this.calculateRetentionConfidence(behaviorData);
          factors.retention_score = predictionValue;
          recommendations.push(...this.generateRetentionRecommendations(predictionValue));
          break;

        case 'RISK':
          predictionValue = this.predictRisk(behaviorData);
          confidence = this.calculateRiskConfidence(behaviorData);
          factors.risk_score = predictionValue;
          recommendations.push(...this.generateRiskRecommendations(predictionValue));
          break;
      }

      logger.info(`[MerchantAnalysisService] Behavior prediction completed: type=${predictionType}, value=${predictionValue}, confidence=${confidence}, traceId=${trace_id}`);

      return {
        merchant_id: behaviorData.merchant_id,
        prediction_type: predictionType,
        prediction_value: predictionValue,
        confidence,
        factors,
        recommendations,
        timestamp: new Date()
      };
    } catch (error: any) {
      logger.error(`[MerchantAnalysisService] Failed to predict merchant behavior: ${error.message}, traceId=${trace_id}`);
      return {
        merchant_id: behaviorData.merchant_id,
        prediction_type: predictionType,
        prediction_value: 0,
        confidence: 0.1,
        factors: {},
        recommendations: ['无法预测商户行为，数据不足'],
        timestamp: new Date()
      };
    }
  }

  /**
   * AI-MV003: 智能结算优化
   * 基于结算数据和费用数据提供优化建议
   */
  async optimizeSettlement(
    settlementData: SettlementData,
    feeData: FeeData[],
    trace_id: string
  ): Promise<SettlementOptimization> {
    try {
      logger.info(`[MerchantAnalysisService] Optimizing settlement: merchantId=${settlementData.merchant_id}, settlementId=${settlementData.settlement_id}, traceId=${trace_id}`);

      // 分析费用数据
      const feeAnalysis = this.analyzeFees(feeData);

      // 计算潜在节省
      const potentialSavings = feeAnalysis.reduce((sum, fee) => sum + fee.savings, 0);

      // 生成推荐变更
      const recommendedChanges = this.generateSettlementRecommendations(feeAnalysis, settlementData);

      // 计算优化评分
      const optimizationScore = this.calculateOptimizationScore(potentialSavings, settlementData.total_amount);

      logger.info(`[MerchantAnalysisService] Settlement optimization completed: score=${optimizationScore}, savings=${potentialSavings}, traceId=${trace_id}`);

      return {
        merchant_id: settlementData.merchant_id,
        current_settlement: settlementData,
        optimization_score: optimizationScore,
        potential_savings: potentialSavings,
        recommended_changes: recommendedChanges,
        fee_analysis: feeAnalysis,
        timestamp: new Date()
      };
    } catch (error: any) {
      logger.error(`[MerchantAnalysisService] Failed to optimize settlement: ${error.message}, traceId=${trace_id}`);
      return {
        merchant_id: settlementData.merchant_id,
        current_settlement: settlementData,
        optimization_score: 0,
        potential_savings: 0,
        recommended_changes: [],
        fee_analysis: [],
        timestamp: new Date()
      };
    }
  }

  // 辅助方法
  private calculateActiveDays(transactionData: TransactionData[]): number {
    const activeDates = new Set<string>();
    transactionData.forEach(t => {
      if (t.status === 'COMPLETED') {
        activeDates.add(t.transaction_date.toISOString().split('T')[0]);
      }
    });
    return activeDates.size;
  }

  private calculateGrowthRate(transactionData: TransactionData[]): number {
    if (transactionData.length < 2) return 0;

    // 按月份分组
    const monthlyData: { [month: string]: number } = {};
    transactionData.forEach(t => {
      if (t.transaction_type === 'SALE' && t.status === 'COMPLETED') {
        const month = t.transaction_date.toISOString().substring(0, 7); // YYYY-MM
        monthlyData[month] = (monthlyData[month] || 0) + t.amount;
      }
    });

    // 计算增长率
    const months = Object.keys(monthlyData).sort();
    if (months.length < 2) return 0;

    const currentMonth = months[months.length - 1];
    const previousMonth = months[months.length - 2];
    const currentValue = monthlyData[currentMonth];
    const previousValue = monthlyData[previousMonth];

    return previousValue > 0 ? (currentValue - previousValue) / previousValue : 0;
  }

  private calculateRiskScore(merchantData: MerchantData, transactionData: TransactionData[]): number {
    let riskScore = 0;

    // 状态风险
    if (merchantData.status === 'SUSPENDED' || merchantData.status === 'TERMINATED') {
      riskScore += 30;
    } else if (merchantData.status === 'PENDING') {
      riskScore += 15;
    }

    // 退款风险
    const refundCount = transactionData.filter(t => t.transaction_type === 'REFUND').length;
    const totalCount = transactionData.length;
    if (totalCount > 0) {
      const refundRate = refundCount / totalCount;
      riskScore += refundRate * 40;
    }

    // 失败交易风险
    const failedCount = transactionData.filter(t => t.status === 'FAILED').length;
    if (totalCount > 0) {
      const failedRate = failedCount / totalCount;
      riskScore += failedRate * 30;
    }

    return Math.min(riskScore, 100);
  }

  private calculateValueScore(params: {
    totalRevenue: number;
    transactionCount: number;
    averageTransactionValue: number;
    activeDays: number;
    growthRate: number;
    riskScore: number;
    tier: string;
    status: string;
  }): number {
    let score = 0;

    // 营收得分 (30%)
    score += this.normalizeValue(params.totalRevenue, 0, 1000000) * 30;

    // 交易次数得分 (20%)
    score += this.normalizeValue(params.transactionCount, 0, 1000) * 20;

    // 平均交易价值得分 (15%)
    score += this.normalizeValue(params.averageTransactionValue, 0, 10000) * 15;

    // 活跃天数得分 (10%)
    score += this.normalizeValue(params.activeDays, 0, 365) * 10;

    // 增长率得分 (15%)
    score += this.normalizeValue(params.growthRate, -1, 2) * 15;

    // 风险扣分 (10%)
    score -= (params.riskScore / 100) * 10;

    // 等级加分
    if (params.tier === 'ENTERPRISE') score += 5;
    else if (params.tier === 'PRO') score += 3;

    // 状态加分
    if (params.status === 'ACTIVE') score += 2;

    return Math.max(0, Math.min(score, 100));
  }

  private getValueLevel(score: number): 'LOW' | 'MEDIUM' | 'HIGH' | 'EXCELLENT' {
    if (score >= 80) return 'EXCELLENT';
    if (score >= 60) return 'HIGH';
    if (score >= 40) return 'MEDIUM';
    return 'LOW';
  }

  private generateValueRecommendations(valueLevel: string, growthRate: number, riskScore: number): string[] {
    const recommendations: string[] = [];

    if (valueLevel === 'LOW') {
      recommendations.push('建议提升交易频率和客单价');
      recommendations.push('考虑提供促销活动吸引更多订单');
    } else if (valueLevel === 'EXCELLENT') {
      recommendations.push('建议升级到企业级服务以获得更多权益');
      recommendations.push('考虑成为平台推荐商户');
    }

    if (growthRate < 0) {
      recommendations.push('销售额呈下降趋势，建议分析原因并调整策略');
    } else if (growthRate > 0.5) {
      recommendations.push('销售额增长迅速，建议扩大业务规模');
    }

    if (riskScore > 50) {
      recommendations.push('风险评分较高，建议改善交易质量');
    }

    return recommendations;
  }

  private normalizeValue(value: number, min: number, max: number): number {
    return Math.max(0, Math.min(1, (value - min) / (max - min)));
  }

  // 行为预测方法
  private predictActivity(behaviorData: MerchantBehaviorData): number {
    // 基于登录频率和时长预测活跃度
    const recentLogins = behaviorData.login_history
      .filter(l => (new Date().getTime() - l.login_date.getTime()) / (1000 * 60 * 60 * 24) <= 30);
    
    if (recentLogins.length === 0) return 0;

    const avgLoginFrequency = recentLogins.length / 30;
    const avgLoginDuration = recentLogins.reduce((sum, l) => sum + l.duration, 0) / recentLogins.length;

    return (avgLoginFrequency * 0.6 + avgLoginDuration / 60 * 0.4) * 100;
  }

  private predictSales(behaviorData: MerchantBehaviorData): number {
    // 基于历史订单预测销售额
    const recentOrders = behaviorData.order_history
      .filter(o => (new Date().getTime() - o.order_date.getTime()) / (1000 * 60 * 60 * 24) <= 30);
    
    if (recentOrders.length === 0) return 0;

    const totalRecentSales = recentOrders.reduce((sum, o) => sum + o.order_amount, 0);
    const avgOrderValue = totalRecentSales / recentOrders.length;
    const orderFrequency = recentOrders.length / 30;

    return (totalRecentSales + avgOrderValue * orderFrequency * 30) / 30;
  }

  private predictRetention(behaviorData: MerchantBehaviorData): number {
    // 预测商户留存率
    const loginStreak = this.calculateLoginStreak(behaviorData.login_history);
    const featureUsage = behaviorData.feature_usage.length;
    const supportTickets = behaviorData.support_tickets.filter(t => t.status === 'CLOSED').length;

    return (loginStreak / 30 * 0.5 + featureUsage / 10 * 0.3 + supportTickets / 5 * 0.2) * 100;
  }

  private predictRisk(behaviorData: MerchantBehaviorData): number {
    // 预测商户风险
    const highPriorityTickets = behaviorData.support_tickets.filter(t => t.priority === 'HIGH').length;
    const openTickets = behaviorData.support_tickets.filter(t => t.status === 'OPEN').length;
    const loginAnomalies = this.detectLoginAnomalies(behaviorData.login_history);

    return (highPriorityTickets * 0.4 + openTickets * 0.3 + loginAnomalies * 0.3) * 20;
  }

  private calculateLoginStreak(loginHistory: { login_date: Date; duration: number }[]): number {
    const sortedLogins = loginHistory
      .map(l => l.login_date.toISOString().split('T')[0])
      .sort();

    let streak = 0;
    let currentStreak = 0;
    let lastDate: string | null = null;

    for (const date of sortedLogins) {
      if (!lastDate) {
        currentStreak = 1;
      } else {
        const last = new Date(lastDate);
        const current = new Date(date);
        const diffDays = (current.getTime() - last.getTime()) / (1000 * 60 * 60 * 24);
        
        if (diffDays === 1) {
          currentStreak++;
        } else if (diffDays > 1) {
          currentStreak = 1;
        }
      }
      streak = Math.max(streak, currentStreak);
      lastDate = date;
    }

    return streak;
  }

  private detectLoginAnomalies(loginHistory: { login_date: Date; duration: number }[]): number {
    if (loginHistory.length < 3) return 0;

    const durations = loginHistory.map(l => l.duration);
    const avgDuration = durations.reduce((sum, d) => sum + d, 0) / durations.length;
    const stdDev = Math.sqrt(
      durations.reduce((sum, d) => sum + Math.pow(d - avgDuration, 2), 0) / durations.length
    );

    return loginHistory.filter(l => Math.abs(l.duration - avgDuration) > 2 * stdDev).length;
  }

  private calculateActivityConfidence(behaviorData: MerchantBehaviorData): number {
    return Math.min(1, behaviorData.login_history.length / 30);
  }

  private calculateSalesConfidence(behaviorData: MerchantBehaviorData): number {
    return Math.min(1, behaviorData.order_history.length / 20);
  }

  private calculateRetentionConfidence(behaviorData: MerchantBehaviorData): number {
    return Math.min(1, (behaviorData.login_history.length + behaviorData.feature_usage.length) / 40);
  }

  private calculateRiskConfidence(behaviorData: MerchantBehaviorData): number {
    return Math.min(1, behaviorData.support_tickets.length / 10);
  }

  private generateActivityRecommendations(activityScore: number): string[] {
    const recommendations: string[] = [];
    if (activityScore < 30) {
      recommendations.push('建议增加平台使用频率');
      recommendations.push('定期登录平台查看业务数据');
    } else if (activityScore > 70) {
      recommendations.push('活跃度良好，建议探索更多平台功能');
    }
    return recommendations;
  }

  private generateSalesRecommendations(salesPrediction: number): string[] {
    const recommendations: string[] = [];
    if (salesPrediction < 1000) {
      recommendations.push('销售额较低，建议优化产品 listings');
      recommendations.push('考虑参加平台促销活动');
    } else if (salesPrediction > 10000) {
      recommendations.push('销售额表现良好，建议扩大产品线');
    }
    return recommendations;
  }

  private generateRetentionRecommendations(retentionScore: number): string[] {
    const recommendations: string[] = [];
    if (retentionScore < 40) {
      recommendations.push('留存率较低，建议提升服务质量');
      recommendations.push('定期与客户沟通，了解需求');
    } else if (retentionScore > 80) {
      recommendations.push('留存率良好，建议发展长期客户关系');
    }
    return recommendations;
  }

  private generateRiskRecommendations(riskScore: number): string[] {
    const recommendations: string[] = [];
    if (riskScore > 60) {
      recommendations.push('风险评分较高，建议改善客户服务');
      recommendations.push('及时处理客户投诉和问题');
    } else if (riskScore < 20) {
      recommendations.push('风险评分较低，继续保持良好的业务实践');
    }
    return recommendations;
  }

  // 结算优化方法
  private analyzeFees(feeData: FeeData[]) {
    return feeData.map(fee => {
      let optimalAmount = fee.amount;

      // 根据费用类型计算最优金额
      switch (fee.fee_type) {
        case 'MONTHLY':
          // 企业级商户可能有折扣
          optimalAmount = fee.amount * 0.8;
          break;
        case 'TRANSACTION':
          // 交易量大会有费率优惠
          optimalAmount = fee.amount * 0.9;
          break;
        case 'PENALTY':
          //  penalty fees should be avoided
          optimalAmount = 0;
          break;
      }

      return {
        fee_type: fee.fee_type,
        current_amount: fee.amount,
        optimal_amount: optimalAmount,
        savings: fee.amount - optimalAmount
      };
    });
  }

  private generateSettlementRecommendations(feeAnalysis: any[], settlementData: SettlementData) {
    const recommendations: { change_type: string; description: string; impact: number }[] = [];

    // 检查 penalty fees
    const penaltyFees = feeAnalysis.filter(f => f.fee_type === 'PENALTY');
    if (penaltyFees.length > 0) {
      const totalPenalty = penaltyFees.reduce((sum, f) => sum + f.current_amount, 0);
      recommendations.push({
        change_type: 'PENALTY_AVOIDANCE',
        description: '避免产生 penalty fees',
        impact: totalPenalty
      });
    }

    // 检查 transaction fees
    const transactionFees = feeAnalysis.filter(f => f.fee_type === 'TRANSACTION');
    if (transactionFees.length > 0) {
      const totalTransactionFee = transactionFees.reduce((sum, f) => sum + f.current_amount, 0);
      if (totalTransactionFee > settlementData.total_amount * 0.05) {
        recommendations.push({
          change_type: 'TRANSACTION_FEE_OPTIMIZATION',
          description: '优化交易费用结构',
          impact: totalTransactionFee * 0.1
        });
      }
    }

    // 检查 monthly fees
    const monthlyFees = feeAnalysis.filter(f => f.fee_type === 'MONTHLY');
    if (monthlyFees.length > 0) {
      const totalMonthlyFee = monthlyFees.reduce((sum, f) => sum + f.current_amount, 0);
      if (totalMonthlyFee > 1000) {
        recommendations.push({
          change_type: 'MONTHLY_FEE_REDUCTION',
          description: '协商降低月度费用',
          impact: totalMonthlyFee * 0.2
        });
      }
    }

    return recommendations;
  }

  private calculateOptimizationScore(potentialSavings: number, totalAmount: number): number {
    if (totalAmount === 0) return 0;
    const savingsRatio = potentialSavings / totalAmount;
    return Math.min(100, savingsRatio * 200);
  }

  /**
   * 获取商户分析报告
   */
  async getMerchantAnalysisReport(
    merchantId: string,
    merchantData: MerchantData,
    transactionData: TransactionData[],
    behaviorData: MerchantBehaviorData,
    settlementData: SettlementData,
    feeData: FeeData[],
    trace_id: string
  ) {
    try {
      logger.info(`[MerchantAnalysisService] Generating merchant analysis report: merchantId=${merchantId}, traceId=${trace_id}`);

      // 并行执行所有分析
      const [valueResult, activityPrediction, salesPrediction, retentionPrediction, riskPrediction, optimizationResult] = await Promise.all([
        this.evaluateMerchantValue(merchantData, transactionData, trace_id),
        this.predictMerchantBehavior(behaviorData, 'ACTIVITY', trace_id),
        this.predictMerchantBehavior(behaviorData, 'SALES', trace_id),
        this.predictMerchantBehavior(behaviorData, 'RETENTION', trace_id),
        this.predictMerchantBehavior(behaviorData, 'RISK', trace_id),
        this.optimizeSettlement(settlementData, feeData, trace_id)
      ]);

      return {
        merchant_id: merchantId,
        company_name: merchantData.company_name,
        value_analysis: valueResult,
        behavior_predictions: {
          activity: activityPrediction,
          sales: salesPrediction,
          retention: retentionPrediction,
          risk: riskPrediction
        },
        settlement_optimization: optimizationResult,
        generated_at: new Date()
      };
    } catch (error: any) {
      logger.error(`[MerchantAnalysisService] Failed to generate merchant analysis report: ${error.message}, traceId=${trace_id}`);
      throw error;
    }
  }
}
