"use strict";
/**
 * Cursor CLI Command
 *
 * Handles `ccs cursor [subcommand]` commands.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleCursorCommand = void 0;
const cursor_1 = require("../cursor");
const unified_config_types_1 = require("../config/unified-config-types");
const cursor_command_display_1 = require("./cursor-command-display");
const ui_1 = require("../utils/ui");
const config_loader_facade_1 = require("../config/config-loader-facade");
const LEGACY_CURSOR_COMMAND = 'ccs legacy cursor';
const CLIPROXY_CURSOR_COMMAND = 'ccs cursor';
function printLegacyCursorDeprecationNotice() {
    console.log((0, ui_1.info)(`Deprecated compatibility path. \`${CLIPROXY_CURSOR_COMMAND}\` now belongs to the CLIProxy Cursor provider; use \`${LEGACY_CURSOR_COMMAND}\` for the old bridge.`));
    console.log('');
}
/**
 * Handle cursor subcommand.
 */
async function handleCursorCommand(args) {
    const subcommand = args[0];
    switch (subcommand) {
        case 'auth':
            return handleAuth(args.slice(1));
        case 'status':
            return handleStatus();
        case 'probe':
            return handleProbe();
        case 'models':
            return handleModels();
        case 'start':
            return handleStart();
        case 'stop':
            return handleStop();
        case 'enable':
            return handleEnable();
        case 'disable':
            return handleDisable();
        case undefined:
            return handleHelp();
        case 'help':
        case '--help':
        case '-h':
            return handleHelp();
        default:
            console.error((0, ui_1.fail)(`Unknown subcommand: ${subcommand}`));
            console.error('');
            void handleHelp(); // Print help but keep exit code 1
            return 1;
    }
}
exports.handleCursorCommand = handleCursorCommand;
function handleHelp() {
    return (0, cursor_command_display_1.renderCursorHelp)();
}
function parseOptionValue(args, key) {
    const exactIndex = args.findIndex((arg) => arg === key);
    if (exactIndex !== -1 && args[exactIndex + 1]) {
        return args[exactIndex + 1];
    }
    const prefix = `${key}=`;
    const withEquals = args.find((arg) => arg.startsWith(prefix));
    if (withEquals) {
        return withEquals.slice(prefix.length);
    }
    return undefined;
}
function printAutoDetectFailure(result) {
    console.error((0, ui_1.fail)(`Auto-detection failed: ${result.error ?? 'Unknown error'}`));
    if (result.checkedPaths?.length && result.reason === 'db_not_found') {
        console.log('');
        console.log('Checked paths:');
        for (const candidate of result.checkedPaths) {
            console.log(`  - ${candidate}`);
        }
    }
    if (result.reason === 'sqlite_unavailable') {
        console.log('');
        console.log('Recommended next steps:');
        console.log('  1. Install sqlite3 so CCS can read Cursor state automatically');
        console.log('  2. Or use manual import immediately');
    }
    else if (result.reason === 'db_query_failed') {
        console.log('');
        console.log('Recommended next steps:');
        console.log('  1. Close Cursor IDE and retry auto-detect');
        console.log('  2. If the database remains unreadable, use manual import');
    }
}
/**
 * Handle auth subcommand.
 */
