import axios from 'axios';

const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8083';

export interface SystemMonitorData {
  pipelineStatus: PipelineStatus;
  websocketStats: WebSocketStats;
  databaseStatus: DatabaseStatus;
  memoryStats: MemoryStats;
  systemMetrics: SystemMetrics;
  timestamp: string;
}

export interface PipelineStatus {
  components: PipelineComponent[];
}

export interface PipelineComponent {
  name: string;
  type: string; // agent, kafka, processor, database
  status: 'healthy' | 'warning' | 'error' | 'unknown';
  description: string;
  messagesProcessed: number | null;
  latencyMs: number | null;
  details: string;
}

export interface WebSocketStats {
  totalConnections: number;
  activeConnections: number;
  serviceStats: Record<string, ServiceWebSocketStats>;
}

export interface ServiceWebSocketStats {
  serviceName: string;
  connections: number;
  messagesReceived: number;
  messagesSent: number;
  messagesPerSecond: number;
  lastActivity: string | null;
}

export interface DatabaseStatus {
  connected: boolean;
  activeConnections: number;
  maxConnections: number;
  totalQueries: number;
  avgQueryTimeMs: number | null;
  tableStats: Record<string, TableStats>;
}

export interface TableStats {
  tableName: string;
  rowCount: number;
  sizeBytes: number;
  sizeFormatted: string;
  lastUpdated: string;
}

export interface MemoryStats {
  jvmHeapUsed: number;
  jvmHeapMax: number;
  jvmHeapUsagePercent: number;
  jvmNonHeapUsed: number;
  systemTotalMemory: number;
  systemFreeMemory: number;
  systemUsedMemory: number;
  systemMemoryUsagePercent: number;
  gcCount: number;
  gcTimeMs: number;
}

export interface SystemMetrics {
  cpuUsagePercent: number;
  availableProcessors: number;
  threadCount: number;
  peakThreadCount: number;
  uptimeMs: number;
  uptimeFormatted: string;
  diskTotal: number;
  diskFree: number;
  diskUsed: number;
  diskUsagePercent: number;
  networkBytesReceived: number;
  networkBytesSent: number;
}

export const systemMonitorApi = {
  /**
   * 시스템 모니터링 정보 조회
   */
  getSystemMonitorInfo: async (): Promise<SystemMonitorData> => {
    const response = await axios.get<SystemMonitorData>(`${API_BASE_URL}/api/system-monitor`, {
      timeout: 10000,
    });
    return response.data;
  },

  /**
   * 헬스 체크
   */
  healthCheck: async (): Promise<string> => {
    const response = await axios.get<string>(`${API_BASE_URL}/api/system-monitor/health`);
    return response.data;
  },
};
