import { delay } from '@/mock'

// ==================== Types ====================

export interface ServiceStatus {
  id: string
  name: string
  endpoint: string
  status: 'healthy' | 'degraded' | 'down'
  uptime: number         // seconds
  latency: number        // ms
  version: string
  lastCheck: string
  cpu: number            // percentage 0-100
  memory: number         // percentage 0-100
}

export interface SystemMetrics {
  totalRequests24h: number
  avgResponseTime: number
  errorRate: number
  activeConnections: number
  diskUsage: number       // percentage
  memoryUsage: number     // percentage
  cpuUsage: number        // percentage
  uptimeHours: number
}

export interface TrafficPoint {
  hour: string
  requests: number
  errors: number
}

// ==================== Mock Data ====================

const mockServices: ServiceStatus[] = [
  {
    id: 'svc-plant', name: 'Plant 服务', endpoint: 'plant-rpc:8081',
    status: 'healthy', uptime: 864000, latency: 12, version: 'v1.3.2',
    lastCheck: new Date().toISOString(), cpu: 23, memory: 45,
  },
  {
    id: 'svc-radio', name: 'Radio 服务', endpoint: 'radio-rpc:8082',
    status: 'healthy', uptime: 720000, latency: 18, version: 'v1.1.0',
    lastCheck: new Date().toISOString(), cpu: 15, memory: 38,
  },
  {
    id: 'svc-gateway', name: 'API 网关', endpoint: 'gateway:8888',
    status: 'healthy', uptime: 864000, latency: 5, version: 'v2.0.1',
    lastCheck: new Date().toISOString(), cpu: 31, memory: 52,
  },
  {
    id: 'svc-db', name: 'MySQL 数据库', endpoint: 'mysql:3306',
    status: 'healthy', uptime: 2592000, latency: 3, version: '8.0.35',
    lastCheck: new Date().toISOString(), cpu: 18, memory: 62,
  },
  {
    id: 'svc-redis', name: 'Redis 缓存', endpoint: 'redis:6379',
    status: 'healthy', uptime: 2592000, latency: 1, version: '7.2.4',
    lastCheck: new Date().toISOString(), cpu: 5, memory: 28,
  },
  {
    id: 'svc-etcd', name: 'Etcd 注册中心', endpoint: 'etcd:2379',
    status: 'degraded', uptime: 172800, latency: 45, version: '3.5.12',
    lastCheck: new Date().toISOString(), cpu: 42, memory: 71,
  },
]

function generateTraffic(): TrafficPoint[] {
  const now = new Date()
  const points: TrafficPoint[] = []
  for (let i = 23; i >= 0; i--) {
    const h = new Date(now.getTime() - i * 3600000)
    const hour = h.getHours()
    // Simulate realistic traffic pattern
    const base = hour >= 9 && hour <= 22 ? 800 : 200
    const peak = hour >= 10 && hour <= 12 ? 400 : hour >= 19 && hour <= 21 ? 500 : 0
    const requests = base + peak + Math.floor(Math.random() * 200)
    const errors = Math.floor(requests * (Math.random() * 0.02))
    points.push({
      hour: `${String(hour).padStart(2, '0')}:00`,
      requests,
      errors,
    })
  }
  return points
}

const mockMetrics: SystemMetrics = {
  totalRequests24h: 18420,
  avgResponseTime: 142,
  errorRate: 0.3,
  activeConnections: 87,
  diskUsage: 34,
  memoryUsage: 58,
  cpuUsage: 27,
  uptimeHours: 720,
}

// ==================== API ====================

export async function getServiceList(): Promise<ServiceStatus[]> {
  await delay(400)
  // Add some randomness to simulate live data
  return mockServices.map(s => ({
    ...s,
    latency: s.latency + Math.floor(Math.random() * 10 - 5),
    cpu: Math.min(100, Math.max(0, s.cpu + Math.floor(Math.random() * 10 - 5))),
    memory: Math.min(100, Math.max(0, s.memory + Math.floor(Math.random() * 6 - 3))),
    lastCheck: new Date().toISOString(),
  }))
}

export async function getSystemMetrics(): Promise<SystemMetrics> {
  await delay(300)
  return {
    ...mockMetrics,
    totalRequests24h: mockMetrics.totalRequests24h + Math.floor(Math.random() * 200),
    avgResponseTime: mockMetrics.avgResponseTime + Math.floor(Math.random() * 30 - 15),
    activeConnections: mockMetrics.activeConnections + Math.floor(Math.random() * 20 - 10),
    cpuUsage: Math.min(100, Math.max(0, mockMetrics.cpuUsage + Math.floor(Math.random() * 10 - 5))),
    memoryUsage: Math.min(100, Math.max(0, mockMetrics.memoryUsage + Math.floor(Math.random() * 8 - 4))),
  }
}

export async function getTrafficData(): Promise<TrafficPoint[]> {
  await delay(350)
  return generateTraffic()
}
