import { logger } from '../utils/logger';
import BlacklistDatabaseService, { BlacklistRecord } from './BlacklistDatabaseService';

export interface BuyerBehaviorData {
  buyer_id: string;
  platform: string;
  platform_buyer_id: string;
  order_history: {
    order_id: string;
    order_date: Date;
    amount: number;
    status: string;
    items: number;
  }[];
  return_history: {
    return_id: string;
    order_id: string;
    return_date: Date;
    reason: string;
    amount: number;
  }[];
  complaint_history: {
    complaint_id: string;
    complaint_date: Date;
    reason: string;
    status: string;
  }[];
  review_history: {
    review_id: string;
    review_date: Date;
    rating: number;
    content: string;
  }[];
  login_history: {
    login_date: Date;
    ip_address: string;
    device_id: string;
  }[];
  payment_history: {
    payment_id: string;
    payment_date: Date;
    amount: number;
    method: string;
    status: string;
  }[];
}

export interface RiskAssessmentResult {
  risk_score: number;
  risk_level: 'LOW' | 'MEDIUM' | 'HIGH';
  reasons: string[];
  is_malicious: boolean;
  recommendation: string;
  confidence: number;
  factors: {
    [key: string]: number;
  };
}

export interface BlacklistEffectivenessReport {
  total_blacklisted: number;
  total_orders_blocked: number;
  total_loss_prevented: number;
  false_positive_rate: number;
  true_positive_rate: number;
  recall: number;
  precision: number;
  f1_score: number;
  by_platform: {
    [platform: string]: {
      blacklisted: number;
      orders_blocked: number;
      loss_prevented: number;
    };
  };
  by_risk_level: {
    LOW: number;
    MEDIUM: number;
    HIGH: number;
  };
  time_period: {
    start: Date;
    end: Date;
  };
}

export interface AnomalyDetectionResult {
  detected: boolean;
  anomalies: {
    type: string;
    score: number;
    description: string;
  }[];
  risk_score: number;
}

export default class BlacklistAnalysisService {
  private static instance: BlacklistAnalysisService;

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

  async analyzeBuyerBehavior(behaviorData: BuyerBehaviorData, trace_id: string): Promise<RiskAssessmentResult> {
    try {
      logger.info(`[BlacklistAnalysisService] Analyzing buyer behavior: platform=${behaviorData.platform}, buyerId=${behaviorData.platform_buyer_id}, traceId=${trace_id}`);

      let riskScore = 0;
      const reasons: string[] = [];
      const factors: { [key: string]: number } = {};

      // 分析订单历史
      const orderAnalysis = this.analyzeOrderHistory(behaviorData.order_history);
      riskScore += orderAnalysis.score;
      reasons.push(...orderAnalysis.reasons);
      factors.order_history = orderAnalysis.score;

      // 分析退货历史
      const returnAnalysis = this.analyzeReturnHistory(behaviorData.return_history);
      riskScore += returnAnalysis.score;
      reasons.push(...returnAnalysis.reasons);
      factors.return_history = returnAnalysis.score;

      // 分析投诉历史
      const complaintAnalysis = this.analyzeComplaintHistory(behaviorData.complaint_history);
      riskScore += complaintAnalysis.score;
      reasons.push(...complaintAnalysis.reasons);
      factors.complaint_history = complaintAnalysis.score;

      // 分析评价历史
      const reviewAnalysis = this.analyzeReviewHistory(behaviorData.review_history);
      riskScore += reviewAnalysis.score;
      reasons.push(...reviewAnalysis.reasons);
      factors.review_history = reviewAnalysis.score;

      // 分析登录历史
      const loginAnalysis = this.analyzeLoginHistory(behaviorData.login_history);
      riskScore += loginAnalysis.score;
      reasons.push(...loginAnalysis.reasons);
      factors.login_history = loginAnalysis.score;

      // 分析支付历史
      const paymentAnalysis = this.analyzePaymentHistory(behaviorData.payment_history);
      riskScore += paymentAnalysis.score;
      reasons.push(...paymentAnalysis.reasons);
      factors.payment_history = paymentAnalysis.score;

      // 计算最终风险等级
      const riskLevel = this.calculateRiskLevel(riskScore);
      const isMalicious = riskLevel === 'HIGH';
      const recommendation = this.getRecommendation(riskLevel);
      const confidence = this.calculateConfidence(riskScore, behaviorData);

      logger.info(`[BlacklistAnalysisService] Risk assessment completed: score=${riskScore}, level=${riskLevel}, malicious=${isMalicious}, traceId=${trace_id}`);

      return {
        risk_score: riskScore,
        risk_level: riskLevel,
        reasons,
        is_malicious: isMalicious,
        recommendation,
        confidence,
        factors
      };
    } catch (error: any) {
      logger.error(`[BlacklistAnalysisService] Failed to analyze buyer behavior: ${error.message}, traceId=${trace_id}`);
      return {
        risk_score: 0,
        risk_level: 'LOW',
        reasons: [],
        is_malicious: false,
        recommendation: 'No action needed',
        confidence: 0,
        factors: {}
      };
    }
  }

