"use strict";
/**
 * Config Thinking Command Handler
 *
 * Manages thinking section of config.yaml via CLI.
 * Usage: ccs config thinking [options]
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleConfigThinkingCommand = exports.parseThinkingOverrideInput = exports.parseThinkingCommandArgs = void 0;
const ui_1 = require("../utils/ui");
const unified_config_types_1 = require("../config/unified-config-types");
const thinking_validator_1 = require("../cliproxy/thinking-validator");
const config_thinking_parser_1 = require("./config-thinking-parser");
const config_loader_facade_1 = require("../config/config-loader-facade");
const VALID_THINKING_MODES = ['auto', 'off', 'manual'];
const VALID_TIERS = ['opus', 'sonnet', 'haiku'];
var config_thinking_parser_2 = require("./config-thinking-parser");
Object.defineProperty(exports, "parseThinkingCommandArgs", { enumerable: true, get: function () { return config_thinking_parser_2.parseThinkingCommandArgs; } });
Object.defineProperty(exports, "parseThinkingOverrideInput", { enumerable: true, get: function () { return config_thinking_parser_2.parseThinkingOverrideInput; } });
function showHelp() {
    console.log('');
    console.log((0, ui_1.header)('ccs config thinking'));
    console.log('');
    console.log('  Configure extended thinking/reasoning for CLIProxy providers.');
    console.log('');
    console.log((0, ui_1.subheader)('Usage:'));
    console.log(`  ${(0, ui_1.color)('ccs config thinking', 'command')} [options]`);
    console.log('');
    console.log((0, ui_1.subheader)('Options:'));
    console.log(`  ${(0, ui_1.color)('--mode <mode>', 'command')}                    Set mode (auto, off, manual)`);
    console.log(`  ${(0, ui_1.color)('--override <level>', 'command')}               Set persistent override (manual mode)`);
    console.log(`  ${(0, ui_1.color)('--clear-override', 'command')}                  Remove persistent override`);
    console.log(`  ${(0, ui_1.color)('--tier <tier> <level>', 'command')}            Set tier default (opus/sonnet/haiku)`);
    console.log(`  ${(0, ui_1.color)('--provider-override <p> <t> <l>', 'command')} Set provider-specific tier override`);
    console.log(`  ${(0, ui_1.color)('--clear-provider-override <p> [t]', 'command')} Remove provider override (provider or tier)`);
    console.log(`  ${(0, ui_1.color)('--help, -h', 'command')}                        Show this help`);
    console.log('');
    console.log((0, ui_1.subheader)('Levels:'));
    console.log(`  ${(0, ui_1.dim)('minimal (512), low (1K), medium (8K), high (24K), xhigh (32K), max (adaptive ceiling), auto, off')}`);
    console.log('');
    console.log((0, ui_1.subheader)('Examples:'));
    console.log(`  $ ${(0, ui_1.color)('ccs config thinking', 'command')}                            ${(0, ui_1.dim)('# Show status')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config thinking --mode auto', 'command')}                ${(0, ui_1.dim)('# Auto mode')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config thinking --mode manual --override high', 'command')} ${(0, ui_1.dim)('# Persistent high')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config thinking --tier opus xhigh', 'command')}          ${(0, ui_1.dim)('# Opus -> xhigh')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config thinking --provider-override codex opus xhigh', 'command')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config thinking --clear-provider-override codex opus', 'command')}`);
    console.log('');
    console.log((0, ui_1.subheader)('Environment:'));
    console.log(`  ${(0, ui_1.color)('CCS_THINKING', 'command')}  Override per-session via env var (priority: flag > env > config)`);
    console.log(`  ${(0, ui_1.dim)('Example: CCS_THINKING=high ccs codex "debug this"')}`);
    console.log('');
}
function showStatus() {
    const config = (0, config_loader_facade_1.getThinkingConfig)();
    console.log('');
    console.log((0, ui_1.header)('Thinking Configuration'));
    console.log('');
    // Mode
    const modeText = config.mode === 'auto' ? (0, ui_1.ok)('Auto') : config.mode === 'off' ? (0, ui_1.warn)('Off') : (0, ui_1.info)('Manual');
    console.log(`  Mode:      ${modeText}`);
    // Override
    if (config.override !== undefined) {
        console.log(`  Override:  ${(0, ui_1.color)(String(config.override), 'command')}`);
    }
    // Warnings
    console.log(`  Warnings:  ${config.show_warnings !== false ? 'on' : 'off'}`);
    console.log('');
    // Tier defaults
    console.log((0, ui_1.subheader)('Tier Defaults:'));
    for (const tier of VALID_TIERS) {
        const level = config.tier_defaults?.[tier] ?? unified_config_types_1.DEFAULT_THINKING_TIER_DEFAULTS[tier];
        const isDefault = level === unified_config_types_1.DEFAULT_THINKING_TIER_DEFAULTS[tier];
        const suffix = isDefault ? (0, ui_1.dim)(' (default)') : '';
        console.log(`  ${(0, ui_1.color)(tier.padEnd(10), 'command')} ${level}${suffix}`);
    }
    console.log('');
    // Provider overrides
    const overrides = config.provider_overrides;
    if (overrides && Object.keys(overrides).length > 0) {
        console.log((0, ui_1.subheader)('Provider Overrides:'));
        for (const [provider, tierOverrides] of Object.entries(overrides)) {
            const parts = Object.entries(tierOverrides)
                .map(([t, l]) => `${t}=${l}`)
                .join(', ');
            console.log(`  ${(0, ui_1.color)(provider.padEnd(10), 'command')} ${parts}`);
        }
        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)('thinking')}`);
    console.log('');
    // Env var hint
    if (process.env.CCS_THINKING) {
        console.log((0, ui_1.info)(`CCS_THINKING env var active: ${process.env.CCS_THINKING}`));
        console.log('');
    }
}
async function handleConfigThinkingCommand(args) {
    await (0, ui_1.initUI)();
    const { options, error } = (0, config_thinking_parser_1.parseThinkingCommandArgs)(args);
    if (error) {
        console.error((0, ui_1.fail)(error));
        process.exitCode = 1;
        return;
    }
    if (options.help) {
        showHelp();
        return;
    }
    let hasChanges = false;
    const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
    const thinkingConfig = config.thinking ?? {
        mode: 'auto',
        tier_defaults: { ...unified_config_types_1.DEFAULT_THINKING_TIER_DEFAULTS },
        show_warnings: true,
    };
    // Validate and apply --mode
    if (options.mode !== undefined) {
        const normalizedMode = options.mode.trim().toLowerCase();
        if (!VALID_THINKING_MODES.includes(normalizedMode)) {
            console.error((0, ui_1.fail)(`Invalid mode: ${options.mode}`));
            console.error((0, ui_1.info)(`Valid modes: ${VALID_THINKING_MODES.join(', ')}`));
            process.exitCode = 1;
            return;
        }
        thinkingConfig.mode = normalizedMode;
        hasChanges = true;
    }
    // Validate and apply --override
    if (options.override !== undefined) {
        const parsedOverride = (0, config_thinking_parser_1.parseThinkingOverrideInput)(options.override);
        if (parsedOverride.error) {
            console.error((0, ui_1.fail)(parsedOverride.error));
            console.error((0, ui_1.info)(`Valid levels: ${thinking_validator_1.VALID_THINKING_LEVELS.join(', ')}, or a number`));
            process.exitCode = 1;
            return;
        }
        thinkingConfig.override = parsedOverride.value;
        hasChanges = true;
    }
    // Apply --clear-override
    if (options.clearOverride) {
        thinkingConfig.override = undefined;
        hasChanges = true;
    }
    // Validate and apply --tier
    if (options.tier) {
        const tier = options.tier.tier.toLowerCase().trim();
        const level = options.tier.level.toLowerCase().trim();
        if (!VALID_TIERS.includes(tier)) {
            console.error((0, ui_1.fail)(`Invalid tier: ${options.tier.tier}`));
            console.error((0, ui_1.info)(`Valid tiers: ${VALID_TIERS.join(', ')}`));
            process.exitCode = 1;
            return;
        }
        if (!thinking_validator_1.VALID_THINKING_LEVELS.includes(level)) {
            console.error((0, ui_1.fail)(`Invalid level for ${tier}: ${options.tier.level}`));
            console.error((0, ui_1.info)(`Valid levels: ${thinking_validator_1.VALID_THINKING_LEVELS.join(', ')}`));
            process.exitCode = 1;
            return;
        }
        thinkingConfig.tier_defaults = {
            ...unified_config_types_1.DEFAULT_THINKING_TIER_DEFAULTS,
            ...thinkingConfig.tier_defaults,
            [tier]: level,
        };
        hasChanges = true;
    }
    // Validate and apply --provider-override
    if (options.providerOverride) {
        const provider = options.providerOverride.provider.trim().toLowerCase();
        const tier = options.providerOverride.tier.trim().toLowerCase();
        const level = options.providerOverride.level.trim().toLowerCase();
        if (!provider) {
            console.error((0, ui_1.fail)('Provider name cannot be empty'));
            process.exitCode = 1;
            return;
        }
        if (!VALID_TIERS.includes(tier)) {
            console.error((0, ui_1.fail)(`Invalid tier: ${options.providerOverride.tier}`));
            process.exitCode = 1;
            return;
        }
        if (!thinking_validator_1.VALID_THINKING_LEVELS.includes(level)) {
            console.error((0, ui_1.fail)(`Invalid level: ${options.providerOverride.level}`));
            process.exitCode = 1;
            return;
        }
        const normalizedTier = tier;
        thinkingConfig.provider_overrides = {
            ...thinkingConfig.provider_overrides,
            [provider]: {
                ...thinkingConfig.provider_overrides?.[provider],
                [normalizedTier]: level,
            },
        };
        hasChanges = true;
    }
    // Validate and apply --clear-provider-override
    if (options.clearProviderOverride) {
        const provider = options.clearProviderOverride.provider.trim().toLowerCase();
        const tier = options.clearProviderOverride.tier?.trim().toLowerCase();
        if (!provider) {
            console.error((0, ui_1.fail)('Provider name cannot be empty'));
            process.exitCode = 1;
            return;
        }
        if (tier && !VALID_TIERS.includes(tier)) {
            console.error((0, ui_1.fail)(`Invalid tier: ${options.clearProviderOverride.tier}`));
            console.error((0, ui_1.info)(`Valid tiers: ${VALID_TIERS.join(', ')}`));
            process.exitCode = 1;
            return;
        }
        const normalizedTier = tier;
        const clearResult = (0, config_thinking_parser_1.clearProviderOverride)(thinkingConfig.provider_overrides, provider, normalizedTier);
        thinkingConfig.provider_overrides = clearResult.nextOverrides;
        if (clearResult.changed) {
            hasChanges = true;
        }
        else {
            console.log((0, ui_1.info)(`No provider override found for '${provider}'${tier ? ` tier '${tier}'` : ''}`));
            console.log('');
        }
    }
    if (hasChanges) {
        (0, config_loader_facade_1.updateConfig)({ thinking: thinkingConfig });
        console.log((0, ui_1.ok)('Configuration updated'));
        console.log('');
    }
    // Always show current status
    showStatus();
}
exports.handleConfigThinkingCommand = handleConfigThinkingCommand;
//# sourceMappingURL=config-thinking-command.js.map