"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleConfigChannelsCommand = exports.parseChannelsCommandArgs = void 0;
const ui_1 = require("../utils/ui");
const unified_config_types_1 = require("../config/unified-config-types");
const official_channels_store_1 = require("../channels/official-channels-store");
const official_channels_runtime_1 = require("../channels/official-channels-runtime");
const arg_extractor_1 = require("./arg-extractor");
const config_loader_facade_1 = require("../config/config-loader-facade");
function parseTokenAssignment(value) {
    const separatorIndex = value.indexOf('=');
    if (separatorIndex === -1) {
        return value.trim() ? { channelId: 'discord', token: value.trim() } : null;
    }
    const channelId = value.slice(0, separatorIndex).trim().toLowerCase();
    const token = value.slice(separatorIndex + 1).trim();
    if (!(0, official_channels_runtime_1.isOfficialChannelId)(channelId) || !token) {
        return null;
    }
    return { channelId, token };
}
function parseChannelsCommandArgs(args) {
    const setSelection = (0, arg_extractor_1.extractOption)(args, ['--set']);
    const setToken = (0, arg_extractor_1.extractOption)(args, ['--set-token']);
    const clearToken = (0, arg_extractor_1.extractOption)(args, ['--clear-token']);
    let clearTokenAll = false;
    let clearTokenChannel;
    let clearTokenInvalid;
    if (clearToken.found) {
        if (clearToken.missingValue) {
            clearTokenAll = true;
        }
        else if (clearToken.value) {
            const channelId = clearToken.value.trim().toLowerCase();
            if ((0, official_channels_runtime_1.isOfficialChannelId)(channelId)) {
                clearTokenChannel = channelId;
            }
            else {
                clearTokenInvalid = clearToken.value;
            }
        }
    }
    let parsedSetToken;
    let setTokenInvalid;
    if (setToken.found && !setToken.missingValue && setToken.value) {
        parsedSetToken = parseTokenAssignment(setToken.value) ?? undefined;
        if (!parsedSetToken) {
            setTokenInvalid = setToken.value;
        }
    }
    return {
        enable: (0, arg_extractor_1.hasAnyFlag)(args, ['--enable']),
        disable: (0, arg_extractor_1.hasAnyFlag)(args, ['--disable']),
        clear: (0, arg_extractor_1.hasAnyFlag)(args, ['--clear']),
        unattended: (0, arg_extractor_1.hasAnyFlag)(args, ['--unattended']),
        noUnattended: (0, arg_extractor_1.hasAnyFlag)(args, ['--no-unattended']),
        setSelection: setSelection.found ? setSelection.value : undefined,
        setSelectionMissing: setSelection.found && setSelection.missingValue,
        clearTokenAll,
        clearTokenChannel,
        clearTokenInvalid,
        setToken: parsedSetToken,
        setTokenMissing: setToken.found && setToken.missingValue,
        setTokenInvalid,
        help: (0, arg_extractor_1.hasAnyFlag)(args, ['--help', '-h']),
    };
}
exports.parseChannelsCommandArgs = parseChannelsCommandArgs;
function showHelp() {
    console.log('');
    console.log((0, ui_1.header)('ccs config channels'));
    console.log('');
    console.log(`  ${(0, official_channels_runtime_1.getOfficialChannelsSectionDescription)()}`);
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsDocsSummary)())}`);
    console.log(`  ${(0, ui_1.dim)('Fastest path: run `ccs config`, open Settings -> Channels, turn on the channel, save the token if needed, then run `ccs`.')}`);
    console.log('');
    console.log((0, ui_1.subheader)('Usage:'));
    console.log(`  ${(0, ui_1.color)('ccs config channels', 'command')} [options]`);
    console.log('');
    console.log((0, ui_1.subheader)('Options:'));
    console.log(`  ${(0, ui_1.color)('--set <csv|all>', 'command')}      ${(0, official_channels_runtime_1.getOfficialChannelsSetHelp)()}`);
    console.log(`  ${(0, ui_1.color)('--clear', 'command')}              Clear all selected channels`);
    console.log(`  ${(0, ui_1.color)('--enable', 'command')}             Legacy compatibility alias: add Discord`);
    console.log(`  ${(0, ui_1.color)('--disable', 'command')}            Legacy compatibility alias: remove Discord`);
    console.log(`  ${(0, ui_1.color)('--unattended', 'command')}         Also add --dangerously-skip-permissions`);
    console.log(`  ${(0, ui_1.color)('--no-unattended', 'command')}      Disable unattended runtime flag`);
    console.log(`  ${(0, ui_1.color)('--set-token <spec>', 'command')}   ${(0, official_channels_runtime_1.getOfficialChannelTokenHelp)()}`);
    console.log(`  ${(0, ui_1.color)('--clear-token [channel]', 'command')} ${(0, official_channels_runtime_1.getOfficialChannelClearTokenHelp)()}`);
    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.color)('ccs config', 'command')}                                    ${(0, ui_1.dim)('# Dashboard -> Settings -> Channels (fastest path)')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config channels', 'command')}                           ${(0, ui_1.dim)('# Show status')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config channels --set telegram,discord', 'command')}  ${(0, ui_1.dim)('# Enable Telegram + Discord')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config channels --set all', 'command')}               ${(0, ui_1.dim)('# Enable all official channels')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config channels --set-token telegram=123:abc', 'command')} ${(0, ui_1.dim)('# Save TELEGRAM_BOT_TOKEN')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs config channels --clear-token discord', 'command')}   ${(0, ui_1.dim)('# Clear one token')}`);
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsSupportMessage)())}`);
    console.log('');
}
function showStatus() {
    const config = (0, config_loader_facade_1.getOfficialChannelsConfig)();
    const selected = config.selected;
    const environment = (0, official_channels_runtime_1.getOfficialChannelsEnvironmentStatus)();
    const channelRows = (0, official_channels_runtime_1.expandOfficialChannelSelection)('all').map((channelId) => {
        const selectedForLaunch = selected.includes(channelId);
        const tokenStatus = (0, official_channels_store_1.getOfficialChannelTokenStatus)(channelId);
        return {
            id: channelId,
            displayName: (0, official_channels_runtime_1.getOfficialChannelDisplayName)(channelId),
            selected: selectedForLaunch,
            requiresToken: (0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId),
            tokenConfigured: (0, official_channels_store_1.hasConfiguredOfficialChannelToken)(channelId),
            tokenStatus,
            unavailableReason: (0, official_channels_runtime_1.getOfficialChannelUnavailableReason)(channelId),
            setup: (0, official_channels_runtime_1.buildOfficialChannelSetupSummary)({
                id: channelId,
                displayName: (0, official_channels_runtime_1.getOfficialChannelDisplayName)(channelId),
                selected: selectedForLaunch,
                requiresToken: (0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(channelId),
                tokenAvailable: tokenStatus.available,
                tokenSource: tokenStatus.source,
                savedInClaudeState: tokenStatus.savedInClaudeState,
                processEnvAvailable: tokenStatus.processEnvAvailable,
                unavailableReason: (0, official_channels_runtime_1.getOfficialChannelUnavailableReason)(channelId),
            }),
        };
    });
    const summary = (0, official_channels_runtime_1.buildOfficialChannelsReadinessSummary)({
        config,
        environment,
        channels: channelRows.map((channel) => ({
            id: channel.id,
            displayName: channel.displayName,
            selected: channel.selected,
            requiresToken: channel.requiresToken,
            tokenAvailable: channel.tokenStatus.available,
            tokenSource: channel.tokenStatus.source,
            savedInClaudeState: channel.tokenStatus.savedInClaudeState,
            processEnvAvailable: channel.tokenStatus.processEnvAvailable,
            unavailableReason: channel.unavailableReason,
        })),
    });
    const launchPreview = (0, official_channels_runtime_1.buildOfficialChannelsLaunchPreview)({
        config,
        environment,
        channels: channelRows.map((channel) => ({
            id: channel.id,
            displayName: channel.displayName,
            selected: channel.selected,
            requiresToken: channel.requiresToken,
            tokenAvailable: channel.tokenStatus.available,
            tokenSource: channel.tokenStatus.source,
            savedInClaudeState: channel.tokenStatus.savedInClaudeState,
            processEnvAvailable: channel.tokenStatus.processEnvAvailable,
            unavailableReason: channel.unavailableReason,
        })),
    });
    console.log('');
    console.log((0, ui_1.header)('Official Channels Configuration'));
    console.log('');
    console.log(`  Status:       ${summary.state === 'ready'
        ? (0, ui_1.ok)(summary.title)
        : summary.state === 'limited'
            ? (0, ui_1.warn)(summary.title)
            : (0, ui_1.warn)(summary.title)}`);
    console.log(`  ${(0, ui_1.dim)(summary.message)}`);
    console.log(`  ${(0, ui_1.dim)(summary.nextStep)}`);
    console.log('');
    console.log(`  Launch:       ${(0, ui_1.info)(launchPreview.title)}`);
    console.log(`  ${(0, ui_1.dim)(launchPreview.detail)}`);
    if (launchPreview.appendedArgs.length > 0) {
        console.log(`  ${(0, ui_1.dim)(`ccs adds: ${launchPreview.appendedArgs.join(' ')}`)}`);
    }
    if (launchPreview.skippedMessages.length > 0) {
        console.log(`  ${(0, ui_1.dim)(`Skipped: ${launchPreview.skippedMessages.join(' | ')}`)}`);
    }
    console.log('');
    console.log(`  Channels:     ${selected.length > 0 ? (0, ui_1.ok)((0, official_channels_runtime_1.getChannelConfigSelectionLabel)(selected)) : (0, ui_1.warn)('Disabled')}`);
    console.log(`  Unattended:   ${config.unattended ? (0, ui_1.warn)('Enabled') : (0, ui_1.info)('Disabled')}`);
    console.log(`  Bun:          ${environment.bunInstalled ? (0, ui_1.ok)('Installed') : (0, ui_1.warn)('Missing')}`);
    console.log(`  Claude Code:  ${environment.claudeVersion.state === 'supported'
        ? (0, ui_1.ok)(environment.claudeVersion.message)
        : environment.claudeVersion.state === 'unsupported'
            ? (0, ui_1.warn)(environment.claudeVersion.message)
            : (0, ui_1.info)(environment.claudeVersion.message)}`);
    console.log(`  Claude Auth:  ${environment.auth.state === 'eligible'
        ? (0, ui_1.ok)(environment.auth.message)
        : environment.auth.state === 'ineligible'
            ? (0, ui_1.warn)(environment.auth.message)
            : (0, ui_1.info)(environment.auth.message)}`);
    console.log('');
    console.log((0, ui_1.subheader)('Applies To:'));
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsSupportMessage)())}`);
    console.log(`  ${(0, ui_1.dim)(`Supported profiles: ${(0, official_channels_runtime_1.getOfficialChannelsSupportedProfiles)().join(', ')}`)}`);
    console.log(`  ${(0, ui_1.dim)(environment.stateScopeMessage)}`);
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsAccountStatusCaveat)())}`);
    if (environment.auth.orgRequirementMessage) {
        console.log(`  ${(0, ui_1.dim)(environment.auth.orgRequirementMessage)}`);
    }
    console.log('');
    console.log((0, ui_1.subheader)('Channels:'));
    for (const channel of channelRows) {
        const status = channel.setup.state === 'ready'
            ? (0, ui_1.ok)(channel.setup.label)
            : channel.setup.state === 'not_selected'
                ? (0, ui_1.info)(channel.setup.label)
                : (0, ui_1.warn)(channel.setup.label);
        console.log(`  ${channel.selected ? '[x]' : '[ ]'} ${channel.displayName}: ${status}`);
        console.log(`      ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelSummary)(channel.id))}`);
        console.log(`      ${(0, ui_1.dim)(channel.setup.detail)}`);
        console.log(`      ${(0, ui_1.dim)(channel.setup.nextStep)}`);
        if (channel.requiresToken) {
            const envKey = (0, official_channels_runtime_1.getOfficialChannelEnvKey)(channel.id) ?? '';
            if (channel.tokenStatus.source === 'saved_env') {
                console.log(`      ${(0, ui_1.dim)(`${envKey}: saved in Claude channel state`)}`);
                if (channel.tokenStatus.processEnvAvailable) {
                    console.log(`      ${(0, ui_1.dim)(`${envKey}: also available from current CCS process env`)}`);
                }
                if (channel.tokenStatus.tokenPath) {
                    console.log(`      ${(0, ui_1.dim)(channel.tokenStatus.tokenPath)}`);
                }
            }
            else if (channel.tokenStatus.source === 'process_env') {
                console.log(`      ${(0, ui_1.dim)(`${envKey}: available from current CCS process env`)}`);
            }
            else {
                console.log(`      ${(0, ui_1.dim)(`${envKey}: missing`)}`);
                if (channel.tokenStatus.tokenPath) {
                    console.log(`      ${(0, ui_1.dim)(channel.tokenStatus.tokenPath)}`);
                }
            }
        }
    }
    console.log('');
    console.log((0, ui_1.subheader)('Notes:'));
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsLegacyEnableHelp)())}`);
    console.log(`  ${(0, ui_1.dim)(environment.stateScopeMessage)}`);
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelMacOSHelp)())}`);
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsRuntimeNote)())}`);
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsCompatibilityMessage)())}`);
    console.log(`  ${(0, ui_1.dim)((0, official_channels_runtime_1.getOfficialChannelsAccountStatusCaveat)())}`);
    console.log('');
    console.log((0, ui_1.subheader)('Claude-side Setup:'));
    for (const channelId of (0, official_channels_runtime_1.expandOfficialChannelSelection)('all')) {
        console.log(`  ${(0, ui_1.dim)(`${(0, official_channels_runtime_1.getOfficialChannelDisplayName)(channelId)}:`)}`);
        for (const command of (0, official_channels_runtime_1.getOfficialChannelManualSetupCommands)(channelId)) {
            console.log(`    ${(0, ui_1.color)(command, 'command')}`);
        }
    }
    console.log('');
}
function resolveNextSelection(args) {
    if (args.setSelection !== undefined) {
        return (0, official_channels_runtime_1.expandOfficialChannelSelection)(args.setSelection);
    }
    if (args.clear) {
        return [];
    }
    return null;
}
async function handleConfigChannelsCommand(args) {
    await (0, ui_1.initUI)();
    const options = parseChannelsCommandArgs(args);
    if (options.help) {
        showHelp();
        return;
    }
    if (options.setSelectionMissing) {
        console.error((0, ui_1.fail)(`--set requires a value (${(0, official_channels_runtime_1.getOfficialChannelChoices)()} or all)`));
        process.exitCode = 1;
        return;
    }
    if (options.setSelection !== undefined &&
        !(0, official_channels_runtime_1.isOfficialChannelSelectionValid)(options.setSelection)) {
        console.error((0, ui_1.fail)(`Invalid --set value: ${options.setSelection} (${(0, official_channels_runtime_1.getOfficialChannelChoices)()} or all)`));
        process.exitCode = 1;
        return;
    }
    if (options.setTokenMissing) {
        console.error((0, ui_1.fail)('--set-token requires a value'));
        process.exitCode = 1;
        return;
    }
    if (options.setTokenInvalid) {
        console.error((0, ui_1.fail)(`Invalid --set-token value: ${options.setTokenInvalid} (use <channel>=<token>)`));
        process.exitCode = 1;
        return;
    }
    if (options.clearTokenInvalid) {
        console.error((0, ui_1.fail)(`Invalid --clear-token value: ${options.clearTokenInvalid} (use ${(0, official_channels_runtime_1.getOfficialChannelChoices)()})`));
        process.exitCode = 1;
        return;
    }
    const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
    const nextConfig = {
        ...(config.channels ?? unified_config_types_1.DEFAULT_OFFICIAL_CHANNELS_CONFIG),
        selected: [...(config.channels?.selected ?? unified_config_types_1.DEFAULT_OFFICIAL_CHANNELS_CONFIG.selected)],
    };
    const explicitSelection = resolveNextSelection(options);
    const hasConfigMutation = explicitSelection !== null ||
        options.enable ||
        options.disable ||
        options.unattended ||
        options.noUnattended;
    if (explicitSelection) {
        nextConfig.selected = explicitSelection;
    }
    if (options.enable && !nextConfig.selected.includes('discord')) {
        nextConfig.selected.push('discord');
    }
    if (options.disable) {
        nextConfig.selected = nextConfig.selected.filter((channelId) => channelId !== 'discord');
    }
    if (options.unattended) {
        nextConfig.unattended = true;
    }
    if (options.noUnattended) {
        nextConfig.unattended = false;
    }
    try {
        if (hasConfigMutation) {
            (0, config_loader_facade_1.updateConfig)({ channels: nextConfig });
        }
        if (options.setToken) {
            if (!(0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(options.setToken.channelId)) {
                throw new Error(`${options.setToken.channelId} does not use a bot token.`);
            }
            (0, official_channels_store_1.setConfiguredOfficialChannelToken)(options.setToken.channelId, options.setToken.token);
            console.log((0, ui_1.ok)(`${(0, official_channels_runtime_1.getOfficialChannelDisplayName)(options.setToken.channelId)} token saved`));
            console.log('');
        }
        if (options.clearTokenChannel) {
            if (!(0, official_channels_runtime_1.getOfficialChannelTokenIds)().includes(options.clearTokenChannel)) {
                throw new Error(`${options.clearTokenChannel} does not use a bot token.`);
            }
            (0, official_channels_store_1.clearConfiguredOfficialChannelTokensEverywhere)(options.clearTokenChannel);
            console.log((0, ui_1.ok)(`${(0, official_channels_runtime_1.getOfficialChannelDisplayName)(options.clearTokenChannel)} token cleared`));
            console.log('');
        }
        else if (options.clearTokenAll) {
            (0, official_channels_store_1.clearConfiguredOfficialChannelTokensEverywhere)();
            console.log((0, ui_1.ok)('All saved channel tokens cleared'));
            console.log('');
        }
        if (hasConfigMutation) {
            console.log((0, ui_1.ok)('Configuration updated'));
            console.log('');
        }
    }
    catch (error) {
        console.error((0, ui_1.fail)(error.message));
        process.exitCode = 1;
        return;
    }
    showStatus();
}
exports.handleConfigChannelsCommand = handleConfigChannelsCommand;
//# sourceMappingURL=config-channels-command.js.map