"use strict";
/**
 * Tokens Command
 *
 * Manage CLIProxyAPI auth tokens (API key and management secret).
 *
 * Usage:
 *   ccs tokens                       Show current tokens (masked)
 *   ccs tokens --show                Show tokens unmasked
 *   ccs tokens --api-key <key>       Set global API key
 *   ccs tokens --secret <key>        Set management secret
 *   ccs tokens --regenerate-secret   Auto-generate new management secret
 *   ccs tokens --reset               Reset to defaults
 *   ccs tokens --variant <name> --api-key <key>  Set per-variant API key
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleTokensCommand = void 0;
const ui_1 = require("../utils/ui");
const cliproxy_1 = require("../cliproxy");
const config_generator_1 = require("../cliproxy/config/config-generator");
/**
 * Display current auth status
 */
async function showAuthStatus(showUnmasked) {
    await (0, ui_1.initUI)();
    const summary = (0, cliproxy_1.getAuthSummary)();
    console.log((0, ui_1.header)('CLIProxy Auth Tokens'));
    console.log('');
    // API Key
    const apiKeyDisplay = showUnmasked ? summary.apiKey.value : (0, cliproxy_1.maskToken)(summary.apiKey.value);
    const apiKeyStatus = summary.apiKey.isCustom ? (0, ui_1.color)('(custom)', 'warning') : (0, ui_1.dim)('(default)');
    console.log(`  API Key:           ${apiKeyDisplay} ${apiKeyStatus}`);
    // Management Secret
    const secretDisplay = showUnmasked
        ? summary.managementSecret.value
        : (0, cliproxy_1.maskToken)(summary.managementSecret.value);
    const secretStatus = summary.managementSecret.isCustom
        ? (0, ui_1.color)('(custom)', 'warning')
        : (0, ui_1.dim)('(default)');
    console.log(`  Management Secret: ${secretDisplay} ${secretStatus}`);
    console.log('');
    if (showUnmasked) {
        console.log((0, ui_1.warn)('Tokens shown in plain text. Do not share!'));
        console.log('');
    }
    console.log((0, ui_1.subheader)('Usage'));
    console.log(`  ${(0, ui_1.dim)('Set API key:')}       ccs tokens --api-key <key>`);
    console.log(`  ${(0, ui_1.dim)('Set secret:')}        ccs tokens --secret <key>`);
    console.log(`  ${(0, ui_1.dim)('Generate secret:')}   ccs tokens --regenerate-secret`);
    console.log(`  ${(0, ui_1.dim)('Reset to defaults:')} ccs tokens --reset`);
    console.log('');
}
/**
 * Handle tokens command
 */
