/**
 * 性能测试模块类型定义
 *
 * @author czj
 * @date 2026-08-12
 */

/** 任务状态 */
export type PerfStatus = 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'

/** 压测模式 */
export type PerfMode = 'concurrent' | 'qps' | 'step'

// ==================== 场景增强类型（burst/endurance） ====================

/** 场景类型（null=标准模式） */
export type PerfScenarioType = 'burst' | 'endurance' | null

/** 循环类型 */
export type LoopType = 'finite' | 'infinite'

/** 思考时间分布 */
export type ThinkTimeDistribution = 'constant' | 'gaussian'

/** 错误动作 */
export type ErrorAction = 'continue' | 'stop'

/** 场景接口配置（endurance 多接口模式） */
export interface ScenarioApiConfig {
  name: string
  method?: string
  url: string
  headers?: Record<string, string> | null
  body?: string | null
  threadCount: number
  assertions?: AssertionRule[]
  uniqueFields?: UniqueFieldRule[] | null
}

/** 接口级统计汇总 */
export interface ApiSummaryData {
  name: string
  totalRequests: number
  successCount: number
  failCount: number
  avgResponseTime: number
  minResponseTime: number
  maxResponseTime: number
  p50ResponseTime: number
  p90ResponseTime: number
  p95ResponseTime: number
  p99ResponseTime: number
  stdDev: number
  errorRate: number
  actualTps: number
}

/** 断言类型 */
export type AssertionType = 'status_code' | 'response_time' | 'response_body'

/** 断言操作符 */
export type AssertionOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'contains' | 'not_contains' | 'regex'

/** 断言规则 */
export interface AssertionRule {
  type: AssertionType
  operator: AssertionOperator
  value: string
  path?: string | null
  description?: string | null
}

// ==================== 事务步骤 ====================

/** 事务步骤配置 */
export interface TransactionStep {
  name: string
  url: string
  method?: string
  headers?: Record<string, string> | null
  body?: any | null
  bodyTemplate?: any | null
  assertions?: AssertionRule[]
  captureRules?: any[] | null
  timeout?: number
}

/** 事务步骤执行结果 */
export interface TransactionStepResult {
  stepName: string
  stepIndex: number
  status: number
  success: boolean
  elapsedMs: number
  latencyMs: number
  connectMs: number
  sentBytes: number
  receivedBytes: number
  errorMessage: string
  captured: Record<string, any>
}

// ==================== 执行机资源监控 ====================

/** 资源监控单次采样数据 */
export interface ResourceData {
  cpuPercent: number
  memPercent: number
  memUsedMb: number
  memTotalMb: number
  netSentKbS: number
  netRecvKbS: number
  netSentTotalMb: number
  netRecvTotalMb: number
  backend: string
}

/** 资源趋势序列点 */
export interface ResourceSeriesPoint {
  elapsed: number
  cpuPercent: number
  memPercent: number
  netSentKbS: number
  netRecvKbS: number
}

/** 资源监控汇总 */
export interface ResourceSummary {
  stats: {
    sampleCount: number
    avgCpuPercent: number
    maxCpuPercent: number
    avgMemPercent: number
    maxMemPercent: number
    avgSentKbS: number
    avgRecvKbS: number
    maxSentKbS: number
    maxRecvKbS: number
  }
  series: ResourceSeriesPoint[]
}

// ==================== 目标机资源监控 ====================

/** 目标机 Java 进程单次采样数据 */
export interface JavaProcessSample {
  /** 命中的服务关键字（如 ubains-meeting-inner-api） */
  processName: string
  /** 进程 PID */
  pid: number
  /** 进程 CPU 占用 %（100% = 单核满载） */
  cpuPercent: number
  /** 进程内存占用 %（相对系统总内存） */
  memPercent: number
  /** 进程常驻内存 MB */
  rssMb: number
}

/** 目标机 Java 进程统计汇总 */
export interface JavaProcessStats {
  processName: string
  avgCpuPercent: number
  maxCpuPercent: number
  avgMemPercent: number
  maxMemPercent: number
  avgRssMb: number
  maxRssMb: number
}

