"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleApiCreateCommand = exports.resolvePresetDefaultTarget = void 0;
const services_1 = require("../../api/services");
const provider_capabilities_1 = require("../../cliproxy/provider-capabilities");
const local_config_sync_1 = require("../../cliproxy/sync/local-config-sync");
const ui_1 = require("../../utils/ui");
const prompt_1 = require("../../utils/prompt");
const shared_1 = require("./shared");
function resolvePresetOrExit(presetId) {
    if (!presetId) {
        return null;
    }
    const preset = (0, services_1.getPresetById)(presetId);
    if (preset) {
        return preset;
    }
    console.log((0, ui_1.fail)(`Unknown preset: ${presetId}`));
    console.log('');
    console.log('Available presets:');
    (0, services_1.getPresetIds)().forEach((id) => console.log(`  - ${id}`));
    process.exit(1);
}
function showPresetDeprecationNotice(presetId) {
    if ((presetId || '').trim().toLowerCase() !== 'glmt') {
        return;
    }
    console.log((0, ui_1.warn)('Preset "glmt" is deprecated and now maps to the direct "glm" preset.'));
    console.log((0, ui_1.dim)('  Z.AI models already expose thinking natively, so CCS no longer needs GLMT.'));
    console.log((0, ui_1.dim)('  Update scripts/docs to: ccs api create --preset glm'));
    console.log('');
}
async function resolveProfileName(providedName, preset) {
    const name = providedName || preset?.defaultProfileName;
    if (!name) {
        return prompt_1.InteractivePrompt.input('API name', {
            validate: services_1.validateApiName,
        });
    }
    const error = (0, services_1.validateApiName)(name);
    if (error) {
        console.log((0, ui_1.fail)(error));
        process.exit(1);
    }
    return name;
}
async function resolveCliproxyProfileName(provider, providedName, yes) {
    if (providedName) {
        const error = (0, services_1.validateApiName)(providedName);
        if (error) {
            console.log((0, ui_1.fail)(error));
            process.exit(1);
        }
        return providedName;
    }
    const suggestedName = (0, provider_capabilities_1.isCLIProxyProvider)(provider)
        ? (0, services_1.suggestCliproxyBridgeName)(provider)
        : (0, services_1.getDefaultCliproxyBridgeName)('gemini');
    if (yes) {
        return suggestedName;
    }
    return prompt_1.InteractivePrompt.input('API name', {
        default: suggestedName,
        validate: services_1.validateApiName,
    });
}
async function resolveBaseUrl(providedBaseUrl, preset) {
    let baseUrl = providedBaseUrl ?? preset?.baseUrl ?? '';
    if (!baseUrl && !preset) {
        baseUrl = await prompt_1.InteractivePrompt.input('API Base URL (e.g., https://api.example.com/v1 - without /chat/completions)', { validate: services_1.validateUrl });
    }
    else if (!preset) {
        const error = (0, services_1.validateUrl)(baseUrl);
        if (error) {
            console.log((0, ui_1.fail)(error));
            process.exit(1);
        }
    }
    if (!preset) {
        const urlWarning = (0, services_1.getUrlWarning)(baseUrl);
        if (urlWarning) {
            console.log('');
            console.log((0, ui_1.warn)(urlWarning));
            const continueAnyway = await prompt_1.InteractivePrompt.confirm('Continue with this URL anyway?', {
                default: false,
            });
            if (!continueAnyway) {
                baseUrl = await prompt_1.InteractivePrompt.input('API Base URL', {
                    validate: services_1.validateUrl,
                    default: (0, services_1.sanitizeBaseUrl)(baseUrl),
                });
            }
        }
        return baseUrl;
    }
    console.log((0, ui_1.info)(`Using preset: ${preset.name}`));
    console.log((0, ui_1.dim)(`  ${preset.description}`));
    console.log((0, ui_1.dim)(preset.baseUrl
        ? `  Base URL: ${preset.baseUrl}`
        : '  Auth: Native Anthropic API (x-api-key header)'));
    console.log('');
    return baseUrl;
}
async function resolveApiKey(providedApiKey, preset) {
    if (preset?.requiresApiKey === false) {
        if (providedApiKey) {
            console.log((0, ui_1.dim)(`Note: Using provided API key for ${preset.name} (optional)`));
            return providedApiKey;
        }
        console.log((0, ui_1.info)(`No API key required for ${preset.name}`));
        return preset.apiKeyPlaceholder || preset.id;
    }
    if (providedApiKey) {
        return providedApiKey;
    }
    const keyPrompt = preset?.apiKeyHint ? `API Key (${preset.apiKeyHint})` : 'API Key';
    const apiKey = await prompt_1.InteractivePrompt.password(keyPrompt);
    if (!apiKey) {
        console.log((0, ui_1.fail)('API key is required'));
        process.exit(1);
    }
    return apiKey;
}
async function resolveModelConfiguration(baseUrl, preset, providedModel, yes) {
    let openRouterModel;
    let openRouterTierMapping;
    if ((0, services_1.isOpenRouterUrl)(baseUrl) && !providedModel) {
        console.log('');
        console.log((0, ui_1.info)('OpenRouter detected!'));
        const useInteractive = await prompt_1.InteractivePrompt.confirm('Browse models interactively?', {
            default: true,
        });
        if (useInteractive) {
            const selection = await (0, services_1.pickOpenRouterModel)();
            if (selection) {
                openRouterModel = selection.model;
                openRouterTierMapping = selection.tierMapping;
            }
        }
        console.log('');
        console.log((0, ui_1.dim)('Note: For OpenRouter, ANTHROPIC_API_KEY should be empty.'));
    }
    const defaultModel = preset?.defaultModel || 'claude-sonnet-4-6';
    let model = providedModel || openRouterModel || preset?.defaultModel;
    if (!model && !yes && !preset) {
        model = await prompt_1.InteractivePrompt.input('Default model (ANTHROPIC_MODEL)', {
            default: defaultModel,
        });
    }
    model = model || defaultModel;
    let opusModel = openRouterTierMapping?.opus || model;
    let sonnetModel = openRouterTierMapping?.sonnet || model;
    let haikuModel = openRouterTierMapping?.haiku || model;
    const shouldPromptForMapping = !yes && !openRouterTierMapping && !preset;
    if (shouldPromptForMapping) {
        let wantCustomMapping = model !== defaultModel;
        if (!wantCustomMapping) {
            console.log('');
            console.log((0, ui_1.dim)('Some API proxies route different model types to different backends.'));
            wantCustomMapping = await prompt_1.InteractivePrompt.confirm('Configure different models for Opus/Sonnet/Haiku?', { default: false });
        }
        if (wantCustomMapping) {
            console.log('');
            console.log((0, ui_1.dim)('Leave blank to use the default model for each tier.'));
            opusModel =
                (await prompt_1.InteractivePrompt.input('Opus model (ANTHROPIC_DEFAULT_OPUS_MODEL)', {
                    default: model,
                })) || model;
            sonnetModel =
                (await prompt_1.InteractivePrompt.input('Sonnet model (ANTHROPIC_DEFAULT_SONNET_MODEL)', {
                    default: model,
                })) || model;
            haikuModel =
                (await prompt_1.InteractivePrompt.input('Haiku model (ANTHROPIC_DEFAULT_HAIKU_MODEL)', {
                    default: model,
                })) || model;
        }
    }
    return {
        model,
        models: {
            default: model,
            opus: opusModel,
            sonnet: sonnetModel,
            haiku: haikuModel,
        },
    };
}
async function resolveDefaultTarget(preset, providedTarget, yes) {
    const resolvedTarget = resolvePresetDefaultTarget(preset, providedTarget);
    if (resolvedTarget) {
        if (preset?.defaultTarget && !providedTarget) {
            console.log((0, ui_1.info)(`Using preset default target: ${preset.defaultTarget}`));
        }
        return resolvedTarget;
    }
    if (yes) {
        return 'claude';
    }
    const useDroidByDefault = await prompt_1.InteractivePrompt.confirm('Set default target to Factory Droid for this profile?', { default: false });
    return useDroidByDefault ? 'droid' : 'claude';
}
function resolvePresetDefaultTarget(preset, providedTarget) {
    if (providedTarget) {
        return providedTarget;
    }
    if (preset?.defaultTarget) {
        return preset.defaultTarget;
    }
    return null;
}
exports.resolvePresetDefaultTarget = resolvePresetDefaultTarget;
async function resolveClaudeLongContextPreference(models, explicitPreference, yes) {
    if (explicitPreference !== undefined) {
        return explicitPreference;
    }
    if ((0, shared_1.hasExplicitClaudeExtendedContext)(models)) {
        return true;
    }
    if (yes) {
        return false;
    }
    console.log('');
    console.log((0, ui_1.info)('Claude long context is explicit in CCS.'));
    console.log((0, ui_1.dim)('  Plain Claude model IDs stay on standard context unless you opt into [1m].'));
    console.log((0, ui_1.dim)('  Some providers/accounts still require extra usage or PAYG for long-context requests.'));
    console.log((0, ui_1.dim)('  If that entitlement is missing, upstream requests can still return 429.'));
    console.log('');
    return prompt_1.InteractivePrompt.confirm('Enable [1m] for compatible Claude mappings?', {
        default: false,
    });
}
async function handleApiCreateCommand(args) {
    await (0, ui_1.initUI)();
    const parsedArgs = (0, shared_1.parseApiCommandArgs)(args);
    (0, shared_1.exitOnApiCommandErrors)(parsedArgs.errors);
    console.log((0, ui_1.header)('Create API Profile'));
    console.log('');
    if (parsedArgs.cliproxyProvider) {
        const cliproxyProvider = parsedArgs.cliproxyProvider.trim().toLowerCase();
        if (!(0, provider_capabilities_1.isCLIProxyProvider)(cliproxyProvider)) {
            console.log((0, ui_1.fail)(`Unknown CLIProxy provider: ${cliproxyProvider}`));
            console.log('');
            console.log(`Available providers: ${provider_capabilities_1.CLIPROXY_PROVIDER_IDS.join(', ')}`);
            process.exit(1);
        }
        const incompatibleFlags = [
            parsedArgs.baseUrl && '--base-url',
            parsedArgs.apiKey && '--api-key',
            parsedArgs.model && '--model',
            parsedArgs.preset && '--preset',
        ].filter(Boolean);
        if (incompatibleFlags.length > 0) {
            console.log((0, ui_1.fail)(`--cliproxy-provider cannot be combined with ${incompatibleFlags.join(', ')}`));
            process.exit(1);
        }
        const name = await resolveCliproxyProfileName(cliproxyProvider, parsedArgs.name, parsedArgs.yes);
        const target = await resolveDefaultTarget(null, parsedArgs.target, parsedArgs.yes);
        if (name && (0, services_1.apiProfileExists)(name) && !parsedArgs.force) {
            console.log((0, ui_1.fail)(`API '${name}' already exists`));
            console.log(`    Use ${(0, ui_1.color)('--force', 'command')} to overwrite`);
            process.exit(1);
        }
        console.log((0, ui_1.info)(`Using CLIProxy provider: ${(0, provider_capabilities_1.getProviderDisplayName)(cliproxyProvider)} (${cliproxyProvider})`));
        console.log((0, ui_1.dim)('  CCS will create a routed API profile. Provider credentials stay managed by CLIProxy.'));
        console.log('');
        console.log((0, ui_1.info)('Creating API profile...'));
        const result = (0, services_1.createCliproxyBridgeProfile)(cliproxyProvider, {
            force: parsedArgs.force === true,
            name,
            target,
        });
        if (!result.success || !result.name || !result.cliproxyBridge) {
            console.log((0, ui_1.fail)(`Failed to create CLIProxy bridge profile: ${result.error}`));
            process.exit(1);
        }
        try {
            (0, local_config_sync_1.syncToLocalConfig)();
        }
        catch (error) {
            const message = error instanceof Error ? error.message : 'Unknown error';
            console.log(`[i] Auto-sync to CLIProxy config skipped: ${message}`);
        }
        const details = `API:      ${result.name}\n` +
            `Config:   ${(0, services_1.isUsingUnifiedConfig)() ? '~/.ccs/config.yaml' : '~/.ccs/config.json'}\n` +
            `Settings: ${result.settingsFile}\n` +
            `Provider: ${result.cliproxyBridge.providerDisplayName}\n` +
            `Route:    ${result.cliproxyBridge.routePath}\n` +
            `Proxy:    ${result.cliproxyBridge.currentBaseUrl}\n` +
            `Target:   ${target}`;
        console.log('');
        console.log((0, ui_1.infoBox)(details, 'CLIProxy Bridge Created'));
        console.log('');
        console.log((0, ui_1.header)('Usage'));
        if (target === 'droid') {
            console.log(`  ${(0, ui_1.color)(`ccs ${result.name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# uses droid by default')}`);
            console.log(`  ${(0, ui_1.color)(`ccs-droid ${result.name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# explicit droid alias')}`);
            console.log(`  ${(0, ui_1.color)(`ccsd ${result.name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# legacy shortcut')}`);
        }
        else {
            console.log(`  ${(0, ui_1.color)(`ccs ${result.name} "your prompt"`, 'command')}`);
            console.log(`  ${(0, ui_1.color)(`ccs-droid ${result.name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# explicit one-off droid alias')}`);
            console.log(`  ${(0, ui_1.color)(`ccs ${result.name} --target droid "your prompt"`, 'command')} ${(0, ui_1.dim)('# target flag alternative')}`);
        }
        if (cliproxyProvider === 'codex') {
            console.log(`  ${(0, ui_1.color)(`ccs ${result.name} --target codex "your prompt"`, 'command')} ${(0, ui_1.dim)('# native Codex runtime')}`);
            console.log(`  ${(0, ui_1.color)(`ccs-codex ${result.name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# explicit Codex alias')}`);
            console.log(`  ${(0, ui_1.color)(`ccsx ${result.name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# short alias')}`);
        }
        console.log('');
        console.log((0, ui_1.dim)('Manage provider accounts, keys, and models in: ccs cliproxy'));
        return;
    }
    showPresetDeprecationNotice(parsedArgs.preset);
    const preset = resolvePresetOrExit(parsedArgs.preset);
    const name = await resolveProfileName(parsedArgs.name, preset);
    if ((0, services_1.apiProfileExists)(name) && !parsedArgs.force) {
        console.log((0, ui_1.fail)(`API '${name}' already exists`));
        console.log(`    Use ${(0, ui_1.color)('--force', 'command')} to overwrite`);
        process.exit(1);
    }
    let baseUrl = await resolveBaseUrl(parsedArgs.baseUrl, preset);
    if (baseUrl && baseUrl.includes('api.anthropic.com') && !preset) {
        console.log('');
        console.log((0, ui_1.info)('Anthropic Direct API detected. Base URL will be omitted for native auth.'));
        baseUrl = '';
    }
    const apiKey = await resolveApiKey(parsedArgs.apiKey, preset);
    const { models } = await resolveModelConfiguration(baseUrl, preset, parsedArgs.model, parsedArgs.yes);
    const hasClaudeMappings = (0, shared_1.hasClaudeModelMapping)(models);
    const shouldEnableClaudeLongContext = hasClaudeMappings
        ? await resolveClaudeLongContextPreference(models, parsedArgs.extendedContext, parsedArgs.yes)
        : false;
    const finalModels = hasClaudeMappings
        ? (0, shared_1.applyClaudeExtendedContextPreference)(models, shouldEnableClaudeLongContext)
        : models;
    const target = await resolveDefaultTarget(preset, parsedArgs.target, parsedArgs.yes);
    if (parsedArgs.extendedContext !== undefined && !hasClaudeMappings) {
        console.log('');
        console.log((0, ui_1.dim)('No compatible Claude mappings were detected, so --1m/--no-1m did not change models.'));
    }
    console.log('');
    console.log((0, ui_1.info)('Creating API profile...'));
    const result = (0, services_1.createApiProfile)(name, baseUrl || '', apiKey, finalModels, target, undefined, parsedArgs.extraModels);
    if (!result.success) {
        console.log((0, ui_1.fail)(`Failed to create API profile: ${result.error}`));
        process.exit(1);
    }
    try {
        (0, local_config_sync_1.syncToLocalConfig)();
    }
    catch (error) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        console.log(`[i] Auto-sync to CLIProxy config skipped: ${message}`);
    }
    const hasCustomMapping = finalModels.opus !== finalModels.default ||
        finalModels.sonnet !== finalModels.default ||
        finalModels.haiku !== finalModels.default;
    let details = `API:      ${name}\n` +
        `Config:   ${(0, services_1.isUsingUnifiedConfig)() ? '~/.ccs/config.yaml' : '~/.ccs/config.json'}\n` +
        `Settings: ${result.settingsFile}\n` +
        `Base URL: ${baseUrl}\n` +
        `Model:    ${finalModels.default}\n` +
        `Target:   ${target}`;
    if (hasClaudeMappings) {
        details += `\nLongCtx:  ${shouldEnableClaudeLongContext
            ? 'compatible Claude mappings use [1m]'
            : 'standard Claude context'}`;
    }
    if (hasCustomMapping) {
        details +=
            `\n\nModel Mapping:\n` +
                `  Opus:   ${finalModels.opus}\n` +
                `  Sonnet: ${finalModels.sonnet}\n` +
                `  Haiku:  ${finalModels.haiku}`;
    }
    if (parsedArgs.extraModels && parsedArgs.extraModels.length > 0) {
        details += `\nExtraModels: ${parsedArgs.extraModels.join(', ')}`;
    }
    console.log('');
    console.log((0, ui_1.infoBox)(details, 'API Profile Created'));
    if (hasClaudeMappings) {
        console.log('');
        console.log((0, ui_1.dim)(shouldEnableClaudeLongContext
            ? 'CCS saved [1m] on compatible Claude mappings. Provider-side extra-usage requirements can still reject long-context requests.'
            : 'Claude mappings were saved with standard context. Use --1m later if you want CCS to write [1m] explicitly.'));
    }
    console.log('');
    console.log((0, ui_1.header)('Usage'));
    if (target === 'droid') {
        console.log(`  ${(0, ui_1.color)(`ccs ${name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# uses droid by default')}`);
        console.log(`  ${(0, ui_1.color)(`ccs-droid ${name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# explicit droid alias')}`);
        console.log(`  ${(0, ui_1.color)(`ccsd ${name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# legacy shortcut')}`);
        console.log(`  ${(0, ui_1.color)(`ccs ${name} --target claude "your prompt"`, 'command')} ${(0, ui_1.dim)('# override to Claude')}`);
    }
    else {
        console.log(`  ${(0, ui_1.color)(`ccs ${name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# uses claude by default')}`);
        console.log(`  ${(0, ui_1.color)(`ccs-droid ${name} "your prompt"`, 'command')} ${(0, ui_1.dim)('# explicit one-off droid alias')}`);
        console.log(`  ${(0, ui_1.color)(`ccs ${name} --target droid "your prompt"`, 'command')} ${(0, ui_1.dim)('# target flag alternative')}`);
    }
    console.log('');
    console.log((0, ui_1.header)('Edit Settings'));
    console.log(`  ${(0, ui_1.dim)('To modify env vars later:')}`);
    console.log(`  ${(0, ui_1.color)(`nano ${result.settingsFile.replace('~', '$HOME')}`, 'command')}`);
    console.log('');
}
exports.handleApiCreateCommand = handleApiCreateCommand;
//# sourceMappingURL=create-command.js.map