import { Xt as loadConfig } from "./env-Dlz8aQHP.js";
import "./agent-paths-DUHGyU1s.js";
import "./github-copilot-token-A9DiaCB0.js";
import { A as defaultRuntime } from "./entry.js";
import "./federation-8sW60I4p.js";
import { n as runCommandWithRuntime } from "./cli-utils-XevKf-tr.js";
import { t as managedUpCommand } from "./managed-up-DhYefvn4.js";
import { i as resolveGatewayStartupMode } from "./daemon-install-helpers-CzpeF_Bc.js";
import { spawn } from "node:child_process";

//#region src/commands/start.ts
async function runGatewayForeground(runtime) {
	const entryScript = process.argv[1];
	if (!entryScript) throw new Error("Unable to resolve CLI entry script for gateway start.");
	const child = spawn(process.execPath, [
		entryScript,
		"gateway",
		"--allow-unconfigured",
		"--force"
	], {
		env: process.env,
		stdio: "inherit",
		cwd: process.cwd()
	});
	const exitCode = await new Promise((resolve, reject) => {
		child.once("error", reject);
		child.once("exit", (code, signal) => {
			if (signal) {
				reject(/* @__PURE__ */ new Error(`gateway start interrupted by signal: ${signal}`));
				return;
			}
			resolve(code ?? 1);
		});
	});
	if (exitCode !== 0) throw new Error(`gateway start failed (exit=${exitCode})`);
	runtime.log("Gateway stopped.");
}
function resolveStartMode(input) {
	if (input === "managed") return "managed";
	if (input === "gateway") return "gateway";
	const config = loadConfig();
	return resolveGatewayStartupMode({
		env: process.env,
		config
	}) === "managed-up" ? "managed" : "gateway";
}
async function startCommand(options = {}, runtime = defaultRuntime) {
	if (resolveStartMode(options.mode) === "managed") {
		await managedUpCommand(runtime, { json: false });
		return;
	}
	await runGatewayForeground(runtime);
}

//#endregion
//#region src/cli/program/register.start.ts
function registerStartCommand(program) {
	program.command("start").description("Start runtime (auto-detect managed stack for federation/zrok/wallet, or local gateway)").option("--mode <mode>", "Startup mode: auto|managed|gateway", "auto").action(async (opts) => {
		const rawMode = String(opts.mode ?? "auto").trim().toLowerCase();
		const mode = rawMode === "auto" || rawMode === "managed" || rawMode === "gateway" ? rawMode : null;
		if (!mode) {
			defaultRuntime.error("Invalid --mode (use auto, managed, or gateway).");
			defaultRuntime.exit(1);
			return;
		}
		await runCommandWithRuntime(defaultRuntime, async () => {
			await startCommand({ mode }, defaultRuntime);
		});
	});
}

//#endregion
export { registerStartCommand };