"use strict";
/**
 * CLI argument parsing and normalization utilities.
 *
 * Extracted from src/ccs.ts (lines 129-244, 246-296, 371-392).
 * Pure functions — no side effects except console.error and process.exit.
 *
 * Also contains bootstrapAndParseEarlyCli() — the Phase A bootstrap extracted
 * from main() (lines 128-232 of the original). Handles: adapter registration,
 * UI init, --config-dir flag, cloud-sync warnings, completion short-circuit,
 * normalizeLegacyCursorArgs, resolveBrowserLaunchFlagResolution, codex passthrough.
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNativeCodexPassthroughArgs = exports.shouldPassthroughNativeCodexCommand = exports.shouldNormalizeNativeClaudeEffort = exports.normalizeNativeClaudeEffortArgs = exports.exitWithRuntimeReasoningFlagError = exports.normalizeCodexRuntimeReasoningOverride = exports.resolveRuntimeReasoningFlags = exports.printCursorLegacySubcommandDeprecation = exports.normalizeLegacyCursorArgs = exports.detectProfile = exports.NATIVE_CLAUDE_EFFORT_LEVEL_SET = exports.NATIVE_CLAUDE_EFFORT_LEVELS = exports.CODEX_NATIVE_PASSTHROUGH_SUBCOMMANDS = exports.CODEX_NATIVE_PASSTHROUGH_FLAGS = exports.CODEX_RUNTIME_REASONING_LEVELS = exports.bootstrapAndParseEarlyCli = void 0;
const fs = __importStar(require("fs"));
const ui_1 = require("../utils/ui");
const constants_1 = require("../cursor/constants");
const target_resolver_1 = require("../targets/target-resolver");
const droid_reasoning_runtime_1 = require("../targets/droid-reasoning-runtime");
const config_manager_1 = require("../utils/config-manager");
const browser_1 = require("../utils/browser");
/**
 * Phase A bootstrap: runs everything that must happen before config loading and profile detection.
 *
 * Side-effects preserved from original main():
 * - Dynamic import of initUI
 * - setGlobalConfigDir (--config-dir flag)
 * - Cloud-sync warnings
 * - Completion short-circuit via tryHandleRootCommand
 * - Codex native passthrough via execNativeCodexCommand
 *
 * Adapter registration (registerTarget calls) stays in main() because it is
 * singleton wiring with no dependency on the parsed args.
 */