/** 目标机 Java 进程趋势序列 */
export interface JavaProcessSeries {
  processName: string
  data: Array<{
    elapsed: number
    cpuPercent: number
    memPercent: number
    rssMb: number
  }>
}

/** 目标机资源监控单次采样数据 */
export interface TargetResourceData {
  cpuPercent: number
  memPercent: number
  memUsedMb: number
  memTotalMb: number
  loadAvg1: number
  loadAvg5: number
  loadAvg15: number
  /** 目标机地址（仅合并报告汇总中有，实时采样无此字段） */
  host?: string
  /** Java 进程 CPU/内存占用明细 */
  javaProcesses?: JavaProcessSample[] | null
  timestamp: number
  available: boolean
}

/** 目标机资源趋势序列点 */
export interface TargetResourceSeriesPoint {
  elapsed: number
  cpuPercent: number
  memPercent: number
  loadAvg1: number
}

/** 目标机资源监控汇总 */
export interface TargetResourceSummary {
  host: string
  stats: {
    sampleCount: number
    avgCpuPercent: number
    maxCpuPercent: number
    avgMemPercent: number
    maxMemPercent: number
    avgLoadAvg1: number
    maxLoadAvg1: number
  }
  series: TargetResourceSeriesPoint[]
  /** Java 进程统计汇总（仅当匹配到进程时存在） */
  javaProcessStats?: JavaProcessStats[] | null
  /** Java 进程趋势序列（仅当匹配到进程时存在） */
  javaProcessSeries?: JavaProcessSeries[] | null
}

/** 事务步骤汇总 */
export interface StepSummary {
  stepName: string
  avgElapsedMs: number
  maxElapsedMs: number
  minElapsedMs: number
  successCount: number
  failCount: number
  sampleCount: number
}

/** 事务处理时间汇总 */
export interface TransactionSummary {
  totalTransactions: number
  successCount: number
  failCount: number
  avgElapsedMs: number
  maxElapsedMs: number
  minElapsedMs: number
  stepSummaries: StepSummary[]
}

/** 唯一性字段规则 */
export interface UniqueFieldRule {
  field: string
  strategy: 'suffix' | 'template'
  template?: string | null
}

/** 项目类型 */
export type PerfProjectType = 'standard' | 'custom'

/** 性能测试任务 */
export interface PerformanceTask {
  id: string
  name: string
  description: string | null
  status: PerfStatus
  errorMessage: string | null
  projectId: string | null
  targetUrl: string
  method: string
  headers: Record<string, string> | null
  body: string | null
  bodyTemplate: string | null
  mode: PerfMode
  concurrency: number
  qpsTarget: number | null
  duration: number
  rampUp: number | null
  stepConcurrency: number | null
  stepDuration: number | null
  authRequired: boolean
  accountKey: string | null
  loginUsername: string | null
  loginPassword: string | null
  signRequest: boolean
  assertions: AssertionRule[]
  totalRequests: number | null
  successCount: number | null
  failCount: number | null
  minResponseTime: number | null
  maxResponseTime: number | null
  avgResponseTime: number | null
  p50ResponseTime: number | null
  p90ResponseTime: number | null
  p95ResponseTime: number | null
  p99ResponseTime: number | null
  stdDev: number | null
  latencyAvg: number | null
  latencyMin: number | null
  latencyMax: number | null
  connectTimeAvg: number | null
  connectTimeMax: number | null
  peakTps: number | null
  totalSentBytes: number | null
  totalReceivedBytes: number | null
  apdex: number | null
  errorTypeTimeout: number | null
  errorTypeConnectError: number | null
  errorTypeClientError: number | null
  errorTypeHttp4xx: number | null
  errorTypeHttp5xx: number | null
  errorTypeAssertion: number | null
  actualTps: number | null
  errorRate: number | null
  startTime: string | null
  endTime: string | null
  durationActual: number | null
  presetId: string | null
  captureRules: any[] | null
  uniqueFields: UniqueFieldRule[] | null
  /** 事务步骤 */
  steps?: TransactionStep[] | null
  transactionFailPolicy?: string | null
  transactionTimeout?: number | null
  /** 场景类型（burst=瞬时并发 / endurance=长稳压测 / null=标准） */
  scenarioType?: PerfScenarioType
  /** endurance 场景接口配置 */
  scenarioApis?: ScenarioApiConfig[] | null
  /** 循环类型（burst） */
  loopType?: LoopType
  /** 循环次数（loopType=finite 时生效） */
  loopCount?: number
  /** 集合点（burst） */
  synchronizingTimerEnabled?: boolean
  synchronizingTimerCount?: number
  synchronizingTimerTimeout?: number
  /** 错误动作（burst） */
  errorAction?: ErrorAction
  /** 思考时间（endurance） */
  thinkTimeEnabled?: boolean
  thinkTimeMin?: number
  thinkTimeMax?: number
  thinkTimeDistribution?: ThinkTimeDistribution
  /** CSV 参数化（endurance） */
  csvParameterizationEnabled?: boolean
  csvContent?: string
  csvVariableMapping?: Record<string, string> | null
  /** 接口级统计汇总 */
  apiSummary?: ApiSummaryData[] | null
  /** 执行机资源监控汇总 */
  resourceSummary?: ResourceSummary | null
  /** 事务处理时间汇总 */
  transactionSummary?: TransactionSummary | null
  createdAt: string
  updatedAt: string
}

