/**
 * 性能追踪器
 */
class PerformanceTracker {
  constructor() {
    this.metrics = [];
    this.currentStep = null;
  }
  
  /**
   * 开始追踪步骤
   */
  startStep(stepName, stepIndex) {
    this.currentStep = {
      name: stepName,
      index: stepIndex,
      startTime: Date.now(),
      startMemory: process.memoryUsage().heapUsed
    };
  }
  
  /**
   * 结束追踪步骤
   */
  endStep(success = true, error = null) {
    if (!this.currentStep) return;
    
    const endTime = Date.now();
    const endMemory = process.memoryUsage().heapUsed;
    
    const metric = {
      ...this.currentStep,
      endTime,
      duration: endTime - this.currentStep.startTime,
      memoryUsed: endMemory - this.currentStep.startMemory,
      success,
      error: error ? error.message : null
    };
    
    this.metrics.push(metric);
    this.currentStep = null;
    
    return metric;
  }
  
  /**
   * 获取统计信息
   */
  getStats() {
    if (this.metrics.length === 0) {
      return null;
    }
    
    const totalDuration = this.metrics.reduce((sum, m) => sum + m.duration, 0);
    const avgDuration = totalDuration / this.metrics.length;
    const successCount = this.metrics.filter(m => m.success).length;
    const failCount = this.metrics.filter(m => !m.success).length;
    
    // 找出最慢的步骤
    const slowestStep = this.metrics.reduce((slowest, current) => 
      current.duration > slowest.duration ? current : slowest
    );
    
    return {
      totalSteps: this.metrics.length,
      totalDuration,
      avgDuration,
      successCount,
      failCount,
      successRate: (successCount / this.metrics.length * 100).toFixed(2) + '%',
      slowestStep: {
        name: slowestStep.name,
        duration: slowestStep.duration
      }
    };
  }
  
  /**
   * 生成报告
   */
  generateReport() {
    const stats = this.getStats();
    if (!stats) return '无性能数据';
    
    let report = '\n========== 性能报告 ==========\n';
    report += `总步骤数: ${stats.totalSteps}\n`;
    report += `总耗时: ${(stats.totalDuration / 1000).toFixed(2)}秒\n`;
    report += `平均耗时: ${stats.avgDuration.toFixed(0)}ms/步骤\n`;
    report += `成功率: ${stats.successRate}\n`;
    report += `最慢步骤: ${stats.slowestStep.name} (${stats.slowestStep.duration}ms)\n`;
    report += '\n步骤明细:\n';
    
    this.metrics.forEach((metric, index) => {
      const status = metric.success ? '✓' : '✗';
      report += `  ${index + 1}. ${status} ${metric.name} - ${metric.duration}ms\n`;
      if (metric.error) {
        report += `     错误: ${metric.error}\n`;
      }
    });
    
    report += '===============================\n';
    return report;
  }
  
  /**
   * 导出为 JSON
   */
  exportJSON() {
    return {
      stats: this.getStats(),
      metrics: this.metrics
    };
  }
}

module.exports = PerformanceTracker;
