/**
 * API 性能监控
 * 记录和分析 API 请求性能
 */

interface RequestMetrics {
  url: string
  method: string
  duration: number
  status: number
  timestamp: number
  success: boolean
}

class ApiMonitor {
  private metrics: RequestMetrics[] = []
  private maxMetrics = 100 // 只保留最近 100 条记录

  /**
   * 记录请求指标
   */
  record(metric: RequestMetrics) {
    this.metrics.push(metric)

    // 限制数组大小
    if (this.metrics.length > this.maxMetrics) {
      this.metrics.shift()
    }

    // 开发环境下，慢请求警告
    if (import.meta.env.DEV && metric.duration > 1000) {
      console.warn(`[API 慢请求] ${metric.method} ${metric.url} 耗时 ${metric.duration}ms`)
    }
  }

  /**
   * 获取所有指标
   */
  getMetrics(): RequestMetrics[] {
    return [...this.metrics]
  }

  /**
   * 获取平均响应时间
   */
  getAverageResponseTime(): number {
    if (this.metrics.length === 0) return 0
    const total = this.metrics.reduce((sum, m) => sum + m.duration, 0)
    return Math.round(total / this.metrics.length)
  }

  /**
   * 获取成功率
   */
  getSuccessRate(): number {
    if (this.metrics.length === 0) return 100
    const successCount = this.metrics.filter((m) => m.success).length
    return Math.round((successCount / this.metrics.length) * 100)
  }

  /**
   * 获取最慢的请求
   */
  getSlowestRequests(count = 5): RequestMetrics[] {
    return [...this.metrics]
      .sort((a, b) => b.duration - a.duration)
      .slice(0, count)
  }

  /**
   * 按 URL 分组统计
   */
  getStatsByUrl(): Record<string, { count: number; avgDuration: number; successRate: number }> {
    const urlStats: Record<string, RequestMetrics[]> = {}

    this.metrics.forEach((metric) => {
      if (!urlStats[metric.url]) {
        urlStats[metric.url] = []
      }
      urlStats[metric.url]!.push(metric)
    })

    const result: Record<string, { count: number; avgDuration: number; successRate: number }> = {}

    Object.entries(urlStats).forEach(([url, metrics]) => {
      const totalDuration = metrics.reduce((sum, m) => sum + m.duration, 0)
      const successCount = metrics.filter((m) => m.success).length

      result[url] = {
        count: metrics.length,
        avgDuration: Math.round(totalDuration / metrics.length),
        successRate: Math.round((successCount / metrics.length) * 100),
      }
    })

    return result
  }

  /**
   * 清空指标
   */
  clear() {
    this.metrics = []
  }

  /**
   * 打印性能报告
   */
  printReport() {
    console.group('📊 API 性能报告')
    console.log('总请求数:', this.metrics.length)
    console.log('平均响应时间:', this.getAverageResponseTime(), 'ms')
    console.log('成功率:', this.getSuccessRate(), '%')
    console.log('最慢的 5 个请求:')
    console.table(
      this.getSlowestRequests(5).map((m) => ({
        方法: m.method,
        URL: m.url,
        耗时: `${m.duration}ms`,
        状态: m.status,
      }))
    )
    console.log('按 URL 统计:')
    console.table(this.getStatsByUrl())
    console.groupEnd()
  }
}

// 导出单例
export const apiMonitor = new ApiMonitor()

// 开发环境下暴露到 window 对象，方便调试
if (import.meta.env.DEV) {
  ;(window as any).__apiMonitor = apiMonitor
  console.log('💡 使用 __apiMonitor.printReport() 查看 API 性能报告')
}