/** 创建任务请求 */
export interface PerformanceTaskCreate {
  name: string
  description?: string | null
  projectId?: string | null
  targetUrl: string
  method?: string
  headers?: Record<string, string> | null
  body?: string | null
  bodyTemplate?: string | null
  mode: PerfMode
  concurrency?: number
  qpsTarget?: number | null
  duration: number
  rampUp?: number | null
  stepConcurrency?: number | null
  stepDuration?: number | null
  authRequired?: boolean
  accountKey?: string | null
  loginUsername?: string | null
  loginPassword?: string | null
  signRequest?: boolean
  assertions?: AssertionRule[]
  uniqueFields?: UniqueFieldRule[] | null
  /** 事务步骤 */
  steps?: TransactionStep[] | null
  transactionFailPolicy?: string | null
  transactionTimeout?: number | null
  /** 场景增强（burst/endurance） */
  scenarioType?: PerfScenarioType
  scenarioApis?: ScenarioApiConfig[] | null
  loopType?: LoopType
  loopCount?: number
  synchronizingTimerEnabled?: boolean
  synchronizingTimerCount?: number
  synchronizingTimerTimeout?: number
  errorAction?: ErrorAction
  thinkTimeEnabled?: boolean
  thinkTimeMin?: number
  thinkTimeMax?: number
  thinkTimeDistribution?: ThinkTimeDistribution
  csvParameterizationEnabled?: boolean
  csvContent?: string
  csvVariableMapping?: Record<string, string> | null
}

/** 更新任务请求 */
export interface PerformanceTaskUpdate {
  name?: string
  description?: string | null
  projectId?: string | null
  targetUrl?: string
  method?: string
  headers?: Record<string, string> | null
  body?: string | null
  bodyTemplate?: string | null
  mode?: PerfMode
  concurrency?: number
  qpsTarget?: number | null
  duration?: number
  rampUp?: number | null
  stepConcurrency?: number | null
  stepDuration?: number | null
  authRequired?: boolean
  accountKey?: string | null
  loginUsername?: string | null
  loginPassword?: string | null
  signRequest?: boolean
  assertions?: AssertionRule[]
  uniqueFields?: UniqueFieldRule[] | null
  /** 事务步骤 */
  steps?: TransactionStep[] | null
  transactionFailPolicy?: string | null
  transactionTimeout?: number | null
  /** 场景增强（burst/endurance） */
  scenarioType?: PerfScenarioType
  scenarioApis?: ScenarioApiConfig[] | null
  loopType?: LoopType
  loopCount?: number
  synchronizingTimerEnabled?: boolean
  synchronizingTimerCount?: number
  synchronizingTimerTimeout?: number
  errorAction?: ErrorAction
  thinkTimeEnabled?: boolean
  thinkTimeMin?: number
  thinkTimeMax?: number
  thinkTimeDistribution?: ThinkTimeDistribution
  csvParameterizationEnabled?: boolean
  csvContent?: string
  csvVariableMapping?: Record<string, string> | null
}

