/**
 * CLI argument parsing and help display
 */
import chalk from "chalk";
import { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR } from "../config.js";
const VALID_THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
export function isValidThinkingLevel(level) {
    return VALID_THINKING_LEVELS.includes(level);
}
export function parseArgs(args) {
    const result = {
        messages: [],
        fileArgs: [],
        unknownFlags: new Map(),
        diagnostics: [],
    };
    for (let i = 0; i < args.length; i++) {
        const arg = args[i];
        if (arg === "--help" || arg === "-h") {
            result.help = true;
        }
        else if (arg === "--version" || arg === "-v") {
            result.version = true;
        }
        else if (arg === "--mode" && i + 1 < args.length) {
            const mode = args[++i];
            if (mode === "text" || mode === "json" || mode === "rpc") {
                result.mode = mode;
            }
        }
        else if (arg === "--continue" || arg === "-c") {
            result.continue = true;
        }
        else if (arg === "--resume" || arg === "-r") {
            result.resume = true;
        }
        else if (arg === "--provider" && i + 1 < args.length) {
            result.provider = args[++i];
        }
        else if (arg === "--model" && i + 1 < args.length) {
            result.model = args[++i];
        }
        else if (arg === "--api-key" && i + 1 < args.length) {
            result.apiKey = args[++i];
        }
        else if (arg === "--system-prompt" && i + 1 < args.length) {
            result.systemPrompt = args[++i];
        }
        else if (arg === "--append-system-prompt" && i + 1 < args.length) {
            result.appendSystemPrompt = result.appendSystemPrompt ?? [];
            result.appendSystemPrompt.push(args[++i]);
        }
        else if (arg === "--no-session") {
            result.noSession = true;
        }
        else if (arg === "--session" && i + 1 < args.length) {
            result.session = args[++i];
        }
        else if (arg === "--fork" && i + 1 < args.length) {
            result.fork = args[++i];
        }
        else if (arg === "--session-dir" && i + 1 < args.length) {
            result.sessionDir = args[++i];
        }
        else if (arg === "--models" && i + 1 < args.length) {
            result.models = args[++i].split(",").map((s) => s.trim());
        }
        else if (arg === "--no-tools") {
            result.noTools = true;
        }
        else if (arg === "--tools" && i + 1 < args.length) {
            result.tools = args[++i]
                .split(",")
                .map((s) => s.trim())
                .filter((name) => name.length > 0);
        }
        else if (arg === "--thinking" && i + 1 < args.length) {
            const level = args[++i];
            if (isValidThinkingLevel(level)) {
                result.thinking = level;
            }
            else {
                result.diagnostics.push({
                    type: "warning",
                    message: `Invalid thinking level "${level}". Valid values: ${VALID_THINKING_LEVELS.join(", ")}`,
                });
            }
        }
        else if (arg === "--print" || arg === "-p") {
            result.print = true;
        }
        else if (arg === "--export" && i + 1 < args.length) {
            result.export = args[++i];
        }
        else if ((arg === "--extension" || arg === "-e") && i + 1 < args.length) {
            result.extensions = result.extensions ?? [];
            result.extensions.push(args[++i]);
        }
        else if (arg === "--no-extensions" || arg === "-ne") {
            result.noExtensions = true;
        }
        else if (arg === "--skill" && i + 1 < args.length) {
            result.skills = result.skills ?? [];
            result.skills.push(args[++i]);
        }
        else if (arg === "--prompt-template" && i + 1 < args.length) {
            result.promptTemplates = result.promptTemplates ?? [];
            result.promptTemplates.push(args[++i]);
        }
        else if (arg === "--theme" && i + 1 < args.length) {
            result.themes = result.themes ?? [];
            result.themes.push(args[++i]);
        }
        else if (arg === "--no-skills" || arg === "-ns") {
            result.noSkills = true;
        }
        else if (arg === "--no-prompt-templates" || arg === "-np") {
            result.noPromptTemplates = true;
        }
        else if (arg === "--no-themes") {
            result.noThemes = true;
        }
        else if (arg === "--no-context-files" || arg === "-nc") {
            result.noContextFiles = true;
        }
        else if (arg === "--list-models") {
            // Check if next arg is a search pattern (not a flag or file arg)
            if (i + 1 < args.length && !args[i + 1].startsWith("-") && !args[i + 1].startsWith("@")) {
                result.listModels = args[++i];
            }
            else {
                result.listModels = true;
            }
        }
        else if (arg === "--verbose") {
            result.verbose = true;
        }
        else if (arg === "--offline") {
            result.offline = true;
        }
        else if (arg.startsWith("@")) {
            result.fileArgs.push(arg.slice(1)); // Remove @ prefix
        }
        else if (arg.startsWith("--")) {
            const eqIndex = arg.indexOf("=");
            if (eqIndex !== -1) {
                result.unknownFlags.set(arg.slice(2, eqIndex), arg.slice(eqIndex + 1));
            }
            else {
                const flagName = arg.slice(2);
                const next = args[i + 1];
                if (next !== undefined && !next.startsWith("-") && !next.startsWith("@")) {
                    result.unknownFlags.set(flagName, next);
                    i++;
                }
                else {
                    result.unknownFlags.set(flagName, true);
                }
            }
        }
        else if (arg.startsWith("-") && !arg.startsWith("--")) {
            result.diagnostics.push({ type: "error", message: `Unknown option: ${arg}` });
        }
        else if (!arg.startsWith("-")) {
            result.messages.push(arg);
        }
    }
    return result;
}
export function printHelp(extensionFlags) {
    const green = chalk.hex("#6ee7a2");
    const dim = chalk.gray;
    const white = chalk.white;
    const section = (name) => chalk.bold(green(name));
    const bullet = `${green("•")} `;
    const line = (flag, description) => `  ${bullet}${white(flag.padEnd(28))}${dim(description)}`;
    const extensionFlagsText = extensionFlags && extensionFlags.length > 0
        ? `\n${section("Extensions")}\n${extensionFlags
            .map((flag) => {
            const value = flag.type === "string" ? " <value>" : "";
            const description = flag.description ?? `Registered by ${flag.extensionPath}`;
            return line(`--${flag.name}${value}`, description);
        })
            .join("\n")}\n`
        : "";
    console.log(`${chalk.bold(green("OPERATOR"))} ${dim("// terminal coding agent")}

${section("Usage")}
  ${white(`${APP_NAME} [options] [@files...] [messages...]`)}
  ${white(`${APP_NAME} ollama use`)}

${section("Commands")}
${line("ollama use", "pick a local Ollama model from downloaded models")}

${section("Core")}
${line("--provider <name>", "provider name (default: alem-ai-plus-gpt-oss)")}
${line("--model <pattern>", 'model id, or "provider/model[:thinking]"')}
${line("--thinking <level>", "off, minimal, low, medium, high, xhigh")}
${line("--tools <tools>", "comma-separated tool allowlist")}
${line("--theme <path>", "load a theme file or theme directory")}

${section("Sessions")}
${line("--continue, -c", "continue the previous session")}
${line("--resume, -r", "choose a past session interactively")}
${line("--session <path|id>", "open a specific session file or partial id")}
${line("--session-dir <dir>", "override session storage directory")}
${line("--no-session", "run without saving session history")}

${section("Output")}
${line("--print, -p", "one-shot mode: process prompt and exit")}
${line("--list-models [search]", "show available models")}
${line("--offline", "disable startup network operations")}
${line("--help, -h", "show this help")}
${line("--version, -v", "show version")}
${extensionFlagsText}
${section("Examples")}
  ${bullet}${white(`${APP_NAME}`)}
  ${bullet}${white(`${APP_NAME} ollama use`)}
  ${bullet}${white(`${APP_NAME} "Review this project"`)}
  ${bullet}${white(`${APP_NAME} -p "List all .ts files in src/"`)}
  ${bullet}${white(`${APP_NAME} --continue "What did we discuss?"`)}
  ${bullet}${white(`${APP_NAME} --provider alem-ai-plus-gpt-oss --model gpt-oss "Help me refactor this code"`)}
  ${bullet}${white(`${APP_NAME} --model gpt-oss:high "Solve this complex problem"`)}
  ${bullet}${white(`${APP_NAME} --tools read,grep,find,ls -p "Review the code in src/"`)}

${section("Environment")}
  ${bullet}${dim(`API keys are requested interactively and stored in ~/${CONFIG_DIR_NAME}/agent/auth.json`)}
${line(ENV_AGENT_DIR, `session storage dir (default: ~/${CONFIG_DIR_NAME}/agent)`)}
${line("OPERATOR_OFFLINE", "set 1/true/yes to disable startup network calls")}

${section("Tools")}
${line("read", "read file contents")}
${line("bash", "execute shell commands")}
${line("edit", "edit files with find/replace")}
${line("write", "write files (creates/overwrites)")}
${line("grep", "search file contents")}
${line("find", "find files by glob")}
${line("ls", "list directory contents")}
`);
}
//# sourceMappingURL=args.js.map