async function bootstrapAndParseEarlyCli(rawArgs) {
    let args = rawArgs;
    const isCompletionCommand = args[0] === '__complete';
    // Initialize UI colors early to ensure consistent colored output
    // Must happen before any status messages (ok, info, fail, etc.)
    if (!isCompletionCommand && process.stdout.isTTY && !process.env['CI']) {
        const { initUI } = await Promise.resolve().then(() => __importStar(require('../utils/ui')));
        await initUI();
    }
    // Parse --config-dir flag (must happen before any config loading)
    const configDirIdx = args.findIndex((a) => a === '--config-dir' || a.startsWith('--config-dir='));
    if (configDirIdx !== -1) {
        const arg = args[configDirIdx];
        let configDirValue;
        let spliceCount = 1;
        if (arg.startsWith('--config-dir=')) {
            configDirValue = arg.split('=').slice(1).join('=');
        }
        else {
            configDirValue = args[configDirIdx + 1];
            spliceCount = 2;
        }
        if (!configDirValue || configDirValue.startsWith('-')) {
            console.error((0, ui_1.fail)('--config-dir requires a path argument'));
            process.exit(1);
        }
        try {
            const stat = fs.statSync(configDirValue);
            if (!stat.isDirectory()) {
                console.error((0, ui_1.fail)(`Not a directory: ${configDirValue}`));
                process.exit(1);
            }
        }
        catch {
            console.error((0, ui_1.fail)(`Config directory not found: ${configDirValue}`));
            console.error((0, ui_1.info)('Create the directory first, then copy your config files into it.'));
            process.exit(1);
        }
        (0, config_manager_1.setGlobalConfigDir)(configDirValue);
        // Security warning: cloud sync paths expose OAuth tokens
        const cloudService = (0, config_manager_1.detectCloudSyncPath)(configDirValue);
        if (!isCompletionCommand && cloudService) {
            console.error((0, ui_1.warn)(`CCS directory is under ${cloudService}.`));
            console.error('    OAuth tokens in cliproxy/auth/ will be synced to cloud.');
            console.error('    Consider: CCS_DIR=/path/outside/cloud ccs ...');
        }
        // Remove consumed args so they don't leak to Claude CLI
        // Clone the array before splicing so the original rawArgs is unaffected
        args = [...args];
        args.splice(configDirIdx, spliceCount);
    }
    else if (process.env.CCS_DIR) {
        // Also warn for CCS_DIR env var pointing to cloud sync
        const cloudService = (0, config_manager_1.detectCloudSyncPath)(process.env.CCS_DIR);
        if (!isCompletionCommand && cloudService) {
            console.error((0, ui_1.warn)(`CCS directory is under ${cloudService}.`));
            console.error('    OAuth tokens in cliproxy/auth/ will be synced to cloud.');
            console.error('    Consider: CCS_DIR=/path/outside/cloud ccs ...');
        }
    }
    else if (process.env.CCS_HOME) {
        // Also warn for CCS_HOME env var pointing to cloud sync
        const cloudService = (0, config_manager_1.detectCloudSyncPath)(process.env.CCS_HOME);
        if (!isCompletionCommand && cloudService) {
            console.error((0, ui_1.warn)(`CCS directory is under ${cloudService}.`));
            console.error('    OAuth tokens in cliproxy/auth/ will be synced to cloud.');
            console.error('    Consider: CCS_DIR=/path/outside/cloud ccs ...');
        }
    }
    if (isCompletionCommand) {
        const { tryHandleRootCommand } = await Promise.resolve().then(() => __importStar(require('../commands/root-command-router')));
        await tryHandleRootCommand(args);
        return { args, isCompletionCommand, browserLaunchOverride: undefined, exitNow: true };
    }
    args = normalizeLegacyCursorArgs(args);
    let browserLaunchOverride;
    try {
        const browserLaunchFlags = (0, browser_1.resolveBrowserLaunchFlagResolution)(args);
        browserLaunchOverride = browserLaunchFlags.override;
        args = browserLaunchFlags.argsWithoutFlags;
    }
    catch (error) {
        console.error((0, ui_1.fail)(error.message));
        process.exit(1);
        // process.exit never returns but TypeScript needs the unreachable return
        return { args, isCompletionCommand, browserLaunchOverride: undefined, exitNow: true };
    }
    if (shouldPassthroughNativeCodexCommand(args)) {
        const { execNativeCodexCommand } = await Promise.resolve().then(() => __importStar(require('./target-executor')));
        execNativeCodexCommand(args);
        return { args, isCompletionCommand, browserLaunchOverride: undefined, exitNow: true };
    }
    return { args, isCompletionCommand, browserLaunchOverride, exitNow: false };
}
exports.bootstrapAndParseEarlyCli = bootstrapAndParseEarlyCli;
// ========== Constants ==========
exports.CODEX_RUNTIME_REASONING_LEVELS = new Set([
    'minimal',
    'low',
    'medium',
    'high',
    'xhigh',
]);
exports.CODEX_NATIVE_PASSTHROUGH_FLAGS = new Set(['--help', '-h', '--version', '-v']);
exports.CODEX_NATIVE_PASSTHROUGH_SUBCOMMANDS = new Set([
    'a',
    'app',
    'app-server',
    'apply',
    'cloud',
    'completion',
    'debug',
    'e',
    'exec',
    'exec-server',
    'features',
    'fork',
    'help',
    'login',
    'logout',
    'mcp',
    'mcp-server',
    'plugin',
    'remote-control',
    'resume',
    'review',
    'sandbox',
]);
exports.NATIVE_CLAUDE_EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
exports.NATIVE_CLAUDE_EFFORT_LEVEL_SET = new Set(exports.NATIVE_CLAUDE_EFFORT_LEVELS);
// ========== Profile Detection ==========
/**
 * Smart profile detection — first non-flag arg is the profile name.
 */