/** 任务列表项 */
export interface PerformanceTaskListItem {
  id: string
  name: string
  description: string | null
  status: PerfStatus
  projectId: string | null
  targetUrl: string
  method: string
  mode: PerfMode
  concurrency: number
  duration: number
  actualTps: number | null
  peakTps: number | null
  p95ResponseTime: number | null
  avgResponseTime: number | null
  errorRate: number | null
  startTime: string | null
  endTime: string | null
  createdAt: string
  /** 场景类型（列表标识） */
  scenarioType?: PerfScenarioType
}

/** 任务列表响应 */
export interface PerformanceTaskListResponse {
  total: number
  items: PerformanceTaskListItem[]
}

/** 执行请求 */
export interface PerformanceRunRequest {
  configOverride?: Record<string, any> | null
}

/** 执行响应 */
export interface PerformanceRunResponse {
  message: string
  taskId: string
  /** 执行记录ID（非阻塞执行立即返回，前端凭此跳转监控页） */
  executionId?: string | null
  status: string
}

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

/** 执行历史列表项 */
export interface PerformanceExecutionListItem {
  id: string
  taskId: string
  taskName: string
  projectId: string | null
  status: PerfStatus
  startTime: string | null
  endTime: string | null
  durationActual: number
  totalRequests: number
  actualTps: number
  avgResponseTime: number
  p95ResponseTime: number
  errorRate: number
  triggeredBy: string
  snapshotCount: number
}

/** 执行历史列表响应 */
export interface PerformanceExecutionListResponse {
  total: number
  items: PerformanceExecutionListItem[]
}

/** 执行历史详情 */
export interface PerformanceExecutionDetail {
  id: string
  taskId: string
  taskName: string
  projectId: string | null
  status: PerfStatus
  errorMessage: string | null
  startTime: string | null
  endTime: string | null
  durationActual: number
  totalRequests: number
  successCount: number
  failCount: number
  errorRate: number
  actualTps: number
  peakTps: number
  minResponseTime: number
  maxResponseTime: number
  avgResponseTime: number
  p50ResponseTime: number
  p90ResponseTime: number
  p95ResponseTime: number
  p99ResponseTime: number
  stdDev: number
  latencyAvg: number
  latencyMin: number
  latencyMax: number
  connectTimeAvg: number
  connectTimeMax: number
  apdex: number
  totalSentBytes: number
  totalReceivedBytes: number
  resourceSummary?: ResourceSummary | null
  targetResourceSummary?: TargetResourceSummary | null
  transactionSummary?: TransactionSummary | null
  apiSummary?: ApiSummaryData[] | null
  snapshotCount: number
  triggeredBy: string
  batchId: string | null
  createdAt: string | null
}

/** 快照数据 */
export interface PerformanceSnapshot {
  id: number
  taskId: string
  elapsed: number
  concurrentUsers: number
  tps: number
  avgResponseTime: number
  minResponseTime: number
  maxResponseTime: number
  p50ResponseTime: number
  p90ResponseTime: number
  p95ResponseTime: number
  p99ResponseTime: number
  stdDev: number
  latencyAvg: number
  connectTimeAvg: number
  sentBytes: number
  receivedBytes: number
  peakTps: number
  successCount: number
  failCount: number
  status2xx: number
  status3xx: number
  status4xx: number
  status5xx: number
  /** 执行机资源监控数据（实时快照附带） */
  resource?: ResourceData | null
  /** 目标机资源监控数据（实时快照附带） */
  targetResource?: TargetResourceData | null
}

/** 快照列表响应 */
export interface PerformanceSnapshotListResponse {
  total: number
  items: PerformanceSnapshot[]
}

/** 报告摘要 */
export interface PerformanceReportSummary {
  taskId: string
  taskName: string
  targetUrl: string
  method: string
  mode: string
  concurrency: number
  durationSetting: number
  durationActual: number | null
  startTime: string | null
  endTime: string | null
  accountKey: string | null
  /** 场景类型 */
  scenarioType?: PerfScenarioType
}

