export type StartupState = ReturnType<typeof createStartupState>;

export function createStartupState() {
  return {
    phase: "starting",
    startedAt: new Date().toISOString(),
    core: {
      ready: false,
      running: false,
      attemptCount: 0,
      readyAt: "",
      lastAttemptAt: "",
      lastError: "",
    },
    browser: {
      status: "pending",
      message: "",
      lastAttemptAt: "",
    },
    ocr: {
      status: "pending",
      message: "",
      lastAttemptAt: "",
    },
    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,
    },
    browser: {
      status: startupState.browser.status,
      message: startupState.browser.message,
      lastAttemptAt: startupState.browser.lastAttemptAt,
    },
    ocr: {
      status: startupState.ocr.status,
      message: startupState.ocr.message,
      lastAttemptAt: startupState.ocr.lastAttemptAt,
    },
    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();
}
