#!/usr/bin/env node
import { version } from "../../package.js";
import { ROOT_COMMAND_DESCRIPTION } from "./command-manifest.js";
import { loadAllCommands, resolveCommandName, tryLoadCommand } from "./command-loaders.js";
import { getContextWithOpts, parsedOpts } from "./context.js";
import { Command } from "commander";
//#region src/cli/index.ts
/** Command wiring and `program.parse`; executable entry is `bin.ts` (log preset before logger init). */
async function flushLoggerAndExit(code) {
	const { flushAndClose } = await import("../utils/logger/shutdown.js");
	await flushAndClose();
	process.exit(code);
}
const LONG_RUNNING_COMMANDS = new Set(["gateway", "agent"]);
function isExtensionsDevCommand(command) {
	return command.name() === "dev" && command.parent?.name() === "extensions";
}
function buildProgram() {
	const program = new Command().name("xopc").description(ROOT_COMMAND_DESCRIPTION).version(version).option("--verbose", "Enable verbose logging", false).option("--config <path>", "Config file path").option("--workspace <path>", "Workspace directory");
	program.hook("preAction", (thisCommand) => {
		const next = thisCommand.opts();
		for (const k of Object.keys(parsedOpts)) delete parsedOpts[k];
		Object.assign(parsedOpts, next);
	});
	program.hook("postAction", async (_hookOwner, actionCommand) => {
		const cmd = actionCommand ?? program;
		const args = cmd.args;
		const subCommandName = args.length > 0 ? args[0] : cmd.name();
		if (LONG_RUNNING_COMMANDS.has(subCommandName) || isExtensionsDevCommand(cmd)) {
			if (subCommandName === "agent") {
				if (!(process.argv.includes("-i") || process.argv.includes("--interactive"))) await flushLoggerAndExit(0);
			}
			return;
		}
		await flushLoggerAndExit(0);
	});
	return program;
}
async function runCli(argv = process.argv) {
	const program = buildProgram();
	const ctx = getContextWithOpts(argv);
	const filteredArgv = argv.filter((arg, index) => {
		if (arg !== "--") return true;
		return index < 2;
	});
	const target = resolveCommandName(filteredArgv);
	let loaded = false;
	if (target) loaded = await tryLoadCommand(program, ctx, target, getContextWithOpts);
	if (!loaded) await loadAllCommands(program, ctx, getContextWithOpts);
	program.parse(filteredArgv);
}
//#endregion
export { getContextWithOpts, parsedOpts, runCli };

//# sourceMappingURL=index.js.map