import http from './http'
import type { FleetHealthRow } from '@/types/car'
import { CARS } from '@/mock/data/cars'

const MOCK = import.meta.env.VITE_USE_MOCK === 'true'

function mockFleetHealth(): FleetHealthRow[] {
  return CARS.map((c, i) => {
    const rawId = c.rawId ?? (parseInt(c.id.replace(/\D/g, ''), 10) || i + 1)
    const ip = c.ip ?? `10.0.1.${10 + i}`
    const reachable = c.state !== 'offline'
    return {
      carId: rawId,
      carName: c.name,
      ip,
      onboardUrl: c.onboardUrl ?? `http://${ip}:8081`,
      latencyMs: reachable ? 8 + i * 4 : 2000,
      reachable,
      probedAt: new Date().toISOString(),
      uptimeSecs: 3600 + i * 120,
      alarmActiveSecs: c.state === 'fault' ? 120 : i * 5,
      faultRatePercent: c.state === 'fault' ? 3.2 : 0.1 * i,
      isAlarmActive: c.state === 'fault',
      cpuPercent: 20 + i * 8,
      memPercent: 40 + i * 5
    }
  })
}

export async function fetchFleetHealth(): Promise<FleetHealthRow[]> {
  if (MOCK) {
    await new Promise((r) => setTimeout(r, 120))
    return mockFleetHealth()
  }
  // 平台侧聚合：SimpleLite 指标 + WatchDog(:9776) TCP RTT。
  // 不再直打 /sl/projection/fleet/health（其探测车载 :8081，现场多数未开导致假超时 2000ms）。
  try {
    const { data } = await http.get<FleetHealthRow[]>('/fleet/health')
    if (Array.isArray(data) && data.length > 0) return data
  } catch {
    /* fall through */
  }
  const { data } = await http.get<FleetHealthRow[]>('/sl/projection/fleet/health')
  return Array.isArray(data) ? data : []
}
