import { P as theme, _ as defaultRuntime } from "./entry.js";
import { G as writeConfigFile, R as createConfigIO } from "./auth-profiles-CgnoZiYS.js";
import { E as ensureAgentWorkspace, _ as DEFAULT_AGENT_WORKSPACE_DIR } from "./agent-scope-Cezno7_M.js";
import { x as shortenHomePath } from "./utils-CD6tCvSG.js";
import "./core-root-CmA71BTT.js";
import "./logger-BcqRk323.js";
import "./exec-CaapFZaD.js";
import "./registry-CBFkaKwt.js";
import "./github-copilot-token-DHTToceK.js";
import "./manifest-registry-DdFBL-mx.js";
import "./version-sf9dgjHP.js";
import "./dock-MGfYkqVd.js";
import "./accounts-DQj4GURA.js";
import "./plugins-D7VGnP8X.js";
import "./logging-JZEg5nDp.js";
import "./accounts-F1jmiu3k.js";
import "./message-channel-DelDwlJy.js";
import "./tailnet-mjXbAxqf.js";
import "./ws-GlDBWD0H.js";
import "./redact-CC_d52A1.js";
import "./errors-DAcI6n_m.js";
import "./sessions-CSzvEM0w.js";
import "./accounts-BMuunqOS.js";
import { o as resolveSessionTranscriptsDir } from "./paths-COzEpwhO.js";
import "./chat-envelope-BUdriZB0.js";
import "./client-B8ehJjd1.js";
import "./call-BAwuZELF.js";
import "./pairing-token-01jjmach.js";
import "./onboard-helpers-DePmX0qT.js";
import "./prompt-style-Bi8LEJM5.js";
import { t as formatDocsLink } from "./links-C87Xouo6.js";
import { n as runCommandWithRuntime } from "./cli-utils-DWSfnwCw.js";
import "./progress-DiO7soys.js";
import { t as hasExplicitOptions } from "./command-options-BVmaCunF.js";
import "./note-BUcnHAZz.js";
import "./clack-prompter-xERNpNNL.js";
import "./runtime-guard-kCSrmbox.js";
import "./onboarding.secret-input-D1HVfJYL.js";
import "./onboarding-TTG0CD0H.js";
import { n as logConfigUpdated, t as formatConfigPath } from "./logging-DW8_VTnZ.js";
import { t as onboardCommand } from "./onboard-BU_LzOyA.js";
import JSON5 from "json5";
import fs from "node:fs/promises";

//#region src/commands/setup.ts
async function readConfigFileRaw(configPath) {
	try {
		const raw = await fs.readFile(configPath, "utf-8");
		const parsed = JSON5.parse(raw);
		if (parsed && typeof parsed === "object") return {
			exists: true,
			parsed
		};
		return {
			exists: true,
			parsed: {}
		};
	} catch {
		return {
			exists: false,
			parsed: {}
		};
	}
}
async function setupCommand(opts, runtime = defaultRuntime) {
	const desiredWorkspace = typeof opts?.workspace === "string" && opts.workspace.trim() ? opts.workspace.trim() : void 0;
	const configPath = createConfigIO().configPath;
	const existingRaw = await readConfigFileRaw(configPath);
	const cfg = existingRaw.parsed;
	const defaults = cfg.agents?.defaults ?? {};
	const workspace = desiredWorkspace ?? defaults.workspace ?? DEFAULT_AGENT_WORKSPACE_DIR;
	const next = {
		...cfg,
		agents: {
			...cfg.agents,
			defaults: {
				...defaults,
				workspace
			}
		}
	};
	if (!existingRaw.exists || defaults.workspace !== workspace) {
		await writeConfigFile(next);
		if (!existingRaw.exists) runtime.log(`Wrote ${formatConfigPath(configPath)}`);
		else logConfigUpdated(runtime, {
			path: configPath,
			suffix: "(set agents.defaults.workspace)"
		});
	} else runtime.log(`Config OK: ${formatConfigPath(configPath)}`);
	const ws = await ensureAgentWorkspace({
		dir: workspace,
		ensureBootstrapFiles: !next.agents?.defaults?.skipBootstrap
	});
	runtime.log(`Workspace OK: ${shortenHomePath(ws.dir)}`);
	const sessionsDir = resolveSessionTranscriptsDir();
	await fs.mkdir(sessionsDir, { recursive: true });
	runtime.log(`Sessions OK: ${shortenHomePath(sessionsDir)}`);
}

//#endregion
//#region src/cli/program/register.setup.ts
function registerSetupCommand(program) {
	program.command("setup").description("Initialize ~/.gensparx/gensparx.json and the agent workspace").addHelpText("after", () => `\n${theme.muted("Docs:")} ${formatDocsLink("/cli/setup", "docs.gensparx.com/cli/setup")}\n`).option("--workspace <dir>", "Agent workspace directory (default: ~/.gensparx/workspace; stored as agents.defaults.workspace)").option("--wizard", "Run the interactive onboarding wizard", false).option("--non-interactive", "Run the wizard without prompts", false).option("--mode <mode>", "Wizard mode: local|remote").option("--remote-url <url>", "Remote Gateway WebSocket URL").option("--remote-token <token>", "Remote Gateway token (optional)").action(async (opts, command) => {
		await runCommandWithRuntime(defaultRuntime, async () => {
			const hasWizardFlags = hasExplicitOptions(command, [
				"wizard",
				"nonInteractive",
				"mode",
				"remoteUrl",
				"remoteToken"
			]);
			if (opts.wizard || hasWizardFlags) {
				await onboardCommand({
					workspace: opts.workspace,
					nonInteractive: Boolean(opts.nonInteractive),
					mode: opts.mode,
					remoteUrl: opts.remoteUrl,
					remoteToken: opts.remoteToken
				}, defaultRuntime);
				return;
			}
			await setupCommand({ workspace: opts.workspace }, defaultRuntime);
		});
	});
}

//#endregion
export { registerSetupCommand };