async function handleAuth(args) {
    printLegacyCursorDeprecationNotice();
    const manual = args.includes('--manual');
    if (manual) {
        const accessToken = parseOptionValue(args, '--token') ?? parseOptionValue(args, '--access-token') ?? '';
        const machineId = parseOptionValue(args, '--machine-id') ?? parseOptionValue(args, '--machineId') ?? '';
        if (!accessToken || !machineId) {
            console.error((0, ui_1.fail)(`Manual auth requires both token and machine ID.\n\nExample:\n  ${LEGACY_CURSOR_COMMAND} auth --manual --token <token> --machine-id <machine-id>`));
            return 1;
        }
        if (!(0, cursor_1.validateToken)(accessToken, machineId)) {
            console.error((0, ui_1.fail)('Invalid token or machine ID format'));
            return 1;
        }
        (0, cursor_1.saveCredentials)({
            accessToken,
            machineId,
            authMethod: 'manual',
            importedAt: new Date().toISOString(),
        });
        console.log((0, ui_1.ok)('Cursor credentials imported (manual mode)'));
        console.log('');
        console.log('Next steps:');
        console.log(`  0. Preferred auth:     ${CLIPROXY_CURSOR_COMMAND} --auth`);
        console.log(`  1. Enable integration: ${LEGACY_CURSOR_COMMAND} enable`);
        console.log(`  2. Start daemon:       ${LEGACY_CURSOR_COMMAND} start`);
        return 0;
    }
    console.log((0, ui_1.info)('Importing Cursor IDE authentication...'));
    console.log('');
    console.log((0, ui_1.info)('Attempting auto-detection...'));
    const autoResult = (0, cursor_1.autoDetectTokens)();
    if (autoResult.found && autoResult.accessToken && autoResult.machineId) {
        (0, cursor_1.saveCredentials)({
            accessToken: autoResult.accessToken,
            machineId: autoResult.machineId,
            authMethod: 'auto-detect',
            importedAt: new Date().toISOString(),
        });
        console.log((0, ui_1.ok)('Auto-detected Cursor credentials'));
        console.log('');
        console.log('Next steps:');
        console.log(`  0. Preferred auth:     ${CLIPROXY_CURSOR_COMMAND} --auth`);
        console.log(`  1. Enable integration: ${LEGACY_CURSOR_COMMAND} enable`);
        console.log(`  2. Start daemon:       ${LEGACY_CURSOR_COMMAND} start`);
        console.log(`  3. Check status:       ${LEGACY_CURSOR_COMMAND} status`);
        return 0;
    }
    console.log('');
    printAutoDetectFailure(autoResult);
    console.log('');
    console.log('Manual fallback:');
    console.log(`  ${LEGACY_CURSOR_COMMAND} auth --manual --token <token> --machine-id <machine-id>`);
    console.log('');
    return 1;
}
async function handleStatus() {
    printLegacyCursorDeprecationNotice();
    const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
    const authStatus = (0, cursor_1.checkAuthStatus)();
    const daemonStatus = await (0, cursor_1.getDaemonStatus)(cursorConfig.port);
    (0, cursor_command_display_1.renderCursorStatus)(cursorConfig, authStatus, daemonStatus);
    return 0;
}
async function handleProbe() {
    printLegacyCursorDeprecationNotice();
    const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
    const result = await (0, cursor_1.probeCursorRuntime)(cursorConfig);
    (0, cursor_command_display_1.renderCursorProbe)(result);
    return result.ok ? 0 : 1;
}
async function handleModels() {
    printLegacyCursorDeprecationNotice();
    const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
    const models = await (0, cursor_1.getAvailableModels)(cursorConfig.port);
    const defaultModel = (0, cursor_1.getDefaultModel)();
    (0, cursor_command_display_1.renderCursorModels)(models, defaultModel);
    return 0;
}
/**
 * Handle start subcommand.
 */
async function handleStart() {
    printLegacyCursorDeprecationNotice();
    const cursorConfig = (0, config_loader_facade_1.getCursorConfig)();
    if (!cursorConfig.enabled) {
        console.error((0, ui_1.fail)(`Cursor integration is disabled. Run: ${LEGACY_CURSOR_COMMAND} enable`));
        return 1;
    }
    const authStatus = (0, cursor_1.checkAuthStatus)();
    if (!authStatus.authenticated) {
        console.error((0, ui_1.fail)(`Not authenticated. Run: ${LEGACY_CURSOR_COMMAND} auth`));
        return 1;
    }
    if (authStatus.expired) {
        console.error((0, ui_1.fail)(`Credentials expired. Run: ${LEGACY_CURSOR_COMMAND} auth`));
        return 1;
    }
    console.log((0, ui_1.info)(`Starting cursor daemon on port ${cursorConfig.port}...`));
    const result = await (0, cursor_1.startDaemon)({
        port: cursorConfig.port,
        ghost_mode: cursorConfig.ghost_mode,
    });
    if (result.success) {
        console.log((0, ui_1.ok)(`Daemon started (PID: ${result.pid})`));
        return 0;
    }
    else {
        console.error((0, ui_1.fail)(result.error || 'Failed to start daemon'));
        return 1;
    }
}
/**
 * Handle stop subcommand.
 */
async function handleStop() {
    printLegacyCursorDeprecationNotice();
    console.log((0, ui_1.info)('Stopping cursor daemon...'));
    const result = await (0, cursor_1.stopDaemon)();
    if (result.success) {
        console.log((0, ui_1.ok)('Daemon stopped'));
        return 0;
    }
    else {
        console.error((0, ui_1.fail)(result.error || 'Failed to stop daemon'));
        return 1;
    }
}
/**
 * Handle enable subcommand.
 */
async function handleEnable() {
    printLegacyCursorDeprecationNotice();
    (0, config_loader_facade_1.mutateConfig)((config) => {
        if (!config.cursor) {
            config.cursor = { ...unified_config_types_1.DEFAULT_CURSOR_CONFIG };
        }
        config.cursor.enabled = true;
    });
    console.log((0, ui_1.ok)('Cursor integration enabled'));
    console.log('');
    console.log('Next steps:');
    console.log(`  0. Preferred auth: ${CLIPROXY_CURSOR_COMMAND} --auth`);
    console.log(`  1. Authenticate: ${LEGACY_CURSOR_COMMAND} auth`);
    console.log(`  2. Start daemon: ${LEGACY_CURSOR_COMMAND} start`);
    console.log(`  3. Check status: ${LEGACY_CURSOR_COMMAND} status`);
    return 0;
}
/**
 * Handle disable subcommand.
 */
async function handleDisable() {
    printLegacyCursorDeprecationNotice();
    (0, config_loader_facade_1.mutateConfig)((config) => {
        if (config.cursor) {
            config.cursor.enabled = false;
        }
    });
    console.log((0, ui_1.ok)('Cursor integration disabled'));
    return 0;
}
//# sourceMappingURL=cursor-command.js.map