import { r as __exportAll } from "./chunk-D_gEzPfs.js";
import { s as defaultRuntime, v as setVerbose } from "./subsystem-hATE68va.js";
import { n as isRich, r as theme } from "./theme-C5EwWDWE.js";
import { n as replaceCliName, r as resolveCliName } from "./command-format-DOYW_19_.js";
import { t as isTruthyEnvValue } from "./env-ChCKTuXK.js";
import { t as VERSION } from "./version-BKRSzdyx.js";
import { t as formatDocsLink } from "./links-BupJpVpQ.js";
import { r as registerProgramCommands, t as ensureConfigReady } from "./config-guard-CmbWsYQa.js";
import { a as getCommandPath, d as hasHelpOrVersion, l as getVerboseFlag } from "./register.subclis-B7sqTsBj.js";
import { t as ensurePluginRegistryLoaded } from "./plugin-registry-Bb6CC447.js";
import { a as hasEmittedCliBanner, i as formatCliBannerLine, r as emitCliBanner } from "./tui-Dh1acgyz.js";
import { n as resolveCliChannelOptions } from "./channel-options-CsA4EdIA.js";
import { Command } from "commander";

//#region src/cli/program/context.ts
function createProgramContext() {
	const channelOptions = resolveCliChannelOptions();
	return {
		programVersion: VERSION,
		channelOptions,
		messageChannelOptions: channelOptions.join("|"),
		koiChannelOptions: ["last", ...channelOptions].join("|")
	};
}

//#endregion
//#region src/cli/program/help.ts
const CLI_NAME = resolveCliName();
const EXAMPLES = [
	["SKYKOI channels login --verbose", "Link personal WhatsApp Web and show QR + connection logs."],
	["SKYKOI message send --target +15555550123 --message \"Hi\" --json", "Send via your web session and print JSON result."],
	["SKYKOI gateway --port 18789", "Run the WebSocket Gateway locally."],
	["SKYKOI --dev gateway", "Run a dev Gateway (isolated state/config) on ws://127.0.0.1:19001."],
	["SKYKOI gateway --force", "Kill anything bound to the default gateway port, then start it."],
	["SKYKOI gateway ...", "Gateway control via WebSocket."],
	["SKYKOI koi --to +15555550123 --message \"Run summary\" --deliver", "Talk directly to the Koi using the Gateway; optionally send the WhatsApp reply."],
	["SKYKOI message send --channel telegram --target @mychat --message \"Hi\"", "Send via your Telegram bot."]
];
function configureProgramHelp(program, ctx) {
	program.name(CLI_NAME).description("").version(ctx.programVersion).option("--dev", "Dev profile: isolate state under ~/.skykoi-dev, default gateway port 19001, and shift derived ports (browser/canvas)").option("--profile <name>", "Use a named profile (isolates SKYKOI_STATE_DIR/SKYKOI_CONFIG_PATH under ~/.skykoi-<name>)");
	program.option("--no-color", "Disable ANSI colors", false);
	program.configureHelp({
		sortSubcommands: true,
		sortOptions: true,
		optionTerm: (option) => theme.option(option.flags),
		subcommandTerm: (cmd) => theme.command(cmd.name())
	});
	program.configureOutput({
		writeOut: (str) => {
			const colored = str.replace(/^Usage:/gm, theme.heading("Usage:")).replace(/^Options:/gm, theme.heading("Options:")).replace(/^Commands:/gm, theme.heading("Commands:"));
			process.stdout.write(colored);
		},
		writeErr: (str) => process.stderr.write(str),
		outputError: (str, write) => write(theme.error(str))
	});
	if (process.argv.includes("-V") || process.argv.includes("--version") || process.argv.includes("-v")) {
		console.log(ctx.programVersion);
		process.exit(0);
	}
	program.addHelpText("beforeAll", () => {
		if (hasEmittedCliBanner()) return "";
		const rich = isRich();
		return `\n${formatCliBannerLine(ctx.programVersion, { richTty: rich })}\n`;
	});
	const fmtExamples = EXAMPLES.map(([cmd, desc]) => `  ${theme.command(replaceCliName(cmd, CLI_NAME))}\n    ${theme.muted(desc)}`).join("\n");
	program.addHelpText("afterAll", ({ command }) => {
		if (command !== program) return "";
		const docs = formatDocsLink("/cli", "docs.skykoi.com/cli");
		return `\n${theme.heading("Examples:")}\n${fmtExamples}\n\n${theme.muted("Docs:")} ${docs}\n`;
	});
}

//#endregion
//#region src/cli/program/preaction.ts
function setProcessTitleForCommand(actionCommand) {
	let current = actionCommand;
	while (current.parent && current.parent.parent) current = current.parent;
	const name = current.name();
	const cliName = resolveCliName();
	if (!name || name === cliName) return;
	process.title = `${cliName}-${name}`;
}
const PLUGIN_REQUIRED_COMMANDS = new Set([
	"message",
	"channels",
	"directory"
]);
function registerPreActionHooks(program, programVersion) {
	program.hook("preAction", async (_thisCommand, actionCommand) => {
		setProcessTitleForCommand(actionCommand);
		const argv = process.argv;
		if (hasHelpOrVersion(argv)) return;
		const commandPath = getCommandPath(argv, 2);
		if (!(isTruthyEnvValue(process.env.SKYKOI_HIDE_BANNER) || commandPath[0] === "update" || commandPath[0] === "completion" || commandPath[0] === "plugins" && commandPath[1] === "update")) await emitCliBanner(programVersion);
		const verbose = getVerboseFlag(argv, { includeDebug: true });
		setVerbose(verbose);
		if (!verbose) process.env.NODE_NO_WARNINGS ??= "1";
		if (commandPath[0] === "doctor" || commandPath[0] === "completion") return;
		await ensureConfigReady({
			runtime: defaultRuntime,
			commandPath
		});
		if (PLUGIN_REQUIRED_COMMANDS.has(commandPath[0])) ensurePluginRegistryLoaded();
	});
}

//#endregion
//#region src/cli/program/build-program.ts
function buildProgram() {
	const program = new Command();
	const ctx = createProgramContext();
	const argv = process.argv;
	configureProgramHelp(program, ctx);
	registerPreActionHooks(program, ctx.programVersion);
	registerProgramCommands(program, ctx, argv);
	return program;
}

//#endregion
//#region src/cli/program.ts
var program_exports = /* @__PURE__ */ __exportAll({ buildProgram: () => buildProgram });

//#endregion
export { buildProgram as n, program_exports as t };