  private analyzeOrderHistory(orders: BuyerBehaviorData['order_history']) {
    let score = 0;
    const reasons: string[] = [];

    if (orders.length === 0) {
      return { score, reasons };
    }

    // 计算订单取消率
    const cancelledOrders = orders.filter(order => order.status === 'CANCELLED' || order.status === 'CANCELLED_BY_BUYER');
    const cancellationRate = cancelledOrders.length / orders.length;
    if (cancellationRate > 0.5) {
      score += 25;
      reasons.push(`High order cancellation rate: ${(cancellationRate * 100).toFixed(1)}%`);
    } else if (cancellationRate > 0.3) {
      score += 15;
      reasons.push(`Moderate order cancellation rate: ${(cancellationRate * 100).toFixed(1)}%`);
    }

    // 分析订单金额异常
    const amounts = orders.map(order => order.amount);
    const avgAmount = amounts.reduce((sum, amount) => sum + amount, 0) / amounts.length;
    const stdDev = this.calculateStandardDeviation(amounts);
    const highValueOrders = orders.filter(order => order.amount > avgAmount + 2 * stdDev);
    if (highValueOrders.length > 0) {
      score += 10;
      reasons.push(`Unusual high-value orders detected`);
    }

    // 分析订单频率
    const orderDates = orders.map(order => order.order_date).sort((a, b) => a.getTime() - b.getTime());
    for (let i = 1; i < orderDates.length; i++) {
      const timeDiff = (orderDates[i].getTime() - orderDates[i-1].getTime()) / (1000 * 60 * 60);
      if (timeDiff < 1) {
        score += 15;
        reasons.push('Rapid consecutive orders detected');
        break;
      }
    }

    return { score, reasons };
  }

  private analyzeReturnHistory(returns: BuyerBehaviorData['return_history']) {
    let score = 0;
    const reasons: string[] = [];

    if (returns.length === 0) {
      return { score, reasons };
    }

    // 计算退货率
    const returnRate = returns.length / (returns.length + 1); // 简化计算
    if (returnRate > 0.7) {
      score += 30;
      reasons.push(`Extremely high return rate: ${(returnRate * 100).toFixed(1)}%`);
    } else if (returnRate > 0.5) {
      score += 20;
      reasons.push(`High return rate: ${(returnRate * 100).toFixed(1)}%`);
    } else if (returnRate > 0.3) {
      score += 10;
      reasons.push(`Moderate return rate: ${(returnRate * 100).toFixed(1)}%`);
    }

    // 分析退货原因
    const suspiciousReasons = ['NOT_AS_DESCRIBED', 'DAMAGED', 'WRONG_ITEM', 'FAKE', 'POOR_QUALITY'];
    const suspiciousReturns = returns.filter(r => suspiciousReasons.includes(r.reason.toUpperCase()));
    if (suspiciousReturns.length > 0) {
      score += 15;
      reasons.push(`Multiple returns with suspicious reasons: ${suspiciousReturns.length}`);
    }

    // 分析退货时间
    for (const returnItem of returns) {
      const returnDate = returnItem.return_date;
      // 检查是否在短时间内多次退货
      const recentReturns = returns.filter(r => {
        const timeDiff = (returnDate.getTime() - r.return_date.getTime()) / (1000 * 60 * 60 * 24);
        return timeDiff > 0 && timeDiff < 7;
      });
      if (recentReturns.length > 2) {
        score += 10;
        reasons.push('Multiple returns within a short period');
        break;
      }
    }

    return { score, reasons };
  }

  private analyzeComplaintHistory(complaints: BuyerBehaviorData['complaint_history']) {
    let score = 0;
    const reasons: string[] = [];

    if (complaints.length === 0) {
      return { score, reasons };
    }

    // 分析投诉数量
    if (complaints.length > 3) {
      score += 25;
      reasons.push(`High number of complaints: ${complaints.length}`);
    } else if (complaints.length > 1) {
      score += 15;
      reasons.push(`Multiple complaints: ${complaints.length}`);
    }

    // 分析投诉状态
    const unresolvedComplaints = complaints.filter(c => c.status !== 'RESOLVED');
    if (unresolvedComplaints.length > 0) {
      score += 10;
      reasons.push(`Unresolved complaints: ${unresolvedComplaints.length}`);
    }

    return { score, reasons };
  }

