import { r as formatErrorMessage } from "./errors-Z0lU1pH3.js";
import { t as formatCliCommand } from "./command-format-HwSAdvXB.js";
import { r as defaultRuntime } from "./runtime-LRpY2Icg.js";
import { t as collectNestedErrorCandidates } from "./error-graph-internal-BhPsO7Uu.js";
import { t as createSubsystemLogger } from "./subsystem-CT-8ly4J.js";
import { i as isSqliteSchemaVersionError } from "./sqlite-user-version-CdJndp9E.js";
import { n as findOpenClawStateDatabaseSchemaMigrationRequiredError } from "./openclaw-state-db-schema-migration-required-BAOXvPBh.js";
import { r as findOpenClawAgentDatabaseMediaMigrationRequiredError } from "./openclaw-agent-db-migration-required-BHhCEvlh.js";
//#region src/cli/gateway-cli/startup-maintenance.ts
const gatewayLog = createSubsystemLogger("gateway");
function resolveGatewayStartupMaintenanceReason(error) {
	if (collectNestedErrorCandidates(error).some(isSqliteSchemaVersionError)) return "a newer OpenClaw build";
	if (findOpenClawAgentDatabaseMediaMigrationRequiredError(error)) return "offline media migration";
	if (findOpenClawStateDatabaseSchemaMigrationRequiredError(error)) return "state database schema migration";
}
async function handleGatewayStartupMaintenance(error) {
	const reason = resolveGatewayStartupMaintenanceReason(error);
	if (!reason) return false;
	const guidance = reason === "a newer OpenClaw build" ? "Start the Gateway with a build that supports these database schemas. This install cannot repair a newer database." : `Run ${formatCliCommand("openclaw doctor --fix")} to repair and restart it.`;
	let parked = false;
	try {
		const { parkCurrentLaunchAgentForMaintenance } = await import("./launchd-CYq90cCJ.js");
		parked = await parkCurrentLaunchAgentForMaintenance();
	} catch (parkError) {
		gatewayLog.error(`failed to park the managed LaunchAgent: ${formatErrorMessage(parkError)}`);
	}
	gatewayLog.error(`gateway requires ${reason}${parked ? "; parked the managed LaunchAgent" : ""}. ${guidance}`);
	defaultRuntime.error(`Gateway failed to start: ${formatErrorMessage(error)}. ${guidance}`);
	defaultRuntime.exit(78);
	return true;
}
//#endregion
export { resolveGatewayStartupMaintenanceReason as n, handleGatewayStartupMaintenance as t };