async function handleTokensCommand(args) {
    await (0, ui_1.initUI)();
    const showFlag = args.includes('--show');
    const resetFlag = args.includes('--reset');
    const regenerateSecretFlag = args.includes('--regenerate-secret');
    const helpFlag = args.includes('--help') || args.includes('-h');
    const apiKeyIndex = args.indexOf('--api-key');
    const hasApiKeyFlag = apiKeyIndex !== -1;
    const apiKeyValue = apiKeyIndex !== -1 ? args[apiKeyIndex + 1] : undefined;
    const secretIndex = args.indexOf('--secret');
    const hasSecretFlag = secretIndex !== -1;
    const secretValue = secretIndex !== -1 ? args[secretIndex + 1] : undefined;
    const variantIndex = args.indexOf('--variant');
    const variantValue = variantIndex !== -1 ? args[variantIndex + 1] : undefined;
    if (helpFlag) {
        console.log((0, ui_1.header)('CCS Tokens Management'));
        console.log('');
        console.log((0, ui_1.subheader)('Usage'));
        console.log(`  ${(0, ui_1.color)('ccs tokens', 'command')} [options]`);
        console.log('');
        console.log((0, ui_1.subheader)('Options'));
        console.log(`  ${(0, ui_1.color)('(no args)', 'command')}              Show masked tokens`);
        console.log(`  ${(0, ui_1.color)('--show', 'command')}                 Show tokens unmasked`);
        console.log(`  ${(0, ui_1.color)('--api-key <key>', 'command')}        Set global API key`);
        console.log(`  ${(0, ui_1.color)('--secret <key>', 'command')}         Set management secret`);
        console.log(`  ${(0, ui_1.color)('--regenerate-secret', 'command')}    Generate new management secret`);
        console.log(`  ${(0, ui_1.color)('--variant <name>', 'command')}       Target specific variant (with --api-key)`);
        console.log(`  ${(0, ui_1.color)('--reset', 'command')}                Reset all to defaults`);
        console.log(`  ${(0, ui_1.color)('--help, -h', 'command')}             Show this help`);
        console.log('');
        console.log((0, ui_1.subheader)('Examples'));
        console.log(`  ${(0, ui_1.dim)('# View current tokens')}`);
        console.log(`  ccs tokens`);
        console.log('');
        console.log(`  ${(0, ui_1.dim)('# Set custom API key')}`);
        console.log(`  ccs tokens --api-key my-custom-key-123`);
        console.log('');
        console.log(`  ${(0, ui_1.dim)('# Generate secure management secret')}`);
        console.log(`  ccs tokens --regenerate-secret`);
        console.log('');
        console.log(`  ${(0, ui_1.dim)('# Set per-variant API key')}`);
        console.log(`  ccs tokens --variant my-gemini --api-key variant-key-456`);
        console.log('');
        return 0;
    }
    if (resetFlag) {
        (0, cliproxy_1.resetAuthToDefaults)();
        (0, config_generator_1.regenerateConfig)();
        console.log((0, ui_1.ok)('Auth tokens reset to defaults'));
        console.log((0, ui_1.info)('CLIProxy config regenerated'));
        return 0;
    }
    if (regenerateSecretFlag && hasSecretFlag) {
        console.error((0, ui_1.fail)('Cannot combine --secret with --regenerate-secret'));
        return 1;
    }
    if (hasApiKeyFlag && (!apiKeyValue || apiKeyValue.startsWith('-'))) {
        console.error((0, ui_1.fail)('Missing value for --api-key'));
        return 1;
    }
    if (hasSecretFlag && (!secretValue || secretValue.startsWith('-'))) {
        console.error((0, ui_1.fail)('Missing value for --secret'));
        return 1;
    }
    let updated = false;
    if (regenerateSecretFlag) {
        const newSecret = (0, cliproxy_1.generateSecureToken)(32);
        (0, cliproxy_1.setGlobalManagementSecret)(newSecret);
        console.log((0, ui_1.ok)('New management secret generated'));
        console.log(`  Secret: ${(0, cliproxy_1.maskToken)(newSecret)}`);
        updated = true;
    }
    if (hasApiKeyFlag) {
        const resolvedApiKey = apiKeyValue;
        if (variantValue) {
            try {
                (0, cliproxy_1.setVariantApiKey)(variantValue, resolvedApiKey);
                console.log((0, ui_1.ok)(`API key set for variant '${variantValue}'`));
            }
            catch (err) {
                const error = err instanceof Error ? err.message : 'Unknown error';
                console.error((0, ui_1.fail)(error));
                return 1;
            }
        }
        else {
            (0, cliproxy_1.setGlobalApiKey)(resolvedApiKey);
            console.log((0, ui_1.ok)('Global API key updated'));
        }
        updated = true;
    }
    if (hasSecretFlag) {
        (0, cliproxy_1.setGlobalManagementSecret)(secretValue);
        console.log((0, ui_1.ok)('Management secret updated'));
        updated = true;
    }
    if (updated) {
        (0, config_generator_1.regenerateConfig)();
        console.log((0, ui_1.info)('CLIProxy config regenerated'));
        console.log((0, ui_1.warn)('Restart CLIProxy to apply: ccs cliproxy restart'));
        return 0;
    }
    await showAuthStatus(showFlag);
    return 0;
}
exports.handleTokensCommand = handleTokensCommand;
//# sourceMappingURL=tokens-command.js.map