/**
 * CLI argument parsing and help display
 */
import chalk from "chalk";
import { APP_NAME, CONFIG_DIR_NAME, ENV_AGENT_DIR, ENV_SESSION_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 === "--update" || arg === "-u") {
            result.update = 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" || arg === "-s") && 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" || arg === "-nt") {
            result.noTools = true;
        }
        else if (arg === "--no-builtin-tools" || arg === "-nbt") {
            result.noBuiltinTools = true;
        }
        else if ((arg === "--tools" || arg === "-t") && 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;
            const next = args[i + 1];
            if (next !== undefined && !next.startsWith("@") && (!next.startsWith("-") || next.startsWith("---"))) {
                result.messages.push(next);
                i++;
            }
        }
        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 extensionFlagsText = extensionFlags && extensionFlags.length > 0
        ? `\n${chalk.bold("Extension CLI Flags:")}\n${extensionFlags
            .map((flag) => {
            const value = flag.type === "string" ? " <value>" : "";
            const description = flag.description ?? `Registered by ${flag.extensionPath}`;
            return `  --${flag.name}${value}`.padEnd(30) + description;
        })
            .join("\n")}\n`
        : "";
    console.log(`${chalk.bold(APP_NAME)} - AI coding assistant with read, bash, edit, write tools

${chalk.bold("USAGE")}
  ${APP_NAME} [options] [@files...] [messages...]
  ${APP_NAME} <command> [args]

${chalk.bold("COMMANDS")}
  install <source> [-l]      Install extension and add to settings
  remove  <source> [-l]      Remove extension from settings
  list                       List installed extensions
  config                     Enable/disable package resources (TUI)
  update self                Update ${APP_NAME} to latest version
  update <source>            Update specific extension
  <command> --help           Command-specific help

${chalk.bold("FLAGS")}
  -p, --print                  Non-interactive: process prompt and exit
  -c, --continue               Continue previous session
  -r, --resume                 Select a session to resume
  -u, --update                 Update ${APP_NAME} to latest version
  -h, --help                   Show this help
  -v, --version                Show version number
  -nt, --no-tools              Disable all tools (built-in + extension)
  -nbt, --no-builtin-tools     Disable only built-in tools
  -t, --tools <list>           Enable only these tools (comma-separated)
  -e, --extension <path>       Load extension file (repeatable)
  -ne, --no-extensions         Disable extension discovery
  -ns, --no-skills             Disable skills discovery
  -nc, --no-context-files      Disable AGENTS.md / CLAUDE.md discovery

  --provider <name>            LLM provider (default: google)
  --model <pattern>            Model ID or pattern (supports provider/id and :<thinking>)
  --api-key <key>              API key (defaults to env var)
  --system-prompt <text>       Custom system prompt
  --append-system-prompt <txt> Append to system prompt (repeatable)
  --mode <mode>                Output mode: text | json | rpc
  -s, --session <path|id>      Use specific session file
  --fork <path|id>             Fork session into new one
  --session-dir <dir>          Session storage directory
  --no-session                 Ephemeral mode (no session saved)
  --models <patterns>          Ctrl+P cycling models (comma-separated, supports glob)
  --thinking <level>           Thinking level: off | minimal | low | medium | high | xhigh
  --skill <path>               Load skill file/dir (repeatable)
  --prompt-template <path>     Load prompt template (repeatable)
  --theme <path>               Load theme file/dir (repeatable)
  --no-themes                  Disable theme discovery
  --no-prompt-templates        Disable prompt template discovery
  --export <file>              Export session to HTML
  --list-models [search]       List available models (optional fuzzy search)
  --verbose                    Force verbose startup
  --offline                    Disable startup network checks

Extensions can register additional flags (e.g., --plan from plan-mode extension).${extensionFlagsText}

${chalk.bold("EXAMPLES")}
  ${APP_NAME}                              Interactive session
  ${APP_NAME} -p "List .ts files"          Quick non-interactive
  ${APP_NAME} -c "What next?"              Continue last session
  ${APP_NAME} -u                           Update to latest version
  ${APP_NAME} --model sonnet:high "..."    Use Claude Sonnet with high thinking
  ${APP_NAME} --models sonnet,haiku        Limit Ctrl+P to Sonnet + Haiku
  ${APP_NAME} -t read,grep,find -p "..."   Read-only audit mode
  ${APP_NAME} --export session.jsonl       Export session to HTML

${chalk.bold("ENVIRONMENT")}
  Configuration:
  ${ENV_AGENT_DIR.padEnd(36)}  Config dir (default: ~/${CONFIG_DIR_NAME}/agent)
  ${ENV_SESSION_DIR.padEnd(36)}  Session storage (overridable via --session-dir)
  VOXCODE_PACKAGE_DIR                  Package dir override (Nix/Guix)
  VOXCODE_OFFLINE                      Skip network ops (1/true/yes)
  VOXCODE_TELEMETRY                    Override telemetry (1/true/yes or 0/false/no)
  VOXCODE_SHARE_VIEWER_URL             Share base URL (default: https://voxcode.dev/session/)

  API Keys:
  ANTHROPIC_API_KEY            ANTHROPIC_OAUTH_TOKEN
  OPENAI_API_KEY               AZURE_OPENAI_API_KEY
  AZURE_OPENAI_BASE_URL        AZURE_OPENAI_RESOURCE_NAME
  AZURE_OPENAI_API_VERSION     AZURE_OPENAI_DEPLOYMENT_NAME_MAP
  DEEPSEEK_API_KEY             GEMINI_API_KEY
  GROQ_API_KEY                 CEREBRAS_API_KEY
  XAI_API_KEY                  FIREWORKS_API_KEY
  TOGETHER_API_KEY             OPENROUTER_API_KEY
  AI_GATEWAY_API_KEY           ZAI_API_KEY
  MISTRAL_API_KEY              MINIMAX_API_KEY
  MOONSHOT_API_KEY             OPENCODE_API_KEY
  KIMI_API_KEY                 CLOUDFLARE_API_KEY
  CLOUDFLARE_ACCOUNT_ID        CLOUDFLARE_GATEWAY_ID
  XIAOMI_API_KEY               XIAOMI_TOKEN_PLAN_CN_API_KEY
  XIAOMI_TOKEN_PLAN_AMS_API_KEY   XIAOMI_TOKEN_PLAN_SGP_API_KEY
  AWS_PROFILE                  AWS_ACCESS_KEY_ID
  AWS_SECRET_ACCESS_KEY        AWS_BEARER_TOKEN_BEDROCK
  AWS_REGION

${chalk.bold("BUILT-IN TOOLS")}
  read     Read file contents
  bash     Execute bash commands
  edit     Edit files with find/replace
  write    Write files (creates/overwrites)
  grep     Search file contents          (read-only, off by default)
  find     Find files by glob pattern    (read-only, off by default)
  ls       List directory contents       (read-only, off by default)

Full docs: https://github.com/voxcode-dev/voxcode
`);
}
//# sourceMappingURL=args.js.map