"use strict";
/**
 * Settings dispatch flow — settings-based profiles (glm, glmt, kimi, etc.).
 *
 * Extracted from src/ccs.ts main() profileInfo.type === 'settings' branch.
 * Image-analysis prep is large enough to split; see settings-image-analysis-prep.ts.
 */
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.runSettingsFlow = void 0;
const config_manager_1 = require("../../utils/config-manager");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const helpers_1 = require("../../utils/helpers");
const api_key_validator_1 = require("../../utils/api-key-validator");
const websearch_manager_1 = require("../../utils/websearch-manager");
const image_analysis_1 = require("../../utils/image-analysis");
const browser_1 = require("../../utils/browser");
const config_loader_facade_2 = require("../../config/config-loader-facade");
const image_analyzer_profile_hook_injector_1 = require("../../utils/hooks/image-analyzer-profile-hook-injector");
const ui_1 = require("../../utils/ui");
const shell_executor_1 = require("../../utils/shell-executor");
const glmt_deprecation_1 = require("../../utils/glmt-deprecation");
const openai_compat_launch_settings_1 = require("../../utils/openai-compat-launch-settings");
const claude_subcommand_detector_1 = require("../../utils/claude-subcommand-detector");
const targets_1 = require("../../targets");
const cliproxy_profile_bridge_1 = require("../../api/services/cliproxy-profile-bridge");
const proxy_1 = require("../../proxy");
const settings_image_analysis_prep_1 = require("./settings-image-analysis-prep");
async function runSettingsFlow(ctx) {
    const { profileInfo, resolvedTarget, claudeCli, targetAdapter, targetBinaryInfo, targetRemainingArgs, nativeClaudeRemainingArgs, runtimeReasoningOverride, codexRuntimeConfigOverrides, claudeBrowserExposure, claudeAttachConfig, resolvedSettingsPath: preResolvedSettingsPath, resolvedSettings: preResolvedSettings, resolvedCliproxyBridge: preResolvedCliproxyBridge, resolveProfileContinuityInheritance, remainingArgs, } = ctx;
    const imageAnalysisMcpReady = resolvedTarget === 'claude' ? (0, image_analysis_1.ensureImageAnalysisMcpOrThrow)() : true;
    const browserAttachRuntime = resolvedTarget === 'claude' &&
        claudeBrowserExposure?.exposeForLaunch &&
        claudeAttachConfig?.enabled
        ? await (0, browser_1.resolveOptionalBrowserAttachRuntime)(claudeAttachConfig)
        : undefined;
    const browserRuntimeEnv = browserAttachRuntime?.runtimeEnv;
    if (browserAttachRuntime?.warning) {
        process.stderr.write(`${(0, ui_1.warn)(browserAttachRuntime.warning)}\n`);
    }
    if (resolvedTarget === 'claude') {
        (0, websearch_manager_1.ensureWebSearchMcpOrThrow)();
        if (browserRuntimeEnv) {
            (0, browser_1.ensureBrowserMcpOrThrow)();
        }
    }
    // Display WebSearch status (single line, equilibrium UX)
    (0, websearch_manager_1.displayWebSearchStatus)();
    const continuityInheritance = resolvedTarget === 'claude'
        ? await resolveProfileContinuityInheritance({
            profileName: profileInfo.name,
            profileType: profileInfo.type,
            target: resolvedTarget,
        })
        : {};
    if (continuityInheritance.sourceAccount && process.env.CCS_DEBUG) {
        console.error((0, ui_1.info)(`Continuity inheritance active: profile "${profileInfo.name}" -> account "${continuityInheritance.sourceAccount}"`));
    }
    const inheritedClaudeConfigDir = continuityInheritance.claudeConfigDir;
    (0, websearch_manager_1.syncWebSearchMcpToConfigDir)(inheritedClaudeConfigDir);
    (0, image_analysis_1.syncImageAnalysisMcpToConfigDir)(inheritedClaudeConfigDir);
    if (browserRuntimeEnv &&
        inheritedClaudeConfigDir &&
        !(0, browser_1.syncBrowserMcpToConfigDir)(inheritedClaudeConfigDir)) {
        throw new Error('Browser MCP is enabled, but CCS could not sync the browser MCP config into the inherited Claude instance.');
    }
    const expandedSettingsPath = preResolvedSettingsPath ??
        (profileInfo.settingsPath
            ? (0, helpers_1.expandPath)(profileInfo.settingsPath)
            : (0, config_manager_1.getSettingsPath)(profileInfo.name));
    const settings = preResolvedSettings ?? (0, config_loader_facade_1.loadSettings)(expandedSettingsPath);
    const cliproxyBridge = preResolvedCliproxyBridge ?? (0, cliproxy_profile_bridge_1.resolveCliproxyBridgeMetadata)(settings);
    let imageAnalysisFallbackHookReady;
    if (resolvedTarget === 'claude') {
        if (imageAnalysisMcpReady) {
            (0, image_analyzer_profile_hook_injector_1.removeImageAnalysisProfileHook)(profileInfo.name, expandedSettingsPath);
        }
        else {
            imageAnalysisFallbackHookReady = (await Promise.resolve().then(() => __importStar(require('../../utils/hooks')))).prepareImageAnalysisFallbackHook();
            (0, image_analyzer_profile_hook_injector_1.ensureProfileHooks)({
                profileName: profileInfo.name,
                profileType: profileInfo.type,
                settingsPath: expandedSettingsPath,
                settings,
                cliproxyBridge,
                sharedHookInstalled: imageAnalysisFallbackHookReady,
            });
        }
    }
    if (resolvedTarget !== 'claude') {
        const compatibility = (0, targets_1.evaluateTargetRuntimeCompatibility)({
            target: resolvedTarget,
            profileType: profileInfo.type,
            cliproxyBridgeProvider: cliproxyBridge?.provider ?? null,
        });
        if (!compatibility.supported) {
            console.error((0, ui_1.fail)(compatibility.reason ||
                `${targetAdapter?.displayName || resolvedTarget} does not support this profile.`));
            if (compatibility.suggestion) {
                console.error((0, ui_1.info)(compatibility.suggestion));
            }
            process.exit(1);
        }
    }
    const rawSettingsEnv = profileInfo.env ?? settings.env ?? {};
    const isDeprecatedGlmtProfile = (0, glmt_deprecation_1.isDeprecatedGlmtProfileName)(profileInfo.name);
    const glmtNormalization = isDeprecatedGlmtProfile
        ? (0, glmt_deprecation_1.normalizeDeprecatedGlmtEnv)(rawSettingsEnv)
        : null;
    const settingsEnv = glmtNormalization?.env ?? rawSettingsEnv;
    if (glmtNormalization) {
        for (const message of glmtNormalization.warnings) {
            console.error((0, ui_1.warn)(message));
        }
    }
    // Pre-flight validation for Z.AI-compatible profiles.
    if (profileInfo.name === 'glm' || isDeprecatedGlmtProfile) {
        const apiKey = settingsEnv['ANTHROPIC_AUTH_TOKEN'];
        if (apiKey) {
            const validation = await (0, api_key_validator_1.validateGlmKey)(apiKey, settingsEnv['ANTHROPIC_BASE_URL']);
            if (!validation.valid) {
                console.error('');
                console.error((0, ui_1.fail)(validation.error || 'API key validation failed'));
                if (validation.suggestion) {
                    console.error('');
                    console.error(validation.suggestion);
                }
                console.error('');
                console.error((0, ui_1.info)('To skip validation: CCS_SKIP_PREFLIGHT=1 ccs glm "prompt"'));
                process.exit(1);
            }
        }
    }
    if (profileInfo.name === 'mm') {
        const apiKey = settingsEnv['ANTHROPIC_AUTH_TOKEN'];
        if (apiKey) {
            const validation = await (0, api_key_validator_1.validateMiniMaxKey)(apiKey, settingsEnv['ANTHROPIC_BASE_URL']);
            if (!validation.valid) {
                console.error('');
                console.error((0, ui_1.fail)(validation.error || 'API key validation failed'));
                if (validation.suggestion) {
                    console.error('');
                    console.error(validation.suggestion);
                }
                console.error('');
                console.error((0, ui_1.info)('To skip validation: CCS_SKIP_PREFLIGHT=1 ccs mm "prompt"'));
                process.exit(1);
            }
        }
    }
    // Pre-flight validation for Anthropic direct profiles (ANTHROPIC_API_KEY + no BASE_URL)
    {
        const anthropicApiKey = settingsEnv['ANTHROPIC_API_KEY'];
        const hasBaseUrl = !!settingsEnv['ANTHROPIC_BASE_URL'];
        if (anthropicApiKey && !hasBaseUrl) {
            const validation = await (0, api_key_validator_1.validateAnthropicKey)(anthropicApiKey);
            if (!validation.valid) {
                console.error('');
                console.error((0, ui_1.fail)(validation.error || 'API key validation failed'));
                if (validation.suggestion) {
                    console.error('');
                    console.error(validation.suggestion);
                }
                console.error('');
                console.error((0, ui_1.info)(`To skip validation: CCS_SKIP_PREFLIGHT=1 ccs ${profileInfo.name} "prompt"`));
                process.exit(1);
            }
        }
    }
    // Image analysis env resolution (split into sibling helper to stay under LOC budget)
    const imageAnalysisEnv = await (0, settings_image_analysis_prep_1.resolveSettingsImageAnalysisEnv)({
        profileInfo,
        resolvedTarget,
        settings,
        cliproxyBridge,
        imageAnalysisMcpReady,
        imageAnalysisFallbackHookReady,
        remainingArgs,
        targetRemainingArgs,
    });
    const webSearchEnv = (0, websearch_manager_1.getWebSearchHookEnv)();
    // Get global env vars (DISABLE_TELEMETRY, etc.) for third-party profiles
    const globalEnvConfig = (0, config_loader_facade_2.getGlobalEnvConfig)();
    const globalEnv = globalEnvConfig.enabled ? globalEnvConfig.env : {};
    // Log global env injection for visibility (debug mode only)
    if (globalEnvConfig.enabled && Object.keys(globalEnv).length > 0 && process.env.CCS_DEBUG) {
        const envNames = Object.keys(globalEnv).join(', ');
        console.error((0, ui_1.info)(`Global env: ${envNames}`));
    }
    // For Claude target launches that already pass `--settings`, keep runtime env free of
    // ANTHROPIC routing/auth while preserving non-routing profile env so nested Team/subagent
    // sessions can still inherit model intent and other profile-scoped runtime flags.
    const settingsRuntimeEnv = (0, shell_executor_1.stripBrowserEnv)({ ...globalEnv, ...settingsEnv });
    const claudeRuntimeEnvVars = {
        ...(0, shell_executor_1.stripAnthropicRoutingEnv)(settingsRuntimeEnv, settingsEnv),
        ...(inheritedClaudeConfigDir ? { CLAUDE_CONFIG_DIR: inheritedClaudeConfigDir } : {}),
        ...webSearchEnv,
        ...imageAnalysisEnv,
        ...(browserRuntimeEnv || {}),
        CCS_PROFILE_TYPE: 'settings',
        CCS_STRIP_INHERITED_ANTHROPIC_ENV: '1',
    };
    // Non-Claude targets still need effective credentials injected directly.
    const envVars = {
        ...settingsRuntimeEnv,
        ...(inheritedClaudeConfigDir ? { CLAUDE_CONFIG_DIR: inheritedClaudeConfigDir } : {}),
        ...webSearchEnv,
        ...imageAnalysisEnv,
        ...(browserRuntimeEnv || {}),
        CCS_PROFILE_TYPE: 'settings',
    };
    // Dispatch through target adapter for non-claude targets
    if (resolvedTarget !== 'claude') {
        const adapter = targetAdapter;
        if (!adapter) {
            console.error((0, ui_1.fail)(`Target adapter not found for "${resolvedTarget}"`));
            process.exit(1);
        }
        const directAnthropicBaseUrl = settingsEnv['ANTHROPIC_BASE_URL'] ||
            (settingsEnv['ANTHROPIC_API_KEY'] ? 'https://api.anthropic.com' : '');
        const creds = {
            profile: profileInfo.name,
            baseUrl: directAnthropicBaseUrl,
            apiKey: settingsEnv['ANTHROPIC_AUTH_TOKEN'] || settingsEnv['ANTHROPIC_API_KEY'] || '',
            model: settingsEnv['ANTHROPIC_MODEL'],
            provider: (0, targets_1.resolveDroidProvider)({
                provider: settingsEnv['CCS_DROID_PROVIDER'] || settingsEnv['DROID_PROVIDER'],
                baseUrl: directAnthropicBaseUrl,
                model: settingsEnv['ANTHROPIC_MODEL'],
            }),
            reasoningOverride: runtimeReasoningOverride,
            runtimeConfigOverrides: codexRuntimeConfigOverrides,
            envVars,
        };
        await adapter.prepareCredentials(creds);
        const targetArgs = adapter.buildArgs(profileInfo.name, targetRemainingArgs, {
            creds,
            profileType: profileInfo.type,
            binaryInfo: targetBinaryInfo || undefined,
        });
        const targetEnv = adapter.buildEnv(creds, profileInfo.type);
        adapter.exec(targetArgs, targetEnv, { binaryInfo: targetBinaryInfo || undefined });
        return;
    }
    const imageAnalysisArgs = imageAnalysisMcpReady
        ? (0, image_analysis_1.appendThirdPartyImageAnalysisToolArgs)(nativeClaudeRemainingArgs)
        : nativeClaudeRemainingArgs;
    const browserArgs = browserRuntimeEnv
        ? (0, browser_1.appendBrowserToolArgs)(imageAnalysisArgs)
        : imageAnalysisArgs;
    const openAICompatProfile = (0, proxy_1.resolveOpenAICompatProfileConfig)(profileInfo.name, expandedSettingsPath, settingsEnv);
    if (openAICompatProfile) {
        const proxyStart = await (0, proxy_1.startOpenAICompatProxy)(openAICompatProfile, {
            insecure: openAICompatProfile.insecure,
        });
        if (!proxyStart.success) {
            console.error((0, ui_1.fail)(proxyStart.error || 'Failed to start local OpenAI-compatible proxy'));
            process.exit(1);
        }
        console.error((0, ui_1.info)(`Using local OpenAI-compatible proxy for "${profileInfo.name}" on port ${proxyStart.port}`));
        const proxyEnv = {
            ...envVars,
            ...(0, proxy_1.buildOpenAICompatProxyEnv)(openAICompatProfile, proxyStart.port, proxyStart.authToken || '', inheritedClaudeConfigDir),
        };
        delete proxyEnv.ANTHROPIC_API_KEY;
        const launchSettings = (0, openai_compat_launch_settings_1.createOpenAICompatLaunchSettings)(expandedSettingsPath, settings);
        // Claude subcommands reject `--settings` (it flips `agents` to list mode).
        // Routing env vars still flow via proxyEnv. Issue #1218.
        const isSubcommand = (0, claude_subcommand_detector_1.isClaudeSubcommandInvocation)(browserArgs);
        const subcommandArgs = isSubcommand
            ? (0, claude_subcommand_detector_1.stripClaudeSubcommandSessionArgs)(browserArgs)
            : browserArgs;
        const launchArgs = isSubcommand
            ? (0, websearch_manager_1.appendThirdPartyWebSearchToolArgs)(subcommandArgs)
            : [
                '--settings',
                launchSettings.settingsPath,
                ...(0, websearch_manager_1.appendThirdPartyWebSearchToolArgs)(browserArgs),
            ];
        const traceEnv = (0, websearch_manager_1.createWebSearchTraceContext)({
            launcher: 'ccs.settings-profile.proxy',
            args: launchArgs,
            profile: profileInfo.name,
            profileType: profileInfo.type,
            settingsPath: expandedSettingsPath,
        });
        (0, shell_executor_1.execClaude)(claudeCli, launchArgs, { ...proxyEnv, ...traceEnv }, launchSettings.cleanup);
        return;
    }
    // Skip `--settings` for Claude subcommands so the interactive agent view
    // works; env vars from the settings file still flow via envVars. Issue #1218.
    const isSubcommand = (0, claude_subcommand_detector_1.isClaudeSubcommandInvocation)(browserArgs);
    const subcommandArgs = isSubcommand ? (0, claude_subcommand_detector_1.stripClaudeSubcommandSessionArgs)(browserArgs) : browserArgs;
    const launchArgs = isSubcommand
        ? (0, websearch_manager_1.appendThirdPartyWebSearchToolArgs)(subcommandArgs)
        : ['--settings', expandedSettingsPath, ...(0, websearch_manager_1.appendThirdPartyWebSearchToolArgs)(browserArgs)];
    const traceEnv = (0, websearch_manager_1.createWebSearchTraceContext)({
        launcher: 'ccs.settings-profile',
        args: launchArgs,
        profile: profileInfo.name,
        profileType: profileInfo.type,
        settingsPath: expandedSettingsPath,
    });
    (0, shell_executor_1.execClaude)(claudeCli, launchArgs, { ...claudeRuntimeEnvVars, ...traceEnv });
}
exports.runSettingsFlow = runSettingsFlow;
//# sourceMappingURL=settings-flow.js.map