"use strict";
/**
 * CLIProxy dispatch flow — OAuth-based profiles (gemini, codex, agy, qwen) or user-defined variants.
 *
 * Extracted from src/ccs.ts main() profileInfo.type === 'cliproxy' branch.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.runCliproxyFlow = void 0;
const helpers_1 = require("../../utils/helpers");
const ui_1 = require("../../utils/ui");
const cliproxy_1 = require("../../cliproxy");
const env_builder_1 = require("../../cliproxy/config/env-builder");
const port_manager_1 = require("../../cliproxy/config/port-manager");
const websearch_manager_1 = require("../../utils/websearch-manager");
const image_analysis_1 = require("../../utils/image-analysis");
const image_analyzer_profile_hook_injector_1 = require("../../utils/hooks/image-analyzer-profile-hook-injector");
const hooks_1 = require("../../utils/hooks");
const targets_1 = require("../../targets");
async function runCliproxyFlow(ctx) {
    const { profileInfo, resolvedTarget, claudeCli, targetAdapter, targetRemainingArgs, runtimeReasoningOverride, codexRuntimeConfigOverrides, remainingArgs, } = ctx;
    const imageAnalysisMcpReady = resolvedTarget === 'claude' ? (0, image_analysis_1.ensureImageAnalysisMcpOrThrow)() : true;
    if (resolvedTarget === 'claude') {
        (0, websearch_manager_1.ensureWebSearchMcpOrThrow)();
    }
    const provider = profileInfo.provider || profileInfo.name;
    const expandedCliproxySettingsPath = profileInfo.settingsPath
        ? (0, helpers_1.expandPath)(profileInfo.settingsPath)
        : undefined;
    if (resolvedTarget === 'claude') {
        if (imageAnalysisMcpReady) {
            (0, image_analyzer_profile_hook_injector_1.removeImageAnalysisProfileHook)(profileInfo.name, expandedCliproxySettingsPath);
        }
        else {
            const imageAnalysisFallbackHookReady = (0, hooks_1.prepareImageAnalysisFallbackHook)();
            (0, image_analyzer_profile_hook_injector_1.ensureProfileHooks)({
                profileName: profileInfo.name,
                profileType: profileInfo.type,
                cliproxyProvider: provider,
                isComposite: profileInfo.isComposite,
                settingsPath: expandedCliproxySettingsPath,
                sharedHookInstalled: imageAnalysisFallbackHookReady,
            });
        }
    }
    const customSettingsPath = profileInfo.settingsPath; // undefined for hardcoded profiles
    const variantPort = profileInfo.port; // variant-specific port for isolation
    const cliproxyPort = variantPort || (0, port_manager_1.resolveLifecyclePort)();
    if (resolvedTarget !== 'claude') {
        const adapter = targetAdapter;
        if (!adapter) {
            console.error((0, ui_1.fail)(`Target adapter not found for "${resolvedTarget}"`));
            process.exitCode = 1;
            return;
        }
        if (!adapter.supportsProfileType('cliproxy')) {
            console.error((0, ui_1.fail)(`${adapter.displayName} does not support CLIProxy profiles`));
            process.exitCode = 1;
            return;
        }
        // Keep CLIProxy management/auth flags on Claude flow only.
        const unsupportedCliproxyFlags = [
            '--auth',
            '--logout',
            '--accounts',
            '--add',
            '--use',
            '--config',
            '--headless',
            '--paste-callback',
            '--port-forward',
            '--nickname',
            '--kiro-auth-method',
            '--kiro-idc-start-url',
            '--kiro-idc-region',
            '--kiro-idc-flow',
            '--backend',
            '--proxy-host',
            '--proxy-port',
            '--proxy-protocol',
            '--proxy-auth-token',
            '--proxy-timeout',
            '--local-proxy',
            '--remote-only',
            '--no-fallback',
            '--allow-self-signed',
            '--1m',
            '--no-1m',
        ];
        const providedUnsupportedFlag = unsupportedCliproxyFlags.find((flag) => targetRemainingArgs.includes(flag) ||
            targetRemainingArgs.some((arg) => arg.startsWith(`${flag}=`)));
        if (providedUnsupportedFlag) {
            console.error((0, ui_1.fail)(`${providedUnsupportedFlag} is only supported when running CLIProxy profiles on Claude target`));
            console.error((0, ui_1.info)(`Run with Claude target: ccs ${profileInfo.name} --target claude ...`));
            process.exitCode = 1;
            return;
        }
        // For Droid execution path, require existing OAuth auth and running local proxy.
        if (profileInfo.isComposite && profileInfo.compositeTiers) {
            const compositeProviders = [
                ...new Set(Object.values(profileInfo.compositeTiers).map((tier) => tier.provider)),
            ];
            const missingProvider = compositeProviders.find((p) => !(0, cliproxy_1.isAuthenticated)(p));
            if (missingProvider) {
                console.error((0, ui_1.fail)(`Missing OAuth auth for composite tier provider: ${missingProvider}`));
                console.error((0, ui_1.info)(`Authenticate first: ccs ${missingProvider} --auth`));
                process.exitCode = 1;
                return;
            }
        }
        else if (!(0, cliproxy_1.isAuthenticated)(provider)) {
            console.error((0, ui_1.fail)(`No OAuth authentication found for provider: ${provider}`));
            console.error((0, ui_1.info)(`Authenticate first: ccs ${provider} --auth`));
            process.exitCode = 1;
            return;
        }
        const ensureServiceResult = await (0, cliproxy_1.ensureCliproxyService)(cliproxyPort, targetRemainingArgs.includes('--verbose') || targetRemainingArgs.includes('-v'));
        if (!ensureServiceResult.started) {
            console.error((0, ui_1.fail)(ensureServiceResult.error || 'Failed to start local CLIProxy service'));
            process.exitCode = 1;
            return;
        }
        const envVars = profileInfo.isComposite && profileInfo.compositeTiers && profileInfo.compositeDefaultTier
            ? (0, env_builder_1.getCompositeEnvVars)(profileInfo.compositeTiers, profileInfo.compositeDefaultTier, cliproxyPort, customSettingsPath)
            : (0, env_builder_1.getEffectiveEnvVars)(provider, cliproxyPort, customSettingsPath);
        const creds = {
            profile: profileInfo.name,
            baseUrl: envVars['ANTHROPIC_BASE_URL'] || '',
            apiKey: envVars['ANTHROPIC_AUTH_TOKEN'] || '',
            model: envVars['ANTHROPIC_MODEL'] || undefined,
            provider: (0, targets_1.resolveDroidProvider)({
                provider: envVars['CCS_DROID_PROVIDER'] || envVars['DROID_PROVIDER'],
                baseUrl: envVars['ANTHROPIC_BASE_URL'],
                model: envVars['ANTHROPIC_MODEL'],
            }),
            reasoningOverride: runtimeReasoningOverride,
            runtimeConfigOverrides: codexRuntimeConfigOverrides,
            envVars,
        };
        if (!creds.baseUrl || !creds.apiKey) {
            console.error((0, ui_1.fail)(`Missing CLIProxy runtime credentials for ${profileInfo.name} (ANTHROPIC_BASE_URL/AUTH_TOKEN)`));
            console.error((0, ui_1.info)('Reconfigure with: ccs config > CLIProxy, or run ccs <provider> --config'));
            process.exitCode = 1;
            return;
        }
        await adapter.prepareCredentials(creds);
        const targetArgs = adapter.buildArgs(profileInfo.name, targetRemainingArgs, {
            creds,
            profileType: profileInfo.type,
            binaryInfo: ctx.targetBinaryInfo || undefined,
        });
        const targetEnv = adapter.buildEnv(creds, profileInfo.type);
        adapter.exec(targetArgs, targetEnv, { binaryInfo: ctx.targetBinaryInfo || undefined });
        return;
    }
    await (0, cliproxy_1.execClaudeWithCLIProxy)(claudeCli, provider, remainingArgs, {
        customSettingsPath,
        port: cliproxyPort,
        isComposite: profileInfo.isComposite,
        compositeTiers: profileInfo.compositeTiers,
        compositeDefaultTier: profileInfo.compositeDefaultTier,
        profileName: profileInfo.name,
    });
}
exports.runCliproxyFlow = runCliproxyFlow;
//# sourceMappingURL=cliproxy-flow.js.map