  private analyzeReviewHistory(reviews: BuyerBehaviorData['review_history']) {
    let score = 0;
    const reasons: string[] = [];

    if (reviews.length === 0) {
      return { score, reasons };
    }

    // 分析评价评分
    const avgRating = reviews.reduce((sum, review) => sum + review.rating, 0) / reviews.length;
    if (avgRating < 2) {
      score += 15;
      reasons.push(`Very low average rating: ${avgRating.toFixed(1)}`);
    } else if (avgRating < 3) {
      score += 10;
      reasons.push(`Low average rating: ${avgRating.toFixed(1)}`);
    }

    // 分析评价内容
    const negativeKeywords = ['fake', 'scam', 'fraud', 'terrible', 'worst', 'refund', 'return', 'never', 'lied', 'cheated'];
    for (const review of reviews) {
      const content = review.content.toLowerCase();
      const negativeMatches = negativeKeywords.filter(keyword => content.includes(keyword));
      if (negativeMatches.length > 0) {
        score += 10;
        reasons.push('Negative review content detected');
        break;
      }
    }

    return { score, reasons };
  }

  private analyzeLoginHistory(logins: BuyerBehaviorData['login_history']) {
    let score = 0;
    const reasons: string[] = [];

    if (logins.length === 0) {
      return { score, reasons };
    }

    // 分析登录频率
    if (logins.length > 10) {
      score += 10;
      reasons.push(`High login frequency: ${logins.length} logins`);
    }

    // 分析IP地址变化
    const uniqueIPs = new Set(logins.map(login => login.ip_address));
    if (uniqueIPs.size > 3) {
      score += 15;
      reasons.push(`Multiple IP addresses detected: ${uniqueIPs.size}`);
    }

    // 分析设备ID变化
    const uniqueDevices = new Set(logins.map(login => login.device_id));
    if (uniqueDevices.size > 2) {
      score += 10;
      reasons.push(`Multiple device IDs detected: ${uniqueDevices.size}`);
    }

    // 分析登录时间异常
    for (const login of logins) {
      const hour = login.login_date.getHours();
      if (hour < 2 || hour > 23) {
        score += 5;
        reasons.push('Unusual login time detected');
        break;
      }
    }

    return { score, reasons };
  }

  private analyzePaymentHistory(payments: BuyerBehaviorData['payment_history']) {
    let score = 0;
    const reasons: string[] = [];

    if (payments.length === 0) {
      return { score, reasons };
    }

    // 分析支付失败
    const failedPayments = payments.filter(payment => payment.status === 'FAILED' || payment.status === 'DECLINED');
    if (failedPayments.length > 2) {
      score += 20;
      reasons.push(`Multiple failed payments: ${failedPayments.length}`);
    } else if (failedPayments.length > 0) {
      score += 10;
      reasons.push(`Failed payments detected: ${failedPayments.length}`);
    }

    // 分析支付方式变化
    const uniqueMethods = new Set(payments.map(payment => payment.method));
    if (uniqueMethods.size > 3) {
      score += 10;
      reasons.push(`Multiple payment methods used: ${uniqueMethods.size}`);
    }

    return { score, reasons };
  }

  private calculateRiskLevel(score: number): 'LOW' | 'MEDIUM' | 'HIGH' {
    if (score >= 70) {
      return 'HIGH';
    } else if (score >= 40) {
      return 'MEDIUM';
    } else {
      return 'LOW';
    }
  }

  private getRecommendation(riskLevel: 'LOW' | 'MEDIUM' | 'HIGH') {
    switch (riskLevel) {
      case 'HIGH':
        return 'Add to blacklist immediately';
      case 'MEDIUM':
        return 'Monitor closely and consider blacklist';
      case 'LOW':
        return 'No action needed';
      default:
        return 'No action needed';
    }
  }

  private calculateConfidence(score: number, behaviorData: BuyerBehaviorData) {
    // 基于数据量和风险分数计算置信度
    const dataPoints = [
      behaviorData.order_history.length,
      behaviorData.return_history.length,
      behaviorData.complaint_history.length,
      behaviorData.review_history.length,
      behaviorData.login_history.length,
      behaviorData.payment_history.length
    ];
    const totalDataPoints = dataPoints.reduce((sum, count) => sum + count, 0);
    const dataConfidence = Math.min(totalDataPoints / 20, 1); // 最多20个数据点达到100%置信度
    const scoreConfidence = Math.min(score / 100, 1); // 风险分数越高，置信度越高
    return (dataConfidence * 0.6 + scoreConfidence * 0.4);
  }