/** 报告指标 */
export interface PerformanceReportMetrics {
  totalRequests: number
  successCount: number
  failCount: number
  errorRate: number
  actualTps: number
  peakTps: number
  minResponseTime: number
  maxResponseTime: number
  avgResponseTime: number
  p50ResponseTime: number
  p90ResponseTime: number
  p95ResponseTime: number
  p99ResponseTime: number
  stdDev: number
  latencyAvg: number
  latencyMin: number
  latencyMax: number
  connectTimeAvg: number
  connectTimeMax: number
  apdex: number
  totalSentBytes: number
  totalReceivedBytes: number
  sentKbPerSec: number
  receivedKbPerSec: number
  status2xx: number
  status3xx: number
  status4xx: number
  status5xx: number
  errorTypeTimeout: number
  errorTypeConnectError: number
  errorTypeClientError: number
  errorTypeHttp4xx: number
  errorTypeHttp5xx: number
  errorTypeAssertion: number
}

/** 报告响应 */
export interface PerformanceReportResponse {
  summary: PerformanceReportSummary
  metrics: PerformanceReportMetrics
  snapshots: PerformanceSnapshot[]
  /** 执行机资源监控汇总 */
  resourceSummary?: ResourceSummary | null
  /** 目标机资源监控汇总 */
  targetResourceSummary?: TargetResourceSummary | null
  /** 事务处理时间汇总 */
  transactionSummary?: TransactionSummary | null
  /** 接口级统计汇总（endurance 多接口） */
  apiSummary?: ApiSummaryData[] | null
}

/** WebSocket 快照消息 */
export interface PerfWsSnapshot {
  type: 'perf_snapshot'
  taskId: string
  /** 执行记录ID（非阻塞执行时附带） */
  executionId?: string | null
  data: {
    elapsed: number
    tps: number
    avgResponseTime: number
    p50: number
    p90: number
    p95: number
    p99: number
    stdDev: number
    latencyAvg: number
    connectTimeAvg: number
    sentBytes: number
    receivedBytes: number
    peakTps: number
    successCount: number
    failCount: number
    totalRequests: number
    concurrentUsers: number
    status2xx: number
    status4xx: number
    status5xx: number
    /** 执行机资源监控数据 */
    resource?: ResourceData | null
    /** 目标机资源监控数据 */
    targetResource?: TargetResourceData | null
  }
  timestamp: string
}

/** WebSocket 完成消息 */
export interface PerfWsComplete {
  type: 'perf_complete'
  taskId: string
  /** 执行记录ID（非阻塞执行时附带） */
  executionId?: string | null
  status: string
  data: Record<string, any>
}

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

/** 接口预设 */
export interface ApiPreset {
  id: string
  name: string
  description: string
  method: string
  targetUrl: string
  headers: Record<string, string> | null
  body: any | null
  bodyTemplate: any | null
  authRequired: boolean
  signRequest: boolean
  accountKey: string
  credentialName: string | null
  loginUsername: string | null
  loginPassword: string | null
  captureRules: any[] | null
  createdAt: string | null
  updatedAt: string | null
}

/** 创建接口预设请求 */
export interface ApiPresetCreate {
  name: string
  description?: string
  method?: string
  targetUrl: string
  headers?: Record<string, string> | null
  body?: any | null
  bodyTemplate?: any | null
  authRequired?: boolean
  signRequest?: boolean
  accountKey?: string
  credentialName?: string | null
  loginUsername?: string | null
  loginPassword?: string | null
  captureRules?: any[] | null
}

/** 接口预设列表项 */
export interface ApiPresetListItem {
  id: string
  name: string
  description: string
  method: string
  targetUrl: string
  updatedAt: string | null
}

/** 接口预设列表响应 */
export interface ApiPresetListResponse {
  total: number
  items: ApiPresetListItem[]
}

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

/** curl 解析结果 */
export interface CurlParseResult {
  method: string
  targetUrl: string
  headers: Record<string, string>
  body: any | null
  authRequired: boolean
  signRequest: boolean
  cookie: string | null
  errors: string[]
}

// ==================== 性能测试项目 ====================

