import { request } from "@/api/request"

// ============ 通用响应类型 ============

export interface ApiResponse<T = any> {
  code: number
  details: T
  message?: string
}

// ============ 报表类型枚举 ============

export enum ReportType {
  TOPN = 'topn',
  STATISTICS = 'statistics',
  TRAFFIC = 'traffic',
  FAULT = 'fault',
  SERVER = 'server',
  NETWORK_DEVICE = 'network_device',
  HISTORY = 'history',
}

export enum ReportStatus {
  PENDING = 'pending',
  RUNNING = 'running',
  SUCCESS = 'success',
  FAILED = 'failed',
}

// ============ 报表记录接口 ============

export interface ReportRecord {
  id: number
  report_type: ReportType
  title: string
  description?: string
  status: ReportStatus
  error_message?: string
  params_json?: Record<string, any>
  result_summary_json?: Record<string, any>
  file_path?: string
  file_size?: number
  file_mime?: string
  created_at: string
  updated_at: string
}

export interface ReportListParams {
  page?: number
  size?: number
  report_type?: ReportType
  status?: ReportStatus
  keyword?: string
  created_from?: string
  created_to?: string
}

export interface PageResult<T> {
  total: number
  page: number
  page_size: number
  data: T[]
}

// ============ 报表生成参数接口 ============

export interface TrafficReportParams {
  topology_id: number
  link_id?: number
  node_id?: string
  granularity?: 'minute' | 'hour' | 'day' | 'month'
  start_time: string
  end_time: string
  report_shape: 'summary' | 'detail' | 'trend' | 'top'
  detail_limit?: number
  trend_granularity?: 'minute' | 'hour' | 'day' | 'month'
  top_order_by?: 'total_bytes' | 'total_in_bytes' | 'total_out_bytes' | 'total_packets' | 'avg_latency' | 'avg_packet_loss' | 'total_connections'
  top_limit?: number
}

export interface FaultReportParams {
  fault_data_source?: 'collector_log' | 'alert' | 'hybrid'
  start_time: string
  end_time: string
  service_identities?: string[]
  status?: 'success' | 'failed' | 'timeout'
  keyword?: string
  group_by?: 'none' | 'service_identity' | 'day'
  alert_severities?: string[]
  alert_label_filters?: Record<string, string>
  include_raw_messages?: boolean
  detail_limit?: number
}

export interface ServerReportParams {
  server_ids?: number[]
  server_identities?: string[]
  start_time: string
  end_time: string
  columns?: ('availability' | 'last_check_time' | 'cpu' | 'memory_phys' | 'memory_virt' | 'disk_io' | 'disk_usage' | 'daily_alerts')[]
  availability_rule?: 'metrics_presence' | 'server_status'
  include_daily_alerts?: boolean
}

export interface StatisticsReportParams {
  data_source: 'dc-host' | 'dc-network' | 'dc-database' | 'dc-middleware'
  metric_name: string
  target_identities: string[]
  start_time: string
  end_time: string
  output_mode: 'scalar' | 'timeseries'
  scalar_aggregations?: ('avg' | 'max' | 'min' | 'sum' | 'count')[]
  interval?: string
  bucket_aggregation?: 'avg' | 'max' | 'min' | 'sum'
}

export interface HistoryReportParams {
  data_source: 'dc-host' | 'dc-network' | 'dc-database' | 'dc-middleware'
  metric_names: string[]
  target_identities: string[]
  start_time: string
  end_time: string
  interval: string
  bucket_aggregation: 'avg' | 'max' | 'min' | 'sum'
  series_layout?: string
}

export interface TopNReportParams {
  data_source: 'dc-host' | 'dc-network' | 'dc-database' | 'dc-middleware'
  metric_name: string
  target_identities: string[]
  start_time: string
  end_time: string
  n?: number
  rank_aggregate?: 'avg' | 'max' | 'min' | 'last'
  order?: 'desc' | 'asc'
  metric_type?: 'cpu' | 'disk' | 'io' | 'memory' | 'network'
  collector_identity?: string
}

export interface GenerateReportParams {
  report_type: ReportType
  title?: string
  description?: string
  params: TrafficReportParams | FaultReportParams | ServerReportParams | StatisticsReportParams | HistoryReportParams | TopNReportParams | Record<string, any>
}

// ============ 报表生成接口（新版） ============

/** 获取报表记录列表 */
export const fetchReportList = (params: ReportListParams) =>
  request.get<ApiResponse<PageResult<ReportRecord>>>('/DC-Control/v1/reports', { params })

/** 获取报表详情 */
export const fetchReportDetail = (id: number) =>
  request.get<ApiResponse<ReportRecord>>(`/DC-Control/v1/reports/${id}`)

/** 生成报表 */
export const generateReport = (data: GenerateReportParams) =>
  request.post<ApiResponse<ReportRecord>>('/DC-Control/v1/reports/generate', data)

/** 查看报表内容 */
export const fetchReportContent = (id: number) =>
  request.get<ApiResponse<Record<string, any>>>(`/DC-Control/v1/reports/${id}/content`)

/** 导出报表 */
export const exportReport = (id: number, format: 'csv' | 'xlsx' = 'csv') =>
  request.get<Blob>(`/DC-Control/v1/reports/${id}/export`, {
    params: { format },
    responseType: 'blob',
  })

// ============ 监测指标类接口（旧版兼容） ============

/** 监测指标TOPN */
export const fetchMetricsTopN = (params: any) =>
  request.get('/DC-Control/v1/reports/metrics/topn', { params })

/** 监测指标汇总 */
export const fetchMetricsSummary = (params: any) =>
  request.get('/DC-Control/v1/reports/metrics/summary', { params })

/** 监测指标汇总导出 */
export const exportMetricsSummary = (params: any) =>
  request.get('/DC-Control/v1/reports/metrics/export', { params, responseType: 'blob' })

// ============ 流量报表接口（旧版兼容） ============

/** 流量报表汇总 */
export const fetchTrafficSummary = (params: any) =>
  request.get('/DC-Control/v1/reports/traffic/summary', { params })

/** 流量报表趋势 */
export const fetchTrafficTrend = (params: any) =>
  request.get('/DC-Control/v1/reports/traffic/trend', { params })

/** 流量报表导出 */
export const exportTrafficReport = (params: any) =>
  request.get('/DC-Control/v1/reports/traffic/export', { params, responseType: 'blob' })

// ============ 状态报表接口（旧版兼容） ============

/** 服务器状态报表 */
export const fetchServerStatus = (params: any) =>
  request.get('/DC-Control/v1/reports/servers/status', { params })

/** 网络设备状态报表 */
export const fetchNetworkDeviceStatus = (params: any) =>
  request.get('/DC-Control/v1/reports/network-devices/status', { params })