  private calculateStandardDeviation(values: number[]) {
    const mean = values.reduce((sum, value) => sum + value, 0) / values.length;
    const squaredDifferences = values.map(value => Math.pow(value - mean, 2));
    const variance = squaredDifferences.reduce((sum, value) => sum + value, 0) / values.length;
    return Math.sqrt(variance);
  }

  async detectAnomalies(behaviorData: BuyerBehaviorData, trace_id: string): Promise<AnomalyDetectionResult> {
    try {
      logger.info(`[BlacklistAnalysisService] Detecting anomalies: platform=${behaviorData.platform}, buyerId=${behaviorData.platform_buyer_id}, traceId=${trace_id}`);

      const anomalies: AnomalyDetectionResult['anomalies'] = [];
      let riskScore = 0;

      // 检测订单异常
      if (behaviorData.order_history.length > 5) {
        const avgOrderAmount = behaviorData.order_history.reduce((sum, order) => sum + order.amount, 0) / behaviorData.order_history.length;
        const highValueOrders = behaviorData.order_history.filter(order => order.amount > avgOrderAmount * 3);
        if (highValueOrders.length > 0) {
          anomalies.push({
            type: 'HIGH_VALUE_ORDERS',
            score: 0.8,
            description: `Multiple high-value orders detected: ${highValueOrders.length}`
          });
          riskScore += 20;
        }
      }

      // 检测退货异常
      if (behaviorData.return_history.length > 3) {
        anomalies.push({
          type: 'HIGH_RETURN_RATE',
          score: 0.9,
          description: `High return rate: ${behaviorData.return_history.length} returns`
        });
        riskScore += 25;
      }

      // 检测登录异常
      if (behaviorData.login_history.length > 8) {
        const uniqueIPs = new Set(behaviorData.login_history.map(login => login.ip_address));
        if (uniqueIPs.size > 4) {
          anomalies.push({
            type: 'MULTIPLE_LOCATIONS',
            score: 0.7,
            description: `Login from multiple locations: ${uniqueIPs.size} IPs`
          });
          riskScore += 15;
        }
      }

      // 检测支付异常
      const failedPayments = behaviorData.payment_history.filter(payment => payment.status === 'FAILED');
      if (failedPayments.length > 2) {
        anomalies.push({
          type: 'PAYMENT_FAILURES',
          score: 0.6,
          description: `Multiple payment failures: ${failedPayments.length}`
        });
        riskScore += 15;
      }

      logger.info(`[BlacklistAnalysisService] Anomaly detection completed: ${anomalies.length} anomalies detected, riskScore=${riskScore}, traceId=${trace_id}`);

      return {
        detected: anomalies.length > 0,
        anomalies,
        risk_score: riskScore
      };
    } catch (error: any) {
      logger.error(`[BlacklistAnalysisService] Failed to detect anomalies: ${error.message}, traceId=${trace_id}`);
      return {
        detected: false,
        anomalies: [],
        risk_score: 0
      };
    }
  }