/** 性能测试项目 */
export interface PerformanceProject {
  id: string
  name: string
  description: string
  projectType: PerfProjectType
  icon: string
  sortOrder: number
  taskCount: number
  lastRunStatus: string | null
  lastRunTime: string | null
  createdAt: string | null
  updatedAt: string | null
}

/** 创建项目请求 */
export interface PerformanceProjectCreate {
  name: string
  description?: string
  projectType?: PerfProjectType
  icon?: string
  sortOrder?: number
}

/** 更新项目请求 */
export interface PerformanceProjectUpdate {
  name?: string
  description?: string
  projectType?: PerfProjectType
  icon?: string
  sortOrder?: number
}

/** 项目列表响应 */
export interface PerformanceProjectListResponse {
  total: number
  items: PerformanceProject[]
}

/** 项目统计 */
export interface PerformanceProjectStats {
  projectId: string
  taskCount: number
  statusDistribution: Record<string, number>
  lastRunStatus: string | null
  lastRunTime: string | null
}

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

/** 批量执行请求 */
export interface BatchRunRequest {
  taskIds: string[]
  projectId?: string | null
}

/** 批量执行响应 */
export interface BatchRunResponse {
  message: string
  batchId: string
  taskCount: number
  taskIds: string[]
  reportId?: string | null
}

/** 批量执行详情中的任务状态项 */
export interface BatchTaskItem {
  taskId: string
  name: string
  status: PerfStatus
  actualTps: number | null
  avgResponseTime: number | null
  errorRate: number | null
  actualConcurrency: number | null
  durationActual: number | null
}

/** 批量执行详情响应 */
export interface BatchDetailResponse {
  batchId: string
  projectId: string | null
  projectName: string
  status: string
  totalCount: number
  successCount: number
  failCount: number
  startedAt: string | null
  completedAt: string | null
  tasks: BatchTaskItem[]
}

/** WebSocket 批量执行进度消息 */
export interface PerfBatchProgress {
  type: 'perf_batch_progress'
  batchId: string
  projectId: string | null
  currentIndex: number
  totalCount: number
  currentTaskId: string
  currentTaskName: string
  currentStatus: 'running' | 'completed' | 'failed' | 'partially_failed' | 'cancelled'
  successCount: number
  failCount: number
}

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

/** 合并报告任务明细项 */
export interface TaskSummaryItem {
  taskId: string
  taskName: string
  status: string
  totalRequests: number
  successCount: number
  failCount: number
  avgResponseTime: number
  actualTps: number
  errorRate: number
}

/** 合并报告聚合指标摘要 */
export interface ProjectReportSummary {
  totalRequests: number
  successCount: number
  failCount: number
  errorRate: number
  actualTps: number
  peakTps: number
  avgResponseTime: number
  minResponseTime: number
  maxResponseTime: number
  p50ResponseTime: number
  p90ResponseTime: number
  p95ResponseTime: number
  p99ResponseTime: number
  stdDev: number
  apdex: number
  status2xx: number
  status3xx: number
  status4xx: number
  status5xx: number
  totalSentBytes: number
  totalReceivedBytes: number
  durationActual: number
}

/** 合并报告响应 */
export interface ProjectReportResponse {
  id: string
  projectId: string
  batchId: string | null
  createdAt: string | null
  summary: ProjectReportSummary
  taskSummaries: TaskSummaryItem[]
}

/** 合并报告列表响应 */
export interface ProjectReportListResponse {
  total: number
  items: ProjectReportResponse[]
}

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

/** AI 分析响应 */
export interface AiAnalysisResponse {
  executionId: string
  analysisType: 'single' | 'comparison'
  overallVerdict: string
  keyFindings: { type: string; description: string; severity: string; evidence?: string }[]
  bottlenecks: { type: string; location: string; severity: 'high' | 'medium' | 'low'; description: string; evidence: string }[]
  suggestions: { priority: 'P0' | 'P1' | 'P2'; content: string; expectedEffect: string }[]
  resourceAnalysis?: string
  trendAnalysis?: Record<string, any>
  comparison?: Record<string, any>[]
  rawResponse?: string
  source: 'ai' | 'rule'
}