import { S as getCoreCliCommandsWithSubcommands, f as isRootVersionInvocation, g as getSubCliCommandsWithSubcommands, n as getCommandPathWithRootOptions } from "./argv-DD2cfVTN.js";
import { n as resolveCliName, t as replaceCliName } from "./cli-name-CAJoj2J5.js";
import { t as formatCliCommand } from "./command-format-CKGmlpAQ.js";
import { t as formatDocsLink } from "./links-CsLBrRff.js";
import { n as isRich, r as theme } from "./theme-vjDs9tao.js";
import "./utils-CCC-BEJH.js";
import { t as escapeRegExp } from "./regexp-BZyMFTlj.js";
import { h as ALLOWED_LOG_LEVELS, v as tryParseLogLevel } from "./logger-Csae0Wet.js";
import { t as resolveCommitHash } from "./git-commit-BdHX4fjS.js";
import { i as hasEmittedCliBanner, r as formatCliBannerLine } from "./banner-DckyFsfc.js";
import { InvalidArgumentError } from "commander";
//#region src/cli/log-level-option.ts
const CLI_LOG_LEVEL_VALUES = ALLOWED_LOG_LEVELS.join("|");
function parseCliLogLevelOption(value) {
	const parsed = tryParseLogLevel(value);
	if (!parsed) throw new InvalidArgumentError(`Invalid --log-level (use ${CLI_LOG_LEVEL_VALUES})`);
	return parsed;
}
//#endregion
//#region src/cli/program/error-output.ts
function stripCommanderErrorPrefix(raw) {
	return raw.trim().replace(/^error:\s*/i, "").trim();
}
function quote(value) {
	return `"${value}"`;
}
function resolveHelpCommand(argv, options) {
	if (options?.root || !argv) return formatCliCommand("openclaw --help");
	const commandPath = getCommandPathWithRootOptions(argv, 2);
	if (commandPath.length === 0) return formatCliCommand("openclaw --help");
	return formatCliCommand(`openclaw ${commandPath.join(" ")} --help`);
}
function lines(...items) {
	return `${items.filter((item) => Boolean(item)).join("\n")}\n`;
}
function formatHelpHint(argv, options) {
	return `${theme.muted("Try:")} ${theme.command(resolveHelpCommand(argv, options))}`;
}
function formatDocsHint() {
	return `${theme.muted("Docs:")} ${formatDocsLink("/cli", "docs.openclaw.ai/cli")}`;
}
/** Convert Commander parse errors into OpenClaw-specific help and docs guidance. */
function formatCliParseErrorOutput(raw, options = {}) {
	const message = stripCommanderErrorPrefix(raw);
	const unknownCommand = message.match(/^unknown command ['"`](.+?)['"`]/i);
	if (unknownCommand) {
		const command = unknownCommand[1] ?? "";
		return lines(theme.error(`OpenClaw does not know the command ${quote(command)}.`), formatHelpHint(options.argv, { root: true }), `${theme.muted("Plugin command?")} ${theme.command(formatCliCommand("openclaw plugins list"))}`, formatDocsHint());
	}
	const unknownOption = message.match(/^unknown option ['"`](.+?)['"`]/i);
	if (unknownOption) {
		const option = unknownOption[1] ?? "";
		return lines(theme.error(`OpenClaw does not recognize option ${quote(option)}.`), formatHelpHint(options.argv));
	}
	const missingArgument = message.match(/^missing required argument ['"`](.+?)['"`]/i);
	if (missingArgument) {
		const argument = missingArgument[1] ?? "";
		return lines(theme.error(`Missing required argument ${quote(argument)}.`), formatHelpHint(options.argv));
	}
	const missingOption = message.match(/^required option ['"`](.+?)['"`] not specified/i);
	if (missingOption) {
		const option = missingOption[1] ?? "";
		return lines(theme.error(`Missing required option ${quote(option)}.`), formatHelpHint(options.argv));
	}
	if (/^too many arguments\b/i.test(message)) return lines(theme.error("Too many arguments for this command."), formatHelpHint(options.argv));
	return lines(theme.error(`OpenClaw could not parse this command: ${message}`), formatHelpHint(options.argv));
}
//#endregion
//#region src/cli/program/help.ts
const CLI_NAME = resolveCliName();
const CLI_NAME_PATTERN = escapeRegExp(CLI_NAME);
const ROOT_COMMANDS_WITH_SUBCOMMANDS = new Set([...getCoreCliCommandsWithSubcommands(), ...getSubCliCommandsWithSubcommands()]);
const ROOT_COMMANDS_HINT = "提示：带 * 后缀的命令有子命令。运行 <command> --help 查看详情。";
const EXAMPLES = [
	["openclaw onboard", "引导设置本地网关、工作区、认证和渠道。"],
	["openclaw setup", "创建基础配置、工作区和会话目录。"],
	["openclaw configure", "调整模型、网关、渠道、插件、技能和健康检查。"],
	["openclaw status", "查看网关、渠道、模型和最近会话状态。"],
	["openclaw doctor --fix", "修复常见的配置、服务、插件和渠道问题。"],
	["openclaw channels add", "在引导提示下添加或更新聊天渠道账号。"],
	["openclaw channels status", "查看已连接的消息账号和登录状态。"],
	["openclaw --dev gateway", "在 ws://127.0.0.1:19001 上运行开发网关（隔离状态/配置）。"],
	["openclaw gateway run --force", "启动网关并替换占用其端口的进程。"],
	["openclaw models status", "运行代理前查看模型/提供商认证健康状态。"],
	["openclaw plugins list", "查看已启用、已禁用和已安装的插件。"],
	["openclaw agent --to +15555550123 --message \"Run summary\" --deliver", "通过网关运行一次代理轮次，并可选交付回复。"],
	["openclaw message send --channel telegram --target @mychat --message \"Hi\"", "通过你的 Telegram 机器人发送。"]
];
function configureProgramHelp(program, ctx, options) {
	const commandsWithSubcommands = new Set([...ROOT_COMMANDS_WITH_SUBCOMMANDS, ...options?.commandsWithSubcommands ?? []]);
	program.name(CLI_NAME).description("").version(ctx.programVersion, "-V, --version", "输出版本号").option("--container <name>", "在正在运行的 Podman/Docker 容器 <name> 内运行 CLI（默认：环境变量 OPENCLAW_CONTAINER）").option("--dev", "开发配置：在 ~/.openclaw-dev 下隔离状态，默认网关端口 19001，并移动派生端口（浏览器/画布）").option("--profile <name>", "使用命名配置文件（在 ~/.openclaw-<name> 下隔离状态和配置）").option("--log-level <level>", `全局日志级别覆盖，适用于文件和控制台 (${CLI_LOG_LEVEL_VALUES})`, parseCliLogLevelOption);
	program.option("--no-color", "禁用 ANSI 颜色", false);
	program.helpOption("-h, --help", "显示命令帮助");
	program.helpCommand("help [command]", "显示命令帮助");
	program.configureHelp({
		sortSubcommands: true,
		sortOptions: true,
		optionTerm: (option) => theme.option(option.flags),
		subcommandTerm: (cmd) => {
			const hasSubcommands = cmd.parent === program && commandsWithSubcommands.has(cmd.name());
			return theme.command(hasSubcommands ? `${cmd.name()} *` : cmd.name());
		}
	});
	const formatHelpOutput = (str) => {
		let output = str;
		if (new RegExp(`^Usage:\\s+${CLI_NAME_PATTERN}\\s+\\[options\\]\\s+\\[command\\]\\s*$`, "m").test(output) && /^Commands:/m.test(output)) output = output.replace(/^Commands:/m, `Commands:\n  ${theme.muted(ROOT_COMMANDS_HINT)}`);
		return output.replace(/^Usage:/gm, theme.heading("用法：")).replace(/^Options:/gm, theme.heading("选项：")).replace(/^Commands:/gm, theme.heading("命令："));
	};
	program.configureOutput({
		writeOut: (str) => {
			process.stdout.write(formatHelpOutput(str));
		},
		writeErr: (str) => {
			process.stderr.write(formatHelpOutput(str));
		},
		outputError: (str, write) => write(formatCliParseErrorOutput(str, { argv: process.argv }))
	});
	if (isRootVersionInvocation(process.argv)) {
		const commit = resolveCommitHash({ moduleUrl: import.meta.url });
		console.log(commit ? `OpenClaw ${ctx.programVersion} (${commit})` : `OpenClaw ${ctx.programVersion}`);
		process.exit(0);
	}
	program.addHelpText("beforeAll", () => {
		if (hasEmittedCliBanner() || process.env.OPENCLAW_SUPPRESS_HELP_BANNER === "1") return "";
		const rich = isRich();
		return `\n${formatCliBannerLine(ctx.programVersion, {
			richTty: rich,
			mode: "default"
		})}\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.openclaw.ai/cli");
		return `\n${theme.heading("示例：")}\n${fmtExamples}\n\n${theme.muted("文档：")} ${docs}\n${theme.muted("汉化版：")} ${theme.info("https://openclaw.qt.cool/")}\n`;
	});
}
//#endregion
export { configureProgramHelp as t };