  async generateEffectivenessReport(startDate: Date, endDate: Date, tenantId?: string): Promise<BlacklistEffectivenessReport> {
    try {
      logger.info(`[BlacklistAnalysisService] Generating effectiveness report: start=${startDate.toISOString()}, end=${endDate.toISOString()}, tenantId=${tenantId}`);

      // 获取黑名单记录
      const blacklistRecords = await BlacklistDatabaseService.getBlacklistRecords(
        { tenant_id: tenantId, status: 'ACTIVE' },
        10000,
        0
      );

      // 模拟数据 - 实际项目中应从订单系统获取
      const totalOrdersBlocked = blacklistRecords.records.length * 2; // 假设每个黑名单用户平均阻止2个订单
      const totalLossPrevented = blacklistRecords.records.length * 500; // 假设每个阻止的订单平均损失500元

      // 计算平台分布
      const byPlatform: BlacklistEffectivenessReport['by_platform'] = {};
      blacklistRecords.records.forEach(record => {
        if (!byPlatform[record.platform]) {
          byPlatform[record.platform] = {
            blacklisted: 0,
            orders_blocked: 0,
            loss_prevented: 0
          };
        }
        byPlatform[record.platform].blacklisted++;
        byPlatform[record.platform].orders_blocked += 2; // 假设值
        byPlatform[record.platform].loss_prevented += 500; // 假设值
      });

      // 计算风险等级分布
      const byRiskLevel: BlacklistEffectivenessReport['by_risk_level'] = {
        LOW: 0,
        MEDIUM: 0,
        HIGH: 0
      };
      blacklistRecords.records.forEach(record => {
        if (record.risk_score >= 70) {
          byRiskLevel.HIGH++;
        } else if (record.risk_score >= 40) {
          byRiskLevel.MEDIUM++;
        } else {
          byRiskLevel.LOW++;
        }
      });

      // 计算统计指标（模拟数据）
      const falsePositiveRate = 0.05; // 5% 误报率
      const truePositiveRate = 0.92; // 92% 准确率
      const recall = 0.88; // 召回率
      const precision = 0.94; // 精确率
      const f1Score = 2 * (precision * recall) / (precision + recall); // F1分数

      logger.info(`[BlacklistAnalysisService] Effectiveness report generated: totalBlacklisted=${blacklistRecords.records.length}, totalOrdersBlocked=${totalOrdersBlocked}, traceId=none`);

      return {
        total_blacklisted: blacklistRecords.records.length,
        total_orders_blocked: totalOrdersBlocked,
        total_loss_prevented: totalLossPrevented,
        false_positive_rate: falsePositiveRate,
        true_positive_rate: truePositiveRate,
        recall,
        precision,
        f1_score: f1Score,
        by_platform: byPlatform,
        by_risk_level: byRiskLevel,
        time_period: {
          start: startDate,
          end: endDate
        }
      };
    } catch (error: any) {
      logger.error(`[BlacklistAnalysisService] Failed to generate effectiveness report: ${error.message}`);
      return {
        total_blacklisted: 0,
        total_orders_blocked: 0,
        total_loss_prevented: 0,
        false_positive_rate: 0,
        true_positive_rate: 0,
        recall: 0,
        precision: 0,
        f1_score: 0,
        by_platform: {},
        by_risk_level: {
          LOW: 0,
          MEDIUM: 0,
          HIGH: 0
        },
        time_period: {
          start: startDate,
          end: endDate
        }
      };
    }
  }

  async getBehavioralPatterns(tenantId?: string) {
    try {
      logger.info(`[BlacklistAnalysisService] Analyzing behavioral patterns: tenantId=${tenantId}`);

      // 获取所有黑名单记录
      const blacklistRecords = await BlacklistDatabaseService.getBlacklistRecords(
        { tenant_id: tenantId, status: 'ACTIVE' },
        10000,
        0
      );

      // 分析模式
      const patterns = {
        most_common_reasons: this.analyzeCommonReasons(blacklistRecords.records),
        platform_distribution: this.analyzePlatformDistribution(blacklistRecords.records),
        risk_score_distribution: this.analyzeRiskScoreDistribution(blacklistRecords.records),
        time_based_patterns: this.analyzeTimeBasedPatterns(blacklistRecords.records)
      };

      return patterns;
    } catch (error: any) {
      logger.error(`[BlacklistAnalysisService] Failed to get behavioral patterns: ${error.message}`);
      return {
        most_common_reasons: [],
        platform_distribution: {},
        risk_score_distribution: {},
        time_based_patterns: {}
      };
    }
  }

  private analyzeCommonReasons(records: BlacklistRecord[]) {
    const reasonCounts: { [reason: string]: number } = {};
    records.forEach(record => {
      if (record.blacklist_reason) {
        reasonCounts[record.blacklist_reason] = (reasonCounts[record.blacklist_reason] || 0) + 1;
      }
    });
    return Object.entries(reasonCounts)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 5)
      .map(([reason, count]) => ({ reason, count }));
  }

  private analyzePlatformDistribution(records: BlacklistRecord[]) {
    const platformCounts: { [platform: string]: number } = {};
    records.forEach(record => {
      platformCounts[record.platform] = (platformCounts[record.platform] || 0) + 1;
    });
    return platformCounts;
  }

  private analyzeRiskScoreDistribution(records: BlacklistRecord[]) {
    const distribution = {
      low: 0,
      medium: 0,
      high: 0
    };
    records.forEach(record => {
      if (record.risk_score >= 70) {
        distribution.high++;
      } else if (record.risk_score >= 40) {
        distribution.medium++;
      } else {
        distribution.low++;
      }
    });
    return distribution;
  }

  private analyzeTimeBasedPatterns(records: BlacklistRecord[]) {
    const monthlyCounts: { [month: string]: number } = {};
    records.forEach(record => {
      if (record.blacklist_date) {
        const month = record.blacklist_date.toISOString().substring(0, 7); // YYYY-MM
        monthlyCounts[month] = (monthlyCounts[month] || 0) + 1;
      }
    });
    return monthlyCounts;
  }
}
