type StartupProcessError = {
  time: string
  message: string
}

export type StartupState = {
  phase: string
  startedAt: string
  core: {
    ready: boolean
    running: boolean
    attemptCount: number
    readyAt: string
    lastAttemptAt: string
    lastError: string
  }
  process: {
    lastUnhandledRejection: StartupProcessError | null
    lastUncaughtException: StartupProcessError | null
  }
}

export function createStartupState(): StartupState {
  return {
    phase: 'starting',
    startedAt: new Date().toISOString(),
    core: {
      ready: false,
      running: false,
      attemptCount: 0,
      readyAt: '',
      lastAttemptAt: '',
      lastError: '',
    },
    process: {
      lastUnhandledRejection: null,
      lastUncaughtException: null,
    },
  }
}

export function buildHealthPayload(startupState: StartupState, shutdownStarted: boolean) {
  return {
    phase: startupState.phase,
    startedAt: startupState.startedAt,
    core: {
      ready: startupState.core.ready,
      running: startupState.core.running,
      attemptCount: startupState.core.attemptCount,
      readyAt: startupState.core.readyAt,
      lastAttemptAt: startupState.core.lastAttemptAt,
      lastError: startupState.core.lastError,
    },
    process: {
      pid: process.pid,
      shutdownStarted,
      lastUnhandledRejection: startupState.process.lastUnhandledRejection,
      lastUncaughtException: startupState.process.lastUncaughtException,
    },
  }
}

export function formatStartupError(error: unknown) {
  if (error instanceof Error && error.message) {
    return error.message.split('\n')[0]?.trim() || '未知错误'
  }

  return String(error || '未知错误').trim()
}