function detectProfile(args) {
    if (args.length === 0 || args[0].startsWith('-')) {
        // No args or first arg is a flag → use default profile
        return { profile: 'default', remainingArgs: args };
    }
    else {
        // First arg doesn't start with '-' → treat as profile name
        return { profile: args[0], remainingArgs: args.slice(1) };
    }
}
exports.detectProfile = detectProfile;
function normalizeLegacyCursorArgs(args) {
    if (args[0] === 'legacy' && args[1] === 'cursor') {
        return [constants_1.LEGACY_CURSOR_PROFILE_NAME, ...args.slice(2)];
    }
    return args;
}
exports.normalizeLegacyCursorArgs = normalizeLegacyCursorArgs;
function printCursorLegacySubcommandDeprecation(subcommand) {
    console.error((0, ui_1.warn)(`\`ccs cursor ${subcommand}\` is deprecated for the legacy Cursor IDE bridge.`));
    console.error((0, ui_1.warn)(`Use \`ccs legacy cursor ${subcommand}\` for the old bridge, or \`ccs cursor --auth|--accounts|--config\` for the CLIProxy provider.`));
    console.error('');
}
exports.printCursorLegacySubcommandDeprecation = printCursorLegacySubcommandDeprecation;
// ========== Runtime Reasoning Flags ==========
function resolveRuntimeReasoningFlags(args, envThinkingValue) {
    const runtime = (0, droid_reasoning_runtime_1.resolveDroidReasoningRuntime)(args, envThinkingValue);
    if (runtime.duplicateDisplays.length > 0) {
        console.error((0, ui_1.warn)(`[!] Multiple reasoning flags detected. Using first occurrence: ${runtime.sourceDisplay || '<first-flag>'}`));
    }
    return {
        argsWithoutReasoningFlags: runtime.argsWithoutReasoningFlags,
        reasoningOverride: runtime.reasoningOverride,
        reasoningSource: runtime.sourceFlag
            ? 'flag'
            : runtime.reasoningOverride !== undefined
                ? 'env'
                : undefined,
        sourceDisplay: runtime.sourceDisplay,
    };
}
exports.resolveRuntimeReasoningFlags = resolveRuntimeReasoningFlags;
function normalizeCodexRuntimeReasoningOverride(value) {
    return typeof value === 'string' && exports.CODEX_RUNTIME_REASONING_LEVELS.has(value) ? value : undefined;
}
exports.normalizeCodexRuntimeReasoningOverride = normalizeCodexRuntimeReasoningOverride;
function exitWithRuntimeReasoningFlagError(message, options) {
    console.error((0, ui_1.fail)(message));
    console.error('    Examples: --thinking low, --thinking 8192, --thinking off');
    console.error(`    Codex alias: --effort ${options.codexAliasLevels}`);
    if (options.includeDroidExecExample) {
        console.error('    Droid exec: --reasoning-effort high');
    }
    process.exit(1);
}
exports.exitWithRuntimeReasoningFlagError = exitWithRuntimeReasoningFlagError;
// ========== Native Claude Effort Normalization ==========
function normalizeNativeClaudeEffortArgs(args) {
    const normalizedArgs = [];
    const allowedValues = exports.NATIVE_CLAUDE_EFFORT_LEVELS.join(', ');
    for (let i = 0; i < args.length; i++) {
        const arg = args[i];
        if (arg === '--effort') {
            const rawValue = args[i + 1];
            if (!rawValue || rawValue.startsWith('-') || !rawValue.trim()) {
                throw new Error(`--effort requires a value: ${allowedValues}`);
            }
            const value = rawValue.toLowerCase();
            if (!exports.NATIVE_CLAUDE_EFFORT_LEVEL_SET.has(value)) {
                throw new Error(`Invalid --effort value: ${rawValue}. Expected one of: ${allowedValues}.`);
            }
            normalizedArgs.push(arg, value);
            i++;
            continue;
        }
        if (arg.startsWith('--effort=')) {
            const rawValue = arg.slice('--effort='.length);
            if (!rawValue.trim()) {
                throw new Error(`--effort requires a value: ${allowedValues}`);
            }
            const value = rawValue.toLowerCase();
            if (!exports.NATIVE_CLAUDE_EFFORT_LEVEL_SET.has(value)) {
                throw new Error(`Invalid --effort value: ${rawValue}. Expected one of: ${allowedValues}.`);
            }
            normalizedArgs.push(`--effort=${value}`);
            continue;
        }
        normalizedArgs.push(arg);
    }
    return normalizedArgs;
}
exports.normalizeNativeClaudeEffortArgs = normalizeNativeClaudeEffortArgs;
function shouldNormalizeNativeClaudeEffort(profileType) {
    return profileType === 'default' || profileType === 'account' || profileType === 'settings';
}
exports.shouldNormalizeNativeClaudeEffort = shouldNormalizeNativeClaudeEffort;
// ========== Native Codex Passthrough ==========
function shouldPassthroughNativeCodexCommand(args) {
    return getNativeCodexPassthroughArgs(args) !== null;
}
exports.shouldPassthroughNativeCodexCommand = shouldPassthroughNativeCodexCommand;
function getNativeCodexPassthroughArgs(args) {
    const targetArgs = (0, target_resolver_1.stripTargetFlag)(args);
    if ((0, target_resolver_1.resolveTargetType)(args) !== 'codex' || targetArgs.length === 0) {
        return null;
    }
    const firstArg = targetArgs[0] || '';
    if (exports.CODEX_NATIVE_PASSTHROUGH_FLAGS.has(firstArg)) {
        return targetArgs;
    }
    if (exports.CODEX_NATIVE_PASSTHROUGH_SUBCOMMANDS.has(firstArg)) {
        return targetArgs;
    }
    const secondArg = targetArgs[1] || '';
    if (firstArg === 'codex' && exports.CODEX_NATIVE_PASSTHROUGH_FLAGS.has(secondArg)) {
        return targetArgs.slice(1);
    }
    if (firstArg === 'codex' && exports.CODEX_NATIVE_PASSTHROUGH_SUBCOMMANDS.has(secondArg)) {
        return targetArgs.slice(1);
    }
    return null;
}
exports.getNativeCodexPassthroughArgs = getNativeCodexPassthroughArgs;
//# sourceMappingURL=cli-argument-parser.js.map