/**
 * 性能测试模块 API 调用封装
 *
 * @author czj
 * @date 2026-08-12
 */

import request from '@/utils/request'
import type {
  PerformanceTask,
  PerformanceTaskCreate,
  PerformanceTaskUpdate,
  PerformanceTaskListResponse,
  PerformanceRunRequest,
  PerformanceRunResponse,
  PerformanceSnapshotListResponse,
  PerformanceReportResponse,
  PerformanceExecutionListResponse,
  PerformanceExecutionDetail,
  CurlParseResult,
  PerformanceProjectCreate,
  PerformanceProjectUpdate,
  PerformanceProject,
  PerformanceProjectListResponse,
  PerformanceProjectStats,
  BatchRunRequest,
  BatchRunResponse,
  BatchDetailResponse,
  ProjectReportResponse,
  ProjectReportListResponse,
  AiAnalysisResponse,
} from '@/types/performance'

const BASE = '/api/performance'

// ==================== 任务 CRUD ====================

/** 获取任务列表 */
export function listTasks(params?: {
  page?: number
  pageSize?: number
  status?: string
  /** 按项目过滤；传 null 查未归属任务，不传返回全部 */
  projectId?: string | null
}): Promise<PerformanceTaskListResponse> {
  const queryParams: Record<string, any> = { ...params }
  // camelCase → snake_case: 后端路由 Query 参数名为 project_id
  if (params?.projectId !== undefined) {
    queryParams.project_id = params.projectId
    delete queryParams.projectId
  }
  return request.get(`${BASE}/tasks`, { params: queryParams })
}

/** 获取任务详情 */
export function getTask(id: string): Promise<PerformanceTask> {
  return request.get(`${BASE}/tasks/${id}`)
}

/** 创建任务 */
export function createTask(data: PerformanceTaskCreate): Promise<PerformanceTask> {
  return request.post(`${BASE}/tasks`, data)
}

/** 更新任务 */
export function updateTask(id: string, data: PerformanceTaskUpdate): Promise<PerformanceTask> {
  return request.put(`${BASE}/tasks/${id}`, data)
}

/** 删除任务 */
export function deleteTask(id: string): Promise<void> {
  return request.delete(`${BASE}/tasks/${id}`)
}

// ==================== 执行控制 ====================

/** 执行任务 */
export function runTask(id: string, data?: PerformanceRunRequest): Promise<PerformanceRunResponse> {
  return request.post(`${BASE}/tasks/${id}/run`, data || {})
}

/** 停止任务 */
export function stopTask(id: string): Promise<PerformanceRunResponse> {
  return request.post(`${BASE}/tasks/${id}/stop`)
}

// ==================== 快照与报告 ====================

/** 获取快照数据 */
export function getSnapshots(id: string, params?: {
  page?: number
  pageSize?: number
}): Promise<PerformanceSnapshotListResponse> {
  return request.get(`${BASE}/tasks/${id}/snapshots`, { params })
}

/** 获取报告 */
export function getReport(id: string, executionId?: string): Promise<PerformanceReportResponse> {
  const params: Record<string, any> = {}
  if (executionId) {
    params.execution_id = executionId
  }
  return request.get(`${BASE}/tasks/${id}/report`, { params })
}

/** 获取任务执行结果 */
export function getTaskResults(id: string): Promise<PerformanceTask> {
  return request.get(`${BASE}/tasks/${id}/results`)
}

// ==================== 执行历史 ====================

/** 获取执行历史列表 */
export function listExecutions(params?: {
  taskId?: string
  projectId?: string
  page?: number
  pageSize?: number
}): Promise<PerformanceExecutionListResponse> {
  const queryParams: Record<string, any> = { ...params }
  if (params?.taskId !== undefined) {
    queryParams.task_id = params.taskId
    delete queryParams.taskId
  }
  if (params?.projectId !== undefined) {
    queryParams.project_id = params.projectId
    delete queryParams.projectId
  }
  if (params?.pageSize !== undefined) {
    queryParams.page_size = params.pageSize
    delete queryParams.pageSize
  }
  return request.get(`${BASE}/executions`, { params: queryParams })
}

/** 获取执行记录详情 */
export function getExecutionDetail(executionId: string): Promise<PerformanceExecutionDetail> {
  return request.get(`${BASE}/executions/${executionId}`)
}

/** 获取执行记录报告 */
export function getExecutionReport(executionId: string): Promise<PerformanceReportResponse> {
  return request.get(`${BASE}/executions/${executionId}/report`)
}

/** 获取执行记录快照 */
export function getExecutionSnapshots(executionId: string, params?: {
  page?: number
  pageSize?: number
}): Promise<PerformanceSnapshotListResponse> {
  const queryParams: Record<string, any> = { ...params }
  if (params?.pageSize !== undefined) {
    queryParams.page_size = params.pageSize
    delete queryParams.pageSize
  }
  return request.get(`${BASE}/executions/${executionId}/snapshots`, { params: queryParams })
}

/** 删除执行记录 */
export function deleteExecution(executionId: string): Promise<void> {
  return request.delete(`${BASE}/executions/${executionId}`)
}

// ==================== WebSocket 实时监控 ====================

