"use strict";
/**
 * CLIProxy Variant Management
 *
 * Handles:
 * - ccs cliproxy create [name]
 * - ccs cliproxy remove <name>
 */
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.handleEdit = exports.handleRemove = exports.handleCreate = exports.parseProfileArgs = void 0;
const path = __importStar(require("path"));
const account_manager_1 = require("../../cliproxy/accounts/account-manager");
const oauth_handler_1 = require("../../cliproxy/auth/oauth-handler");
const profile_detector_1 = require("../../auth/profile-detector");
const catalog_routing_1 = require("../../cliproxy/services/catalog-routing");
const model_catalog_1 = require("../../cliproxy/model-catalog");
const managed_model_prefixes_1 = require("../../cliproxy/ai-providers/managed-model-prefixes");
const target_metadata_1 = require("../../targets/target-metadata");
const ui_1 = require("../../utils/ui");
const prompt_1 = require("../../utils/prompt");
const services_1 = require("../../cliproxy/services");
const platform_detector_1 = require("../../cliproxy/binary/platform-detector");
const email_account_identity_1 = require("../../cliproxy/accounts/email-account-identity");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const variantManagedPrefixProviders = new Set();
async function ensureVariantManagedModelPrefixes(provider) {
    if (variantManagedPrefixProviders.has(provider)) {
        return;
    }
    await (0, managed_model_prefixes_1.ensureManagedModelPrefixes)([provider]);
    variantManagedPrefixProviders.add(provider);
}
function parseTargetValue(rawValue) {
    const normalized = rawValue.trim().toLowerCase();
    if ((0, target_metadata_1.isPersistedTargetType)(normalized)) {
        return normalized;
    }
    return null;
}
function parseProfileArgs(args) {
    const result = { errors: [] };
    let parseOptions = true;
    for (let i = 0; i < args.length; i++) {
        const arg = args[i];
        if (parseOptions && arg === '--') {
            parseOptions = false;
            continue;
        }
        if (parseOptions && arg === '--provider' && args[i + 1]) {
            result.provider = args[++i];
        }
        else if (parseOptions && arg === '--model' && args[i + 1]) {
            result.model = args[++i];
        }
        else if (parseOptions && arg === '--account' && args[i + 1]) {
            result.account = args[++i];
        }
        else if (parseOptions && arg === '--target') {
            const rawValue = args[i + 1];
            if (!rawValue || rawValue.startsWith('-')) {
                result.errors.push('Missing value for --target');
            }
            else {
                i += 1;
                const parsedTarget = parseTargetValue(rawValue);
                if (!parsedTarget) {
                    result.errors.push(`Invalid --target value "${rawValue}". Use: ${(0, target_metadata_1.getPersistedTargetChoices)()}`);
                }
                else {
                    result.target = parsedTarget;
                }
            }
        }
        else if (parseOptions && arg.startsWith('--target=')) {
            const rawValue = arg.slice('--target='.length);
            const parsedTarget = parseTargetValue(rawValue);
            if (!parsedTarget) {
                result.errors.push(`Invalid --target value "${rawValue}". Use: ${(0, target_metadata_1.getPersistedTargetChoices)()}`);
            }
            else {
                result.target = parsedTarget;
            }
        }
        else if (parseOptions && arg === '--force') {
            result.force = true;
        }
        else if (parseOptions && (arg === '--yes' || arg === '-y')) {
            result.yes = true;
        }
        else if (parseOptions && arg === '--composite') {
            result.composite = true;
        }
        else if ((!parseOptions || !arg.startsWith('-')) && !result.name) {
            result.name = arg;
        }
    }
    return result;
}
exports.parseProfileArgs = parseProfileArgs;
function formatModelOption(model) {
    const tierBadge = model.tier === 'ultra'
        ? (0, ui_1.color)(' [Ultra]', 'warning')
        : model.tier === 'pro'
            ? (0, ui_1.color)(' [Pro]', 'warning')
            : '';
    return `${model.name}${tierBadge}`;
}
const CODEX_EFFORTS_IN_ORDER = ['minimal', 'low', 'medium', 'high', 'xhigh'];
function getCodexSelectableEfforts(model) {
    const maxLevel = model.thinking?.maxLevel;
    const maxIndex = CODEX_EFFORTS_IN_ORDER.findIndex((effort) => effort === maxLevel);
    if (maxIndex < 0)
        return [];
    return CODEX_EFFORTS_IN_ORDER.slice(0, maxIndex + 1);
}
function getCodexModelOptionValues(model, modelId) {
    const serviceTiers = model.codexServiceTiers ?? [];
    const optionValues = [modelId];
    for (const serviceTier of serviceTiers) {
        optionValues.push(`${modelId}-${serviceTier}`);
    }
    for (const effort of getCodexSelectableEfforts(model)) {
        const effortModelId = `${modelId}-${effort}`;
        optionValues.push(effortModelId);
        for (const serviceTier of serviceTiers) {
            optionValues.push(`${effortModelId}-${serviceTier}`);
        }
    }
    return optionValues;
}
function getModelOptionsForProvider(provider, catalog, routing) {
    return catalog.models.flatMap((model) => {
        const modelId = getSelectableModelId(model.id, routing);
        const optionValues = provider === 'codex' ? getCodexModelOptionValues(model, modelId) : [modelId];
        return optionValues.map((optionValue) => ({
            id: optionValue,
            label: provider === 'codex'
                ? `${optionValue} (${formatModelOption(model)})`
                : formatModelOption(model),
        }));
    });
}
function getDefaultModelOptionIndex(modelOptions, catalog, routing) {
    const defaultModelId = getSelectableModelId(catalog.defaultModel, routing);
    const defaultIdx = modelOptions.findIndex((option) => option.id === defaultModelId);
    return defaultIdx >= 0 ? defaultIdx : 0;
}
function getSelectableModelId(modelId, routing) {
    const hint = routing?.models.find((entry) => entry.modelId.toLowerCase() === modelId.toLowerCase());
    return hint?.recommendedModelId ?? modelId;
}
function getBackendLabel(backend) {
    return backend === 'plus' ? 'CLIProxy Plus' : 'CLIProxy';
}
function formatVariantAccountLabel(account) {
    const displayName = (0, email_account_identity_1.formatAccountDisplayName)(account);
    return account.nickname ? `${account.nickname} (${displayName})` : displayName;
}
/**
 * Interactive prompt to select provider + model for a single tier.
 * Returns a CompositeTierConfig, or null if user cancelled auth.
 */
async function selectTierConfig(tierName, verbose) {
    console.log((0, ui_1.header)(`${tierName.charAt(0).toUpperCase() + tierName.slice(1)} Tier`));
    // Select provider
    const providerOptions = profile_detector_1.CLIPROXY_PROFILES.map((p) => ({
        id: p,
        label: p.charAt(0).toUpperCase() + p.slice(1),
    }));
    const provider = (await prompt_1.InteractivePrompt.selectFromList(`Provider for ${tierName}:`, providerOptions));
    // Check auth
    const providerAccounts = (0, account_manager_1.getProviderAccounts)(provider);
    if (providerAccounts.length === 0) {
        console.log('');
        console.log((0, ui_1.warn)(`No accounts authenticated for ${provider}`));
        const shouldAuth = await prompt_1.InteractivePrompt.confirm(`Authenticate with ${provider} now?`, {
            default: true,
        });
        if (!shouldAuth) {
            console.log((0, ui_1.info)(`Skipping auth. Run: ${(0, ui_1.color)(`ccs ${provider} --auth`, 'command')}`));
            return null;
        }
        const newAccount = await (0, oauth_handler_1.triggerOAuth)(provider, {
            add: true,
            verbose,
        });
        if (!newAccount) {
            console.log((0, ui_1.fail)('Authentication failed'));
            process.exit(1);
        }
        console.log((0, ui_1.ok)(`Authenticated as ${formatVariantAccountLabel(newAccount)}`));
    }
    // Select model
    let model;
    if ((0, model_catalog_1.supportsModelConfig)(provider)) {
        try {
            await ensureVariantManagedModelPrefixes(provider);
        }
        catch {
            // Keep interactive model selection available even when prefix repair fails.
        }
        const routing = (await (0, catalog_routing_1.getCatalogRoutingSnapshot)()).routing[provider];
        const catalog = (0, model_catalog_1.getProviderCatalog)(provider);
        if (catalog) {
            const modelOptions = getModelOptionsForProvider(provider, catalog, routing);
            model = await prompt_1.InteractivePrompt.selectFromList(`Model for ${tierName}:`, modelOptions, {
                defaultIndex: getDefaultModelOptionIndex(modelOptions, catalog, routing),
            });
        }
    }
    if (!model) {
        model = await prompt_1.InteractivePrompt.input(`Model name for ${tierName}`, {
            validate: (val) => (val ? null : 'Model is required'),
        });
    }
    console.log('');
    return { provider, model };
}
async function handleCreate(args, backend = platform_detector_1.DEFAULT_BACKEND) {
    await (0, ui_1.initUI)();
    const parsedArgs = parseProfileArgs(args);
    if (parsedArgs.errors.length > 0) {
        parsedArgs.errors.forEach((errorMessage) => console.log((0, ui_1.fail)(errorMessage)));
        process.exitCode = 1;
        return;
    }
    console.log((0, ui_1.header)(`Create ${getBackendLabel(backend)} Variant`));
    console.log('');
    // Step 1: Profile name
    let name = parsedArgs.name;
    if (!name) {
        name = await prompt_1.InteractivePrompt.input('Variant name (e.g., g3, flash, pro)', {
            validate: services_1.validateProfileName,
        });
    }
    else {
        const error = (0, services_1.validateProfileName)(name);
        if (error) {
            console.log((0, ui_1.fail)(error));
            process.exit(1);
        }
    }
    if ((0, services_1.variantExists)(name) && !parsedArgs.force) {
        console.log((0, ui_1.fail)(`Variant '${name}' already exists`));
        console.log(`    Use ${(0, ui_1.color)('--force', 'command')} to overwrite`);
        process.exit(1);
    }
    let resolvedTarget = parsedArgs.target || 'claude';
    if (!parsedArgs.target && !parsedArgs.yes) {
        const useDroidByDefault = await prompt_1.InteractivePrompt.confirm('Set default target to Factory Droid for this variant?', { default: false });
        if (useDroidByDefault) {
            resolvedTarget = 'droid';
        }
    }
    // Composite mode: select provider+model per tier
    if (parsedArgs.composite) {
        console.log((0, ui_1.info)('Composite variant — select provider and model for each tier'));
        console.log('');
        const verbose = args.includes('--verbose');
        const opus = await selectTierConfig('opus', verbose);
        if (!opus) {
            return; // User cancelled auth
        }
        const sonnet = await selectTierConfig('sonnet', verbose);
        if (!sonnet) {
            return; // User cancelled auth
        }
        const haiku = await selectTierConfig('haiku', verbose);
        if (!haiku) {
            return; // User cancelled auth
        }
        // Select default tier
        const tierOptions = [
            { id: 'opus', label: `Opus (${opus.provider}: ${opus.model})` },
            { id: 'sonnet', label: `Sonnet (${sonnet.provider}: ${sonnet.model})` },
            { id: 'haiku', label: `Haiku (${haiku.provider}: ${haiku.model})` },
        ];
        const defaultTier = (await prompt_1.InteractivePrompt.selectFromList('Default tier (ANTHROPIC_MODEL):', tierOptions));
        console.log('');
        console.log((0, ui_1.info)(`Creating composite ${getBackendLabel(backend)} variant...`));
        const result = (0, services_1.createCompositeVariant)({
            name,
            defaultTier,
            target: resolvedTarget,
            tiers: { opus, sonnet, haiku },
        });
        if (!result.success) {
            console.log((0, ui_1.fail)(`Failed to create composite variant: ${result.error}`));
            process.exit(1);
        }
        console.log('');
        const tiers = result.variant?.tiers;
        const tierSummary = tiers
            ? `Opus:    ${tiers.opus.provider} / ${tiers.opus.model}\n` +
                `Sonnet:  ${tiers.sonnet.provider} / ${tiers.sonnet.model}\n` +
                `Haiku:   ${tiers.haiku.provider} / ${tiers.haiku.model}\n` +
                `Default: ${defaultTier}\n` +
                `Target:  ${resolvedTarget}`
            : '';
        const portInfo = result.variant?.port ? `\nPort:    ${result.variant.port}` : '';
        console.log((0, ui_1.infoBox)(`Variant: ${name} (composite)\n${tierSummary}${portInfo}\nConfig:  ~/.ccs/config.yaml`, 'Composite Variant Created'));
        console.log('');
        console.log((0, ui_1.header)('Usage'));
        if (resolvedTarget === '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('');
        return;
    }
    // Step 2: Provider selection
    let provider = parsedArgs.provider;
    if (!provider) {
        const providerOptions = profile_detector_1.CLIPROXY_PROFILES.map((p) => ({
            id: p,
            label: p.charAt(0).toUpperCase() + p.slice(1),
        }));
        provider = (await prompt_1.InteractivePrompt.selectFromList('Select provider:', providerOptions));
    }
    else if (!profile_detector_1.CLIPROXY_PROFILES.includes(provider)) {
        console.log((0, ui_1.fail)(`Invalid provider: ${provider}`));
        console.log(`    Available: ${profile_detector_1.CLIPROXY_PROFILES.join(', ')}`);
        process.exit(1);
    }
    // Step 2.5: Account selection
    let account = parsedArgs.account;
    const providerAccounts = (0, account_manager_1.getProviderAccounts)(provider);
    if (!account) {
        if (providerAccounts.length === 0) {
            console.log('');
            console.log((0, ui_1.warn)(`No accounts authenticated for ${provider}`));
            console.log('');
            const shouldAuth = await prompt_1.InteractivePrompt.confirm(`Authenticate with ${provider} now?`, {
                default: true,
            });
            if (!shouldAuth) {
                console.log('');
                console.log((0, ui_1.info)('Run authentication first:'));
                console.log(`  ${(0, ui_1.color)(`ccs ${provider} --auth`, 'command')}`);
                process.exit(0);
            }
            console.log('');
            const newAccount = await (0, oauth_handler_1.triggerOAuth)(provider, {
                add: true,
                verbose: args.includes('--verbose'),
            });
            if (!newAccount) {
                console.log((0, ui_1.fail)('Authentication failed'));
                process.exit(1);
            }
            account = newAccount.id;
            console.log('');
            console.log((0, ui_1.ok)(`Authenticated as ${formatVariantAccountLabel(newAccount)}`));
        }
        else if (providerAccounts.length === 1) {
            account = providerAccounts[0].id;
        }
        else {
            const ADD_NEW_ID = '__add_new__';
            const accountOptions = [
                ...providerAccounts.map((acc) => ({
                    id: acc.id,
                    label: `${formatVariantAccountLabel(acc)}${acc.isDefault ? ' (default)' : ''}`,
                })),
                { id: ADD_NEW_ID, label: (0, ui_1.color)('[+ Add new account...]', 'info') },
            ];
            const defaultIdx = providerAccounts.findIndex((a) => a.isDefault);
            const selectedAccount = await prompt_1.InteractivePrompt.selectFromList('Select account:', accountOptions, { defaultIndex: defaultIdx >= 0 ? defaultIdx : 0 });
            if (selectedAccount === ADD_NEW_ID) {
                console.log('');
                const newAccount = await (0, oauth_handler_1.triggerOAuth)(provider, {
                    add: true,
                    verbose: args.includes('--verbose'),
                });
                if (!newAccount) {
                    console.log((0, ui_1.fail)('Authentication failed'));
                    process.exit(1);
                }
                account = newAccount.id;
                console.log('');
                console.log((0, ui_1.ok)(`Authenticated as ${formatVariantAccountLabel(newAccount)}`));
            }
            else {
                account = selectedAccount;
            }
        }
    }
    else {
        const exists = providerAccounts.find((a) => a.id === account);
        if (!exists) {
            console.log((0, ui_1.fail)(`Account '${account}' not found for ${provider}`));
            console.log('');
            console.log('Available accounts:');
            providerAccounts.forEach((a) => console.log(`  - ${formatVariantAccountLabel(a)}${a.isDefault ? ' (default)' : ''}`));
            process.exit(1);
        }
    }
    // Step 3: Model selection
    let model = parsedArgs.model;
    if (!model) {
        if ((0, model_catalog_1.supportsModelConfig)(provider)) {
            try {
                await ensureVariantManagedModelPrefixes(provider);
            }
            catch {
                // Keep variant creation available even when prefix repair fails.
            }
            const routing = (await (0, catalog_routing_1.getCatalogRoutingSnapshot)()).routing[provider];
            const catalog = (0, model_catalog_1.getProviderCatalog)(provider);
            if (catalog) {
                const modelOptions = getModelOptionsForProvider(provider, catalog, routing);
                model = await prompt_1.InteractivePrompt.selectFromList('Select model:', modelOptions, {
                    defaultIndex: getDefaultModelOptionIndex(modelOptions, catalog, routing),
                });
            }
        }
        if (!model) {
            model = await prompt_1.InteractivePrompt.input('Model name', {
                validate: (val) => (val ? null : 'Model is required'),
            });
        }
    }
    // Create variant
    console.log('');
    console.log((0, ui_1.info)(`Creating ${getBackendLabel(backend)} variant...`));
    const result = (0, services_1.createVariant)(name, provider, model, account, resolvedTarget);
    if (!result.success) {
        console.log((0, ui_1.fail)(`Failed to create variant: ${result.error}`));
        process.exit(1);
    }
    console.log('');
    const configType = (0, config_loader_facade_1.isUnifiedMode)()
        ? 'CLIProxy Variant Created (Unified Config)'
        : 'CLIProxy Variant Created';
    const settingsDisplay = (0, config_loader_facade_1.isUnifiedMode)()
        ? '~/.ccs/config.yaml'
        : `~/.ccs/${path.basename(result.settingsPath || '')}`;
    const portInfo = result.variant?.port ? `Port:     ${result.variant.port}\n` : '';
    const selectedAccount = account && provider
        ? (0, account_manager_1.getProviderAccounts)(provider).find((acc) => acc.id === account)
        : null;
    console.log((0, ui_1.infoBox)(`Variant:  ${name}\nProvider: ${provider}\nModel:    ${model}\nTarget:   ${resolvedTarget}\n${portInfo}${selectedAccount ? `Account:  ${formatVariantAccountLabel(selectedAccount)}\n` : account ? `Account:  ${account}\n` : ''}${(0, config_loader_facade_1.isUnifiedMode)() ? 'Config' : 'Settings'}:   ${settingsDisplay}`, configType));
    console.log('');
    console.log((0, ui_1.header)('Usage'));
    if (resolvedTarget === '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.dim)('To change model later:'));
    console.log(`  ${(0, ui_1.color)(`ccs ${name} --config`, 'command')}`);
    console.log('');
}
exports.handleCreate = handleCreate;
async function handleRemove(args) {
    await (0, ui_1.initUI)();
    const parsedArgs = parseProfileArgs(args);
    if (parsedArgs.errors.length > 0) {
        parsedArgs.errors.forEach((errorMessage) => console.log((0, ui_1.fail)(errorMessage)));
        process.exitCode = 1;
        return;
    }
    const variants = (0, services_1.listVariants)();
    const variantNames = Object.keys(variants);
    if (variantNames.length === 0) {
        console.log((0, ui_1.warn)('No CLIProxy variants to remove'));
        process.exit(0);
    }
    let name = parsedArgs.name;
    if (!name) {
        console.log((0, ui_1.header)('Remove CLIProxy Variant'));
        console.log('');
        console.log('Available variants:');
        variantNames.forEach((n, i) => {
            const v = variants[n];
            const label = v.type === 'composite' ? 'composite' : v.provider;
            console.log(`  ${i + 1}. ${n} (${label})`);
        });
        console.log('');
        name = await prompt_1.InteractivePrompt.input('Variant name to remove', {
            validate: (val) => {
                if (!val)
                    return 'Variant name is required';
                if (!variantNames.includes(val))
                    return `Variant '${val}' not found`;
                return null;
            },
        });
    }
    if (!variantNames.includes(name)) {
        console.log((0, ui_1.fail)(`Variant '${name}' not found`));
        console.log('');
        console.log('Available variants:');
        variantNames.forEach((n) => console.log(`  - ${n}`));
        process.exit(1);
    }
    const variant = variants[name];
    console.log('');
    console.log(`Variant '${(0, ui_1.color)(name, 'command')}' will be removed.`);
    if (variant.type === 'composite') {
        console.log(`  Type:     composite`);
        if (variant.tiers) {
            console.log(`  Opus:     ${variant.tiers.opus.provider} / ${variant.tiers.opus.model}`);
            console.log(`  Sonnet:   ${variant.tiers.sonnet.provider} / ${variant.tiers.sonnet.model}`);
            console.log(`  Haiku:    ${variant.tiers.haiku.provider} / ${variant.tiers.haiku.model}`);
        }
    }
    else {
        console.log(`  Provider: ${variant.provider}`);
    }
    if (variant.port) {
        console.log(`  Port:     ${variant.port}`);
    }
    console.log(`  Target:   ${variant.target || 'claude'}`);
    console.log(`  Settings: ${variant.settings || '-'}`);
    console.log('');
    const confirmed = parsedArgs.yes || (await prompt_1.InteractivePrompt.confirm('Delete this variant?', { default: false }));
    if (!confirmed) {
        console.log((0, ui_1.info)('Cancelled'));
        process.exit(0);
    }
    const result = (0, services_1.removeVariant)(name);
    if (!result.success) {
        console.log((0, ui_1.fail)(`Failed to remove variant: ${result.error}`));
        process.exit(1);
    }
    console.log((0, ui_1.ok)(`Variant removed: ${name}`));
    console.log('');
}
exports.handleRemove = handleRemove;
async function handleEdit(args, backend = platform_detector_1.DEFAULT_BACKEND) {
    await (0, ui_1.initUI)();
    const parsedArgs = parseProfileArgs(args);
    if (parsedArgs.errors.length > 0) {
        parsedArgs.errors.forEach((errorMessage) => console.log((0, ui_1.fail)(errorMessage)));
        process.exitCode = 1;
        return;
    }
    const variants = (0, services_1.listVariants)();
    const variantNames = Object.keys(variants);
    if (variantNames.length === 0) {
        console.log((0, ui_1.warn)('No CLIProxy variants to edit'));
        process.exit(0);
    }
    let name = parsedArgs.name;
    if (!name) {
        console.log((0, ui_1.header)(`Edit ${getBackendLabel(backend)} Variant`));
        console.log('');
        console.log('Available variants:');
        variantNames.forEach((n, i) => {
            const v = variants[n];
            const label = v.type === 'composite' ? 'composite' : v.provider;
            console.log(`  ${i + 1}. ${n} (${label})`);
        });
        console.log('');
        name = await prompt_1.InteractivePrompt.input('Variant name to edit', {
            validate: (val) => {
                if (!val)
                    return 'Variant name is required';
                if (!variantNames.includes(val))
                    return `Variant '${val}' not found`;
                return null;
            },
        });
    }
    if (!variantNames.includes(name)) {
        console.log((0, ui_1.fail)(`Variant '${name}' not found`));
        console.log('');
        console.log('Available variants:');
        variantNames.forEach((n) => console.log(`  - ${n}`));
        process.exit(1);
    }
    const variant = variants[name];
    // If not composite, use existing updateVariant() flow (interactive prompts)
    if (variant.type !== 'composite') {
        const currentTarget = variant.target || 'claude';
        console.log((0, ui_1.header)(`Edit Variant: ${name}`));
        console.log('');
        console.log(`Current provider: ${variant.provider}`);
        if (variant.model) {
            console.log(`Current model:    ${variant.model}`);
        }
        console.log(`Current target:   ${currentTarget}`);
        console.log('');
        const changeProvider = await prompt_1.InteractivePrompt.confirm('Change provider?', { default: false });
        let newProvider = undefined;
        if (changeProvider) {
            const providerOptions = profile_detector_1.CLIPROXY_PROFILES.map((p) => ({
                id: p,
                label: p.charAt(0).toUpperCase() + p.slice(1),
            }));
            newProvider = (await prompt_1.InteractivePrompt.selectFromList('Select new provider:', providerOptions));
        }
        const providerChanged = !!(newProvider && newProvider !== variant.provider);
        if (providerChanged) {
            console.log((0, ui_1.info)('Provider changed. Model selection is required.'));
        }
        const changeModel = providerChanged
            ? true
            : await prompt_1.InteractivePrompt.confirm('Change model?', { default: false });
        let newModel = variant.model || '';
        if (changeModel) {
            const providerForModel = newProvider || variant.provider;
            if ((0, model_catalog_1.supportsModelConfig)(providerForModel)) {
                try {
                    await ensureVariantManagedModelPrefixes(providerForModel);
                }
                catch {
                    // Keep edit flow available even when prefix repair fails.
                }
                const routing = (await (0, catalog_routing_1.getCatalogRoutingSnapshot)()).routing[providerForModel];
                const catalog = (0, model_catalog_1.getProviderCatalog)(providerForModel);
                if (catalog) {
                    const modelOptions = catalog.models.map((m) => ({
                        id: getSelectableModelId(m.id, routing),
                        label: formatModelOption(m),
                    }));
                    const defaultIdx = catalog.models.findIndex((m) => m.id === catalog.defaultModel);
                    newModel = await prompt_1.InteractivePrompt.selectFromList('Select new model:', modelOptions, {
                        defaultIndex: defaultIdx >= 0 ? defaultIdx : 0,
                    });
                }
            }
            else {
                newModel = await prompt_1.InteractivePrompt.input('New model name', {
                    validate: (val) => (val ? null : 'Model is required'),
                });
            }
        }
        let newTarget = parsedArgs.target;
        if (!parsedArgs.target) {
            const changeTarget = await prompt_1.InteractivePrompt.confirm('Change default target?', {
                default: false,
            });
            if (changeTarget) {
                const targetOptions = [
                    { id: 'claude', label: 'Claude Code' },
                    { id: 'droid', label: 'Factory Droid' },
                ];
                newTarget = (await prompt_1.InteractivePrompt.selectFromList('Select target:', targetOptions, {
                    defaultIndex: currentTarget === 'droid' ? 1 : 0,
                }));
            }
        }
        console.log('');
        console.log((0, ui_1.info)(`Updating ${getBackendLabel(backend)} variant...`));
        // Use existing updateVariant from variant-service for single-provider variants
        const { updateVariant } = await Promise.resolve().then(() => __importStar(require('../../cliproxy/services/variant-service')));
        const result = updateVariant(name, {
            provider: newProvider,
            model: changeModel ? newModel : undefined,
            target: newTarget,
        });
        if (!result.success) {
            console.log((0, ui_1.fail)(`Failed to update variant: ${result.error}`));
            process.exit(1);
        }
        const resolvedTarget = result.variant?.target || currentTarget;
        console.log('');
        console.log((0, ui_1.ok)(`Variant updated: ${name}`));
        console.log('');
        console.log((0, ui_1.header)('Usage'));
        if (resolvedTarget === '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('');
        return;
    }
    // Composite variant edit flow
    const compositeCurrentTarget = variant.target || 'claude';
    console.log((0, ui_1.header)(`Edit Composite Variant: ${name}`));
    console.log('');
    if (!variant.tiers) {
        console.log((0, ui_1.fail)('Invalid composite variant: missing tier configuration'));
        process.exit(1);
    }
    console.log((0, ui_1.info)('Current tier configuration:'));
    console.log(`  Opus:    ${variant.tiers.opus.provider} / ${variant.tiers.opus.model}`);
    console.log(`  Sonnet:  ${variant.tiers.sonnet.provider} / ${variant.tiers.sonnet.model}`);
    console.log(`  Haiku:   ${variant.tiers.haiku.provider} / ${variant.tiers.haiku.model}`);
    console.log(`  Default: ${variant.default_tier}`);
    console.log(`  Target:  ${compositeCurrentTarget}`);
    console.log('');
    const verbose = args.includes('--verbose');
    const updatedTiers = {};
    // Ask per-tier edits
    for (const tierName of ['opus', 'sonnet', 'haiku']) {
        const shouldEdit = await prompt_1.InteractivePrompt.confirm(`Edit ${tierName} tier?`, {
            default: false,
        });
        if (shouldEdit) {
            const newConfig = await selectTierConfig(tierName, verbose);
            if (!newConfig) {
                console.log((0, ui_1.fail)('Edit cancelled'));
                process.exit(0);
            }
            updatedTiers[tierName] = newConfig;
        }
    }
    // Ask for default tier change
    let newDefaultTier = variant.default_tier;
    const changeDefault = await prompt_1.InteractivePrompt.confirm('Change default tier?', { default: false });
    if (changeDefault) {
        const finalTiers = {
            opus: updatedTiers.opus ?? variant.tiers.opus,
            sonnet: updatedTiers.sonnet ?? variant.tiers.sonnet,
            haiku: updatedTiers.haiku ?? variant.tiers.haiku,
        };
        const tierOptions = [
            {
                id: 'opus',
                label: `Opus (${finalTiers.opus.provider}: ${finalTiers.opus.model})`,
            },
            {
                id: 'sonnet',
                label: `Sonnet (${finalTiers.sonnet.provider}: ${finalTiers.sonnet.model})`,
            },
            {
                id: 'haiku',
                label: `Haiku (${finalTiers.haiku.provider}: ${finalTiers.haiku.model})`,
            },
        ];
        newDefaultTier = (await prompt_1.InteractivePrompt.selectFromList('Default tier (ANTHROPIC_MODEL):', tierOptions));
    }
    let newCompositeTarget = parsedArgs.target;
    if (!parsedArgs.target) {
        const changeTarget = await prompt_1.InteractivePrompt.confirm('Change default target?', {
            default: false,
        });
        if (changeTarget) {
            const targetOptions = [
                { id: 'claude', label: 'Claude Code' },
                { id: 'droid', label: 'Factory Droid' },
            ];
            newCompositeTarget = (await prompt_1.InteractivePrompt.selectFromList('Select target:', targetOptions, {
                defaultIndex: compositeCurrentTarget === 'droid' ? 1 : 0,
            }));
        }
    }
    console.log('');
    console.log((0, ui_1.info)(`Updating composite ${getBackendLabel(backend)} variant...`));
    const result = (0, services_1.updateCompositeVariant)(name, {
        tiers: updatedTiers,
        defaultTier: changeDefault ? newDefaultTier : undefined,
        target: newCompositeTarget,
    });
    if (!result.success) {
        console.log((0, ui_1.fail)(`Failed to update composite variant: ${result.error}`));
        process.exit(1);
    }
    console.log('');
    const finalVariant = result.variant;
    if (finalVariant && finalVariant.tiers) {
        const tierSummary = `Opus:    ${finalVariant.tiers.opus.provider} / ${finalVariant.tiers.opus.model}\n` +
            `Sonnet:  ${finalVariant.tiers.sonnet.provider} / ${finalVariant.tiers.sonnet.model}\n` +
            `Haiku:   ${finalVariant.tiers.haiku.provider} / ${finalVariant.tiers.haiku.model}\n` +
            `Default: ${finalVariant.default_tier}\n` +
            `Target:  ${finalVariant.target || compositeCurrentTarget}`;
        const portInfo = finalVariant.port ? `\nPort:    ${finalVariant.port}` : '';
        console.log((0, ui_1.infoBox)(`Variant: ${name} (composite)\n${tierSummary}${portInfo}\nConfig:  ~/.ccs/config.yaml`, 'Composite Variant Updated'));
    }
    else {
        console.log((0, ui_1.ok)(`Composite variant updated: ${name}`));
    }
    console.log('');
}
exports.handleEdit = handleEdit;
//# sourceMappingURL=variant-subcommand.js.map