"use strict";
/**
 * Config Image Analysis Command Handler
 *
 * Manages image_analysis section of config.yaml via CLI.
 * Usage: ccs config image-analysis [options]
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleConfigImageAnalysisCommand = void 0;
const ui_1 = require("../utils/ui");
const unified_config_types_1 = require("../config/unified-config-types");
const provider_capabilities_1 = require("../cliproxy/provider-capabilities");
const arg_extractor_1 = require("./arg-extractor");
const hooks_1 = require("../utils/hooks");
const config_loader_facade_1 = require("../config/config-loader-facade");
const IMAGE_ANALYSIS_PROVIDER_ALIASES = Object.freeze(provider_capabilities_1.CLIPROXY_PROVIDER_IDS.flatMap((provider) => provider_capabilities_1.PROVIDER_CAPABILITIES[provider].aliases).filter((alias, index, aliases) => aliases.indexOf(alias) === index));
function isConfiguredImageAnalysisBackend(backend, providerModels) {
    return Boolean(backend && Object.prototype.hasOwnProperty.call(providerModels, backend));
}
function parseArgs(args) {
    const options = {
        enable: (0, arg_extractor_1.hasAnyFlag)(args, ['--enable']),
        disable: (0, arg_extractor_1.hasAnyFlag)(args, ['--disable']),
        help: (0, arg_extractor_1.hasAnyFlag)(args, ['--help', '-h']),
    };
    const timeoutOption = (0, arg_extractor_1.extractOption)(args, ['--timeout']);
    if (timeoutOption.found) {
        const timeout = parseInt(timeoutOption.value || '', 10);
        if (isNaN(timeout) || timeout < 10 || timeout > 600) {
            console.error((0, ui_1.fail)('Timeout must be between 10 and 600 seconds'));
            process.exit(1);
        }
        options.timeout = timeout;
    }
    const setModelIdx = args.indexOf('--set-model');
    if (setModelIdx !== -1) {
        const provider = args[setModelIdx + 1];
        const model = args[setModelIdx + 2];
        if (provider && model && !provider.startsWith('-') && !model.startsWith('-')) {
            options.setModel = { provider, model };
        }
        else {
            options.setModelError = '--set-model requires <provider> <model>';
        }
    }
    const setFallbackIdx = args.indexOf('--set-fallback');
    if (setFallbackIdx !== -1) {
        const backend = args[setFallbackIdx + 1];
        if (backend && !backend.startsWith('-')) {
            options.setFallback = backend;
        }
        else {
            options.setFallbackError = '--set-fallback requires <backend>';
        }
    }
    const setProfileBackendIdx = args.indexOf('--set-profile-backend');
    if (setProfileBackendIdx !== -1) {
        const profile = args[setProfileBackendIdx + 1];
        const backend = args[setProfileBackendIdx + 2];
        if (profile && backend && !profile.startsWith('-') && !backend.startsWith('-')) {
            options.setProfileBackend = { profile, backend };
        }
        else {
            options.setProfileBackendError = '--set-profile-backend requires <profile> <backend>';
        }
    }
    const clearProfileBackend = (0, arg_extractor_1.extractOption)(args, ['--clear-profile-backend']);
    if (clearProfileBackend.found) {
        if (clearProfileBackend.value && !clearProfileBackend.value.startsWith('-')) {
            options.clearProfileBackend = clearProfileBackend.value;
        }
        else {
            options.setProfileBackendError = '--clear-profile-backend requires <profile>';
        }
    }
    return options;
}
function showHelp() {
    console.log('');
    console.log((0, ui_1.header)('ccs config image-analysis'));
    console.log('');
    console.log('  Configure image analysis for CLIProxy providers.');
    console.log('  Images/PDFs are analyzed via vision models instead of direct Read.');
    console.log('');
    console.log((0, ui_1.subheader)('Usage:'));
    console.log(`  ${(0, ui_1.color)('ccs config image-analysis', 'command')} [options]`);
    console.log('');
    console.log((0, ui_1.subheader)('Options:'));
    console.log(`  ${(0, ui_1.color)('--enable', 'command')}                  Enable image analysis`);
    console.log(`  ${(0, ui_1.color)('--disable', 'command')}                 Disable image analysis`);
    console.log(`  ${(0, ui_1.color)('--timeout <seconds>', 'command')}       Set analysis timeout (10-600)`);
    console.log(`  ${(0, ui_1.color)('--set-model <p> <m>', 'command')}       Set model for provider`);
    console.log(`  ${(0, ui_1.color)('--set-fallback <backend>', 'command')}  Set fallback backend`);
    console.log(`  ${(0, ui_1.color)('--set-profile-backend <p> <b>', 'command')} Map a profile alias to a backend`);
    console.log(`  ${(0, ui_1.color)('--clear-profile-backend <p>', 'command')}   Remove a saved profile mapping`);
    console.log(`  ${(0, ui_1.color)('--help, -h', 'command')}                Show this help`);
    console.log('');
    console.log((0, ui_1.subheader)('Provider Models:'));
    console.log(`  ${(0, ui_1.dim)(`Valid providers: ${provider_capabilities_1.CLIPROXY_PROVIDER_IDS.join(', ')}`)}`);
    if (IMAGE_ANALYSIS_PROVIDER_ALIASES.length > 0) {
        console.log(`  ${(0, ui_1.dim)(`Aliases accepted: ${IMAGE_ANALYSIS_PROVIDER_ALIASES.join(', ')}`)}`);
    }
    console.log(`  ${(0, ui_1.dim)('Defaults: agy -> gemini-3-1-flash-preview, gemini -> gemini-3-flash-preview')}`);
    console.log('');
    console.log((0, ui_1.subheader)('Examples:'));
    console.log(`  $ ${(0, ui_1.color)('ccs config image-analysis', 'command')}               ${(0, ui_1.dim)('# Show status')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config image-analysis --enable', 'command')}      ${(0, ui_1.dim)('# Enable feature')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config image-analysis --timeout 120', 'command')} ${(0, ui_1.dim)('# Set 2min timeout')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config image-analysis --set-model agy gemini-2.5-pro', 'command')}`);
    console.log('');
    console.log((0, ui_1.subheader)('How it works:'));
    console.log(`  1. When Claude's Read tool targets an image/PDF file`);
    console.log(`  2. CCS hook intercepts and sends to CLIProxy vision API`);
    console.log(`  3. Vision model analyzes and returns text description`);
    console.log(`  4. Claude receives description instead of raw image data`);
    console.log('');
    console.log((0, ui_1.subheader)('Supported file types:'));
    console.log(`  ${(0, ui_1.dim)('Images: .jpg, .jpeg, .png, .gif, .webp, .heic, .bmp, .tiff')}`);
    console.log(`  ${(0, ui_1.dim)('Documents: .pdf')}`);
    console.log('');
}
function showStatus() {
    const config = (0, config_loader_facade_1.getImageAnalysisConfig)();
    console.log('');
    console.log((0, ui_1.header)('Image Analysis Configuration'));
    console.log('');
    // Status
    const statusText = config.enabled ? (0, ui_1.ok)('Enabled') : (0, ui_1.warn)('Disabled');
    console.log(`  Status:   ${statusText}`);
    console.log(`  Timeout:  ${config.timeout}s`);
    console.log('');
    // Provider models
    console.log((0, ui_1.subheader)('Provider Models:'));
    const providers = Object.entries(config.provider_models);
    if (providers.length === 0) {
        console.log(`  ${(0, ui_1.dim)('No providers configured')}`);
    }
    else {
        for (const [provider, model] of providers) {
            const isDefault = unified_config_types_1.DEFAULT_IMAGE_ANALYSIS_CONFIG.provider_models[provider] === model;
            const suffix = isDefault ? (0, ui_1.dim)(' (default)') : '';
            // Edge case #3: Long model name truncation
            const truncatedModel = model.length > 40 ? model.slice(0, 37) + '...' : model;
            console.log(`  ${(0, ui_1.color)(provider.padEnd(10), 'command')} ${truncatedModel}${suffix}`);
        }
    }
    console.log('');
    // Config location
    console.log((0, ui_1.subheader)('Configuration:'));
    console.log(`  File: ${(0, ui_1.color)('~/.ccs/config.yaml', 'path')}`);
    console.log(`  Section: ${(0, ui_1.dim)('image_analysis')}`);
    console.log(`  Fallback backend: ${(0, ui_1.color)(config.fallback_backend || 'none', 'command')}`);
    const profileBackends = Object.entries(config.profile_backends ?? {});
    if (profileBackends.length > 0) {
        console.log('');
        console.log((0, ui_1.subheader)('Profile Backends:'));
        for (const [profile, backend] of profileBackends) {
            console.log(`  ${(0, ui_1.color)(profile.padEnd(16), 'command')} ${backend}`);
        }
    }
    console.log('');
    // Troubleshooting hint if disabled
    if (!config.enabled) {
        console.log((0, ui_1.info)('To enable: ccs config image-analysis --enable'));
        console.log('');
    }
}
async function handleConfigImageAnalysisCommand(args) {
    await (0, ui_1.initUI)();
    const options = parseArgs(args);
    if (options.help) {
        showHelp();
        return;
    }
    if (options.setModelError) {
        console.error((0, ui_1.fail)(options.setModelError));
        process.exit(1);
    }
    if (options.setFallbackError) {
        console.error((0, ui_1.fail)(options.setFallbackError));
        process.exit(1);
    }
    if (options.setProfileBackendError) {
        console.error((0, ui_1.fail)(options.setProfileBackendError));
        process.exit(1);
    }
    // Validate conflicting flags (Edge case #2: --enable + --disable conflict)
    if (options.enable && options.disable) {
        console.error((0, ui_1.fail)('Cannot use --enable and --disable together'));
        process.exit(1);
    }
    // Apply changes if any options provided
    let hasChanges = false;
    const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
    const imageConfig = config.image_analysis ?? { ...unified_config_types_1.DEFAULT_IMAGE_ANALYSIS_CONFIG };
    if (options.enable) {
        imageConfig.enabled = true;
        hasChanges = true;
    }
    if (options.disable) {
        imageConfig.enabled = false;
        hasChanges = true;
    }
    if (options.timeout !== undefined) {
        imageConfig.timeout = options.timeout;
        hasChanges = true;
    }
    if (options.setModel) {
        const validProviders = [...provider_capabilities_1.CLIPROXY_PROVIDER_IDS];
        const normalizedProviderInput = options.setModel.provider.trim().toLowerCase();
        const canonicalProvider = (0, provider_capabilities_1.mapExternalProviderName)(normalizedProviderInput);
        if (!canonicalProvider) {
            console.error((0, ui_1.fail)(`Invalid provider: ${options.setModel.provider}`));
            console.error((0, ui_1.info)(`Valid providers: ${validProviders.join(', ')}`));
            process.exit(1);
        }
        // Validate model name (Edge case #1: Empty model string validation)
        const model = options.setModel.model;
        if (!model || model.trim() === '') {
            console.error((0, ui_1.fail)('Model name cannot be empty'));
            process.exit(1);
        }
        imageConfig.provider_models = {
            ...imageConfig.provider_models,
            [canonicalProvider]: model,
        };
        hasChanges = true;
    }
    if (options.setFallback) {
        const normalizedBackend = (0, hooks_1.normalizeImageAnalysisBackendId)(options.setFallback, Object.keys(imageConfig.provider_models));
        if (!isConfiguredImageAnalysisBackend(normalizedBackend, imageConfig.provider_models)) {
            console.error((0, ui_1.fail)(`Invalid fallback backend: ${options.setFallback}`));
            process.exit(1);
        }
        imageConfig.fallback_backend = normalizedBackend;
        hasChanges = true;
    }
    if (options.setProfileBackend) {
        const profileName = options.setProfileBackend.profile.trim();
        const normalizedBackend = (0, hooks_1.normalizeImageAnalysisBackendId)(options.setProfileBackend.backend, Object.keys(imageConfig.provider_models));
        if (!profileName) {
            console.error((0, ui_1.fail)('Profile name cannot be empty'));
            process.exit(1);
        }
        if (!isConfiguredImageAnalysisBackend(normalizedBackend, imageConfig.provider_models)) {
            console.error((0, ui_1.fail)(`Invalid backend: ${options.setProfileBackend.backend}`));
            process.exit(1);
        }
        imageConfig.profile_backends = {
            ...(imageConfig.profile_backends ?? {}),
            [profileName]: normalizedBackend,
        };
        hasChanges = true;
    }
    if (options.clearProfileBackend) {
        const profileName = options.clearProfileBackend.trim().toLowerCase();
        const nextProfileBackends = Object.fromEntries(Object.entries(imageConfig.profile_backends ?? {}).filter(([name]) => name.trim().toLowerCase() !== profileName));
        imageConfig.profile_backends = nextProfileBackends;
        hasChanges = true;
    }
    if (hasChanges) {
        (0, config_loader_facade_1.updateConfig)({ image_analysis: imageConfig });
        console.log((0, ui_1.ok)('Configuration updated'));
        console.log('');
    }
    // Always show current status
    showStatus();
}
exports.handleConfigImageAnalysisCommand = handleConfigImageAnalysisCommand;
//# sourceMappingURL=config-image-analysis-command.js.map