"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.executeCursorProfile = exports.resolveCursorImageAnalysisEnv = exports.generateCursorEnv = void 0;
const child_process_1 = require("child_process");
const cliproxy_1 = require("../cliproxy");
const port_manager_1 = require("../cliproxy/config/port-manager");
const ui_1 = require("../utils/ui");
const websearch_manager_1 = require("../utils/websearch-manager");
const hooks_1 = require("../utils/hooks");
const shell_executor_1 = require("../utils/shell-executor");
const cursor_auth_1 = require("./cursor-auth");
const cursor_daemon_1 = require("./cursor-daemon");
const config_loader_facade_1 = require("../config/config-loader-facade");
function generateCursorEnv(config, claudeConfigDir) {
    const opusModel = config.opus_model || config.model;
    const sonnetModel = config.sonnet_model || config.model;
    const haikuModel = config.haiku_model || config.model;
    return {
        ANTHROPIC_BASE_URL: `http://127.0.0.1:${config.port}`,
        ANTHROPIC_AUTH_TOKEN: 'cursor-managed',
        ANTHROPIC_MODEL: config.model,
        ANTHROPIC_DEFAULT_OPUS_MODEL: opusModel,
        ANTHROPIC_DEFAULT_SONNET_MODEL: sonnetModel,
        ANTHROPIC_SMALL_FAST_MODEL: haikuModel,
        ANTHROPIC_DEFAULT_HAIKU_MODEL: haikuModel,
        DISABLE_NON_ESSENTIAL_MODEL_CALLS: '1',
        CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
        ...(claudeConfigDir ? { CLAUDE_CONFIG_DIR: claudeConfigDir } : {}),
    };
}
exports.generateCursorEnv = generateCursorEnv;
async function resolveCursorImageAnalysisEnv(verbose = false, deps = {}) {
    const getImageAnalysisHookEnvFn = deps.getImageAnalysisHookEnv ?? hooks_1.getImageAnalysisHookEnv;
    const resolveImageAnalysisRuntimeStatusFn = deps.resolveImageAnalysisRuntimeStatus ?? hooks_1.resolveImageAnalysisRuntimeStatus;
    const ensureCliproxyServiceFn = deps.ensureCliproxyService ?? cliproxy_1.ensureCliproxyService;
    const resolveLifecyclePortFn = deps.resolveLifecyclePort ?? port_manager_1.resolveLifecyclePort;
    const env = getImageAnalysisHookEnvFn({
        profileName: 'cursor',
        profileType: 'cursor',
    });
    const provider = env['CCS_CURRENT_PROVIDER'];
    if (env['CCS_IMAGE_ANALYSIS_SKIP'] === '1' || !provider) {
        return { env, warning: null };
    }
    const status = await resolveImageAnalysisRuntimeStatusFn({
        profileName: 'cursor',
        profileType: 'cursor',
    });
    if (status.effectiveRuntimeMode === 'native-read') {
        return {
            env: {
                ...env,
                CCS_CURRENT_PROVIDER: '',
                CCS_IMAGE_ANALYSIS_SKIP: '1',
            },
            warning: `${status.effectiveRuntimeReason || `Image analysis via ${provider} is unavailable.`} This session will use native Read.`,
        };
    }
    if (status.proxyReadiness === 'stopped') {
        const ensureServiceResult = await ensureCliproxyServiceFn(resolveLifecyclePortFn(), verbose);
        if (!ensureServiceResult.started) {
            return {
                env: {
                    ...env,
                    CCS_CURRENT_PROVIDER: '',
                    CCS_IMAGE_ANALYSIS_SKIP: '1',
                },
                warning: `Image analysis via ${provider} is unavailable because CCS could not start the local CLIProxy service. This session will use native Read.`,
            };
        }
    }
    return { env, warning: null };
}
exports.resolveCursorImageAnalysisEnv = resolveCursorImageAnalysisEnv;
async function executeCursorProfile(config, claudeArgs, claudeConfigDir, claudeCliPath = 'claude') {
    if (!config.enabled) {
        console.error((0, ui_1.fail)('Cursor integration is not enabled.'));
        console.error('');
        console.error('Enable it first: ccs legacy cursor enable');
        return 1;
    }
    const authStatus = (0, cursor_auth_1.checkAuthStatus)();
    if (!authStatus.authenticated) {
        console.error((0, ui_1.fail)('Cursor credentials not found.'));
        console.error('');
        console.error('Authenticate first: ccs legacy cursor auth');
        return 1;
    }
    if (authStatus.expired) {
        console.error((0, ui_1.fail)('Cursor credentials have expired.'));
        console.error('');
        console.error('Refresh them with: ccs legacy cursor auth');
        return 1;
    }
    let daemonRunning = await (0, cursor_daemon_1.isDaemonRunning)(config.port);
    if (!daemonRunning) {
        if (config.auto_start) {
            console.log((0, ui_1.info)('Starting cursor daemon...'));
            const result = await (0, cursor_daemon_1.startDaemon)({
                port: config.port,
                ghost_mode: config.ghost_mode,
            });
            if (!result.success) {
                console.error((0, ui_1.fail)(`Failed to start cursor daemon: ${result.error}`));
                return 1;
            }
            console.log((0, ui_1.ok)(`Daemon started on port ${config.port}`));
            daemonRunning = true;
        }
        else {
            console.error((0, ui_1.fail)('Cursor daemon is not running.'));
            console.error('');
            console.error('Start the daemon:');
            console.error('  ccs legacy cursor start');
            console.error('Or enable auto_start in the Cursor config section.');
            return 1;
        }
    }
    const cursorEnv = generateCursorEnv(config, claudeConfigDir);
    const globalEnvConfig = (0, config_loader_facade_1.getGlobalEnvConfig)();
    const globalEnv = globalEnvConfig.enabled ? globalEnvConfig.env : {};
    const webSearchEnv = (0, websearch_manager_1.getWebSearchHookEnv)();
    const { env: imageAnalysisEnv, warning: imageAnalysisWarning } = await resolveCursorImageAnalysisEnv();
    const env = (0, shell_executor_1.stripClaudeCodeEnv)({
        ...process.env,
        ...globalEnv,
        ...cursorEnv,
        ...webSearchEnv,
        ...imageAnalysisEnv,
        CCS_PROFILE_TYPE: 'cursor',
    });
    console.log((0, ui_1.info)(`Using Cursor proxy (model: ${config.model})`));
    if (imageAnalysisWarning) {
        console.log((0, ui_1.info)(imageAnalysisWarning));
    }
    console.log('');
    (0, websearch_manager_1.syncWebSearchMcpToConfigDir)(claudeConfigDir);
    return new Promise((resolve) => {
        const launchArgs = (0, websearch_manager_1.appendThirdPartyWebSearchToolArgs)(claudeArgs);
        const traceEnv = (0, websearch_manager_1.createWebSearchTraceContext)({
            launcher: 'cursor.executor',
            args: launchArgs,
            profile: 'cursor',
            profileType: 'cursor',
            claudeConfigDir,
        });
        const proc = (0, child_process_1.spawn)(claudeCliPath, launchArgs, {
            stdio: 'inherit',
            env: { ...env, ...traceEnv },
            shell: process.platform === 'win32',
        });
        proc.on('close', (code) => {
            resolve(code ?? 0);
        });
        proc.on('error', (err) => {
            console.error((0, ui_1.fail)(`Failed to start Claude: ${err.message}`));
            resolve(1);
        });
    });
}
exports.executeCursorProfile = executeCursorProfile;
//# sourceMappingURL=cursor-profile-executor.js.map