/** 创建 WebSocket 连接订阅性能测试实时数据 */
export function createPerfMonitorStream(
  taskId: string,
  onSnapshot: (data: any) => void,
  onComplete: (data: any) => void,
  onError?: (error: Event) => void,
  onClose?: () => void,
): WebSocket {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  const ws = new WebSocket(`${protocol}//${host}/api/performance/ws/${taskId}`)

  ws.onmessage = (event) => {
    try {
      const msg = JSON.parse(event.data)
      if (msg.type === 'perf_snapshot') {
        onSnapshot(msg)
      } else if (msg.type === 'perf_complete') {
        onComplete(msg)
      }
    } catch (e) {
      console.error('解析 WebSocket 消息失败', e)
    }
  }

  ws.onerror = (error) => {
    console.error('WebSocket 错误', error)
    onError?.(error)
  }

  ws.onclose = () => {
    onClose?.()
  }

  return ws
}

/** 创建 WebSocket 连接订阅批量执行进度（按批次分组） */
export function createPerfBatchStream(
  batchId: string,
  onProgress: (data: any) => void,
  onError?: (error: Event) => void,
  onClose?: () => void,
): WebSocket {
  const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
  const host = window.location.host
  const ws = new WebSocket(`${protocol}//${host}/api/performance/ws/batch/${batchId}`)

  ws.onmessage = (event) => {
    try {
      const msg = JSON.parse(event.data)
      if (msg.type === 'perf_batch_progress') {
        onProgress(msg)
      }
    } catch (e) {
      console.error('解析批量进度 WebSocket 消息失败', e)
    }
  }

  ws.onerror = (error) => {
    console.error('批量进度 WebSocket 错误', error)
    onError?.(error)
  }

  ws.onclose = () => {
    onClose?.()
  }

  return ws
}

// ==================== API 接口预设 ====================

/** 获取预设列表 */
export function listPresets(params?: {
  page?: number
  pageSize?: number
  keyword?: string
}): Promise<any> {
  return request.get(`${BASE}/presets`, { params })
}

/** 获取预设详情 */
export function getPreset(id: string): Promise<any> {
  return request.get(`${BASE}/presets/${id}`)
}

/** 创建预设 */
export function createPreset(data: any): Promise<any> {
  return request.post(`${BASE}/presets`, data)
}

/** 更新预设 */
export function updatePreset(id: string, data: any): Promise<any> {
  return request.put(`${BASE}/presets/${id}`, data)
}

/** 删除预设 */
export function deletePreset(id: string): Promise<void> {
  return request.delete(`${BASE}/presets/${id}`)
}

// ==================== curl 解析 ====================

/** 解析 curl 命令，返回结构化压测配置 */
export function parseCurl(curlCommand: string): Promise<CurlParseResult> {
  return request.post(`${BASE}/parse-curl`, { curlCommand })
}

// ==================== 项目 CRUD ====================

/** 获取项目列表 */
export function listProjects(params?: {
  page?: number
  pageSize?: number
  projectType?: string
}): Promise<PerformanceProjectListResponse> {
  const queryParams: Record<string, any> = { ...params }
  // camelCase → snake_case: 后端路由参数为 project_type
  if (params?.projectType !== undefined) {
    queryParams.project_type = params.projectType
    delete queryParams.projectType
  }
  return request.get(`${BASE}/projects`, { params: queryParams })
}

/** 获取项目详情 */
export function getProject(id: string): Promise<PerformanceProject> {
  return request.get(`${BASE}/projects/${id}`)
}

/** 创建项目 */
export function createProject(data: PerformanceProjectCreate): Promise<PerformanceProject> {
  return request.post(`${BASE}/projects`, data)
}

/** 更新项目 */
export function updateProject(id: string, data: PerformanceProjectUpdate): Promise<PerformanceProject> {
  return request.put(`${BASE}/projects/${id}`, data)
}

/** 删除项目 */
export function deleteProject(id: string): Promise<void> {
  return request.delete(`${BASE}/projects/${id}`)
}

/** 获取项目统计 */
export function getProjectStats(id: string): Promise<PerformanceProjectStats> {
  return request.get(`${BASE}/projects/${id}/stats`)
}

// ==================== 批量执行 ====================

/** 批量执行指定任务 */
export function batchRunTasks(data: BatchRunRequest): Promise<BatchRunResponse> {
  return request.post(`${BASE}/tasks/batch-run`, data)
}

/** 执行项目下所有任务 */
export function runProjectAll(projectId: string): Promise<BatchRunResponse> {
  return request.post(`${BASE}/projects/${projectId}/run-all`)
}

/** 获取批量执行详情 */
export function getBatchDetails(batchId: string): Promise<BatchDetailResponse> {
  return request.get(`${BASE}/batch-details/${batchId}`)
}

// ==================== 合并报告 ====================

/** 获取项目最新合并报告 */
export function getProjectReport(projectId: string): Promise<ProjectReportResponse> {
  return request.get(`${BASE}/projects/${projectId}/report`)
}

/** 按批次ID获取合并报告 */
export function getBatchReport(batchId: string): Promise<ProjectReportResponse> {
  return request.get(`${BASE}/batch-reports/${batchId}`)
}

/** 获取项目历史合并报告列表 */
export function getProjectReports(projectId: string, params?: {
  page?: number
  pageSize?: number
}): Promise<ProjectReportListResponse> {
  return request.get(`${BASE}/projects/${projectId}/reports`, { params })
}

// ==================== AI 分析 ====================

/** 获取单次执行 AI 分析 */
export function getAiAnalysis(executionId: string): Promise<AiAnalysisResponse> {
  return request.post(`${BASE}/executions/${executionId}/ai-analysis`)
}

/** 多版本对比 AI 分析 */
export function getAiComparison(executionIds: string[]): Promise<AiAnalysisResponse> {
  return request.post(`${BASE}/ai-analysis/compare`, { executionIds })
}