import http from '@/api/http'
import type { LaunchMode, RunMode } from '@/types/auth'

export interface HealthInfo {
  status: string
  startTime: string
  uptimeSec: number
}

export interface SimpleLiteDiagnostics {
  enabled: boolean
  isRunning: boolean
  lastLaunchMode?: string | null
  projectionPort: number
  projectionPortReachable: boolean
  gotoSiteApiAvailable?: boolean | null
  executableExists: boolean
  deployHint?: string | null
}

export interface SimpleLiteLaunchResult {
  started: boolean
  status: string
  detail: string
  displayMode?: string | null
  warning?: string | null
}

export function getHealth() {
  return http.get<HealthInfo>('/health')
}

export function getSimpleLiteDiagnostics() {
  return http.get<SimpleLiteDiagnostics>('/health/simplelite')
}

export function stopSimpleLite() {
  return http.post<{ killed: number; diagnostics: SimpleLiteDiagnostics }>('/health/simplelite/stop')
}

export function restartSimpleLite(launchMode: LaunchMode) {
  return http.post<{ restart: SimpleLiteLaunchResult; diagnostics: SimpleLiteDiagnostics }>(
    '/health/simplelite/restart',
    null,
    { params: { launchMode }, timeout: 60_000 }
  )
}

/** 从诊断/会话 runMode 推断重启时使用的 launchMode。 */
export function resolveRestartLaunchMode(
  lastLaunchMode: string | null | undefined,
  runMode: RunMode | null | undefined
): LaunchMode {
  const mode = (lastLaunchMode ?? '').toLowerCase()
  if (mode === 'web') return 'WebOnly'
  if (mode === 'web+local') return 'DesktopAndWeb'
  return runMode === 'WebOnly' ? 'WebOnly' : 'DesktopAndWeb'
}
