"use strict";
/**
 * Pre-dispatch side-effect handlers.
 *
 * Extracted from src/ccs.ts (Phase B, lines 145-254 after Phase A extraction).
 * Each handler may short-circuit the dispatch by returning true.
 *
 * Handles: update check, auto-migrate, recovery-manager, root-command router,
 * provider help shortcut, copilot/cursor subcommand routing, first-time install hint.
 */
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.runPreDispatchHandlers = void 0;
const ui_1 = require("../utils/ui");
const provider_capabilities_1 = require("../cliproxy/provider-capabilities");
const constants_1 = require("../copilot/constants");
const constants_2 = require("../cursor/constants");
const update_checker_1 = require("../utils/update-checker");
const root_command_router_1 = require("../commands/root-command-router");
const environment_builder_1 = require("./environment-builder");
const cli_argument_parser_1 = require("./cli-argument-parser");
// ========== Pre-Dispatch Runner ==========
/**
 * Run all pre-dispatch side-effect handlers in sequence.
 * Returns true if a handler consumed the command (caller should return immediately).
 * Returns false if dispatch should continue normally.
 *
 * All process.exit calls and dynamic imports are preserved at original call sites.
 */
async function runPreDispatchHandlers(ctx) {
    const { args, cliLogger } = ctx;
    const firstArg = args[0];
    // Update check: show cached notification + refresh background cache
    const skipUpdateCheck = [
        'version',
        '--version',
        '-v',
        'help',
        '--help',
        '-h',
        'update',
        '--update',
    ];
    if (process.stdout.isTTY && !process.env['CI'] && !skipUpdateCheck.includes(firstArg ?? '')) {
        // 1. Show cached update notification (async for proper UI)
        await (0, environment_builder_1.showCachedUpdateNotification)();
        // 2. Refresh cache in background if stale (non-blocking)
        if ((0, update_checker_1.isCacheStale)()) {
            (0, environment_builder_1.refreshUpdateCache)();
        }
    }
    // CCS_NO_PRE_DISPATCH guard — set by `ccsx auth use` to keep stdout clean
    // for shell eval. Must be checked BEFORE autoMigrate/recovery, both of which
    // write to stdout and would otherwise contaminate `eval "$(ccsx auth use <name>)"`.
    // See: src/codex-auth/commands/use-command.ts (C2 in plan.md §Validation findings)
    if (process.env.CCS_NO_PRE_DISPATCH === '1') {
        return false;
    }
    // Auto-migrate to unified config format (silent if already migrated)
    // Skip if user is explicitly running migrate command
    if (firstArg !== 'migrate') {
        const { autoMigrate } = await Promise.resolve().then(() => __importStar(require('../config/migration-manager')));
        await autoMigrate();
    }
    // Auto-recovery for missing configuration (BEFORE any early-exit commands)
    // Recovery is safe to run early - it only creates missing files with safe defaults
    // Wrapped in try-catch to prevent blocking --version/--help on permission errors
    try {
        const RecoveryManagerModule = await Promise.resolve().then(() => __importStar(require('../management/recovery-manager')));
        const RecoveryManager = RecoveryManagerModule.default;
        const recovery = new RecoveryManager();
        const recovered = recovery.recoverAll();
        if (recovered) {
            recovery.showRecoveryHints();
        }
    }
    catch (err) {
        cliLogger.warn('recovery.failed', 'Auto-recovery failed during CLI startup', {
            message: err.message,
        });
        // Recovery is best-effort - don't block basic CLI functionality
        console.warn('[!] Recovery failed:', err.message);
    }
    // Root command router (handles --help, --version, config, doctor, etc.)
    if (await (0, root_command_router_1.tryHandleRootCommand)(args)) {
        return true;
    }
    // Provider help shortcut: `ccs gemini --help` → provider-specific help page
    if (typeof firstArg === 'string' &&
        (0, provider_capabilities_1.isCLIProxyProvider)(firstArg) &&
        args.length > 1 &&
        (args.includes('--help') || args.includes('-h'))) {
        const { showProviderShortcutHelp } = await Promise.resolve().then(() => __importStar(require('../commands/help-command')));
        await showProviderShortcutHelp(firstArg);
        return true;
    }
    // Special case: copilot command (GitHub Copilot integration)
    // Route known subcommands to command handler, keep all other args as profile passthrough.
    if (firstArg === 'copilot' && args.length > 1) {
        const copilotToken = args[1];
        const shouldRouteToCopilotCommand = (0, constants_1.isCopilotSubcommandToken)(copilotToken);
        if (shouldRouteToCopilotCommand) {
            const { handleCopilotCommand } = await Promise.resolve().then(() => __importStar(require('../commands/copilot-command')));
            const exitCode = await handleCopilotCommand(args.slice(1));
            process.exit(exitCode);
        }
    }
    // Special case: explicit legacy Cursor bridge namespace.
    if (firstArg === constants_2.LEGACY_CURSOR_PROFILE_NAME && args.length > 1) {
        const { handleCursorCommand } = await Promise.resolve().then(() => __importStar(require('../commands/cursor-command')));
        const cursorToken = args[1];
        if ((0, constants_2.isCursorSubcommandToken)(cursorToken)) {
            const exitCode = await handleCursorCommand(args.slice(1));
            process.exit(exitCode);
        }
    }
    // Compatibility shim: old `ccs cursor <subcommand>` still forwards to the legacy bridge
    // for one migration window, but bare/positional `ccs cursor` now belongs to CLIProxy.
    if (firstArg === 'cursor' && args.length > 1) {
        const { handleCursorCommand } = await Promise.resolve().then(() => __importStar(require('../commands/cursor-command')));
        const cursorToken = args[1];
        if ((0, constants_2.isCursorSubcommandToken)(cursorToken) && cursorToken !== '--help' && cursorToken !== '-h') {
            (0, cli_argument_parser_1.printCursorLegacySubcommandDeprecation)(cursorToken);
            const exitCode = await handleCursorCommand(args.slice(1));
            process.exit(exitCode);
        }
    }
    // First-time install: offer setup wizard for interactive users
    // Check independently of recovery status (user may have empty config.yaml)
    // Skip if headless, CI, or non-TTY environment
    const { isFirstTimeInstall } = await Promise.resolve().then(() => __importStar(require('../commands/setup-command')));
    if (process.stdout.isTTY && !process.env['CI'] && isFirstTimeInstall()) {
        console.log('');
        console.log((0, ui_1.info)('First-time install detected. Run `ccs setup` for guided configuration.'));
        console.log('    Or use `ccs config` for the web dashboard.');
        console.log('');
    }
    return false;
}
exports.runPreDispatchHandlers = runPreDispatchHandlers;
//# sourceMappingURL=pre-dispatch.js.map