"use strict";
/**
 * Env Command Handler
 *
 * Export environment variables for third-party tool integration.
 * Outputs shell-evaluable exports for OpenCode, Cursor, Continue, etc.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleEnvCommand = exports.findProfile = exports.parseFlag = exports.transformToOpenAI = exports.formatExportLine = exports.detectShell = void 0;
const ui_1 = require("../utils/ui");
const claude_extension_hosts_1 = require("../shared/claude-extension-hosts");
const claude_extension_setup_1 = require("../shared/claude-extension-setup");
const config_loader_facade_1 = require("../config/config-loader-facade");
const VALID_FORMATS = ['openai', 'anthropic', 'raw', 'claude-extension'];
const VALID_SHELLS = ['bash', 'fish', 'powershell'];
const VALID_SHELL_INPUTS = ['auto', 'bash', 'zsh', 'fish', 'powershell'];
const VALID_EXTENSION_HOSTS = claude_extension_hosts_1.CLAUDE_EXTENSION_HOSTS.map((host) => host.id);
const VALID_ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
/** Auto-detect shell from environment */
function detectShell(flag) {
    if (flag && flag !== 'auto' && VALID_SHELLS.includes(flag)) {
        return flag;
    }
    const shell = process.env['SHELL'] || '';
    if (shell.includes('fish'))
        return 'fish';
    if (shell.includes('pwsh') || process.platform === 'win32')
        return 'powershell';
    return 'bash';
}
exports.detectShell = detectShell;
/** Format a single env var export for the target shell (single-quoted to prevent injection) */
function formatExportLine(shell, key, value) {
    switch (shell) {
        case 'fish':
            // Fish: single quotes prevent expansion; escape embedded single quotes with '\''
            return `set -gx ${key} '${value.replace(/'/g, "'\\''")}'`;
        case 'powershell':
            // PowerShell: single quotes prevent expansion; escape embedded single quotes with ''
            return `$env:${key} = '${value.replace(/'/g, "''")}'`;
        default:
            // Bash/zsh: single quotes prevent all expansion; handle embedded single quotes
            return `export ${key}='${value.replace(/'/g, "'\\''")}'`;
    }
}
exports.formatExportLine = formatExportLine;
/** Map Anthropic env vars to OpenAI-compatible format.
 * OPENAI_MODEL is included so tools that need it (e.g. OpenCode local provider)
 * can discover the model without additional configuration. */
function transformToOpenAI(envVars) {
    const baseUrl = envVars['ANTHROPIC_BASE_URL'] || '';
    const apiKey = envVars['ANTHROPIC_AUTH_TOKEN'] || envVars['ANTHROPIC_API_KEY'] || '';
    const model = envVars['ANTHROPIC_MODEL'] || '';
    const result = {};
    if (apiKey)
        result['OPENAI_API_KEY'] = apiKey;
    if (baseUrl) {
        result['OPENAI_BASE_URL'] = baseUrl;
        result['LOCAL_ENDPOINT'] = baseUrl;
    }
    if (model)
        result['OPENAI_MODEL'] = model;
    return result;
}
exports.transformToOpenAI = transformToOpenAI;
/** Parse --key=value or --key value style args */
function parseFlag(args, flag) {
    // --flag=value style
    const eqMatch = args.find((a) => a.startsWith(`--${flag}=`));
    if (eqMatch)
        return eqMatch.split('=').slice(1).join('=');
    // --flag value style
    const idx = args.indexOf(`--${flag}`);
    if (idx >= 0 && idx + 1 < args.length && !args[idx + 1].startsWith('-')) {
        return args[idx + 1];
    }
    return undefined;
}
exports.parseFlag = parseFlag;
/** Find the first positional argument, skipping flags and their values */
function findProfile(args, flagsWithValues) {
    for (let i = 0; i < args.length; i++) {
        const arg = args[i];
        if (arg.startsWith('-')) {
            // Skip flag values: --flag=value (single token) or --flag value (two tokens)
            const flagName = arg.replace(/^--/, '').split('=')[0];
            if (!arg.includes('=') && flagsWithValues.includes(flagName) && i + 1 < args.length) {
                i++; // skip next arg (the value)
            }
            continue;
        }
        return arg;
    }
    return undefined;
}
exports.findProfile = findProfile;
/** Show help for env command */
function showHelp() {
    console.log('');
    console.log((0, ui_1.header)('ccs env'));
    console.log('');
    console.log('  Export environment variables for third-party tool integration.');
    console.log('');
    console.log((0, ui_1.subheader)('Usage:'));
    console.log(`  ${(0, ui_1.color)('ccs env', 'command')} <profile> [options]`);
    console.log('');
    console.log((0, ui_1.subheader)('Options:'));
    console.log(`  ${(0, ui_1.color)('--format', 'command')} <fmt>    Output format: openai, anthropic, raw, claude-extension ${(0, ui_1.dim)('(default: anthropic)')}`);
    console.log(`  ${(0, ui_1.color)('--shell', 'command')} <sh>      Shell syntax: auto, bash/zsh, fish, powershell ${(0, ui_1.dim)('(default: auto)')}`);
    console.log(`  ${(0, ui_1.color)('--ide', 'command')} <host>      Claude extension host: ${VALID_EXTENSION_HOSTS.join(', ')} ${(0, ui_1.dim)('(default: vscode)')}`);
    console.log(`  ${(0, ui_1.color)('--help, -h', 'command')}        Show this help message`);
    console.log('');
    console.log((0, ui_1.subheader)('Formats:'));
    console.log(`  ${(0, ui_1.color)('openai', 'command')}      OPENAI_API_KEY, OPENAI_BASE_URL, LOCAL_ENDPOINT`);
    console.log(`  ${(0, ui_1.color)('anthropic', 'command')}   ANTHROPIC_BASE_URL, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_MODEL`);
    console.log(`  ${(0, ui_1.color)('raw', 'command')}         All effective env vars as-is`);
    console.log(`  ${(0, ui_1.color)('claude-extension', 'command')}  Settings JSON snippet for the Claude IDE extension`);
    console.log('');
    console.log((0, ui_1.subheader)('Examples:'));
    console.log(`  $ ${(0, ui_1.color)('eval $(ccs env gemini --format openai)', 'command')}     ${(0, ui_1.dim)('# For OpenCode/Cursor')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs env codex --format anthropic', 'command')}          ${(0, ui_1.dim)('# Anthropic vars')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs env glm --format raw', 'command')}                  ${(0, ui_1.dim)('# All vars from settings')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs env agy --format openai --shell fish', 'command')}  ${(0, ui_1.dim)('# Fish shell syntax')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs env work --format claude-extension --ide vscode', 'command')}  ${(0, ui_1.dim)('# VS Code/Cursor snippet')}`);
    console.log(`  $ ${(0, ui_1.color)('ccs env default --format claude-extension --ide windsurf', 'command')}  ${(0, ui_1.dim)('# Clear/replace Windsurf env overrides')}`);
    console.log('');
    console.log((0, ui_1.subheader)('Notes:'));
    console.log(`  ${(0, ui_1.dim)('- Use ccs persist <profile> for shared ~/.claude/settings.json setup when possible.')}`);
    console.log(`  ${(0, ui_1.dim)('- claude-extension output prints JSON only; replace the full environmentVariables setting.')}`);
    console.log('');
}
/**
 * Handle env command
 * @param args - Command line arguments (after 'env')
 */
async function handleEnvCommand(args) {
    await (0, ui_1.initUI)();
    if (args.includes('--help') || args.includes('-h')) {
        showHelp();
        return;
    }
    // Parse profile (first positional argument, skipping flag values)
    const flagsWithValues = ['format', 'shell', 'ide'];
    const profile = findProfile(args, flagsWithValues);
    if (!profile) {
        console.error((0, ui_1.fail)('Usage: ccs env <profile> [--format openai|anthropic|raw|claude-extension]'));
        process.exit(1);
    }
    // Parse flags
    const formatStr = parseFlag(args, 'format') || 'anthropic';
    if (!VALID_FORMATS.includes(formatStr)) {
        console.error((0, ui_1.fail)(`Invalid format: ${formatStr}. Use: ${VALID_FORMATS.join(', ')}`));
        process.exit(1);
    }
    const format = formatStr;
    const shellStr = parseFlag(args, 'shell') || 'auto';
    if (!VALID_SHELL_INPUTS.includes(shellStr)) {
        console.error((0, ui_1.fail)(`Invalid shell: ${shellStr}. Use: ${VALID_SHELL_INPUTS.join(', ')}`));
        process.exit(1);
    }
    // zsh uses the same syntax as bash
    const shell = detectShell(shellStr === 'zsh' ? 'bash' : shellStr);
    const ide = (parseFlag(args, 'ide') || 'vscode');
    if (!VALID_EXTENSION_HOSTS.includes(ide)) {
        console.error((0, ui_1.fail)(`Invalid IDE host: ${ide}. Use: ${VALID_EXTENSION_HOSTS.join(', ')}`));
        process.exit(1);
    }
    let envVars;
    try {
        const resolved = await (0, claude_extension_setup_1.resolveClaudeExtensionSetup)(profile);
        if (resolved.warnings.length > 0) {
            for (const message of resolved.warnings) {
                console.error((0, ui_1.warn)(message));
            }
        }
        envVars = resolved.extensionEnv;
        if (format === 'claude-extension') {
            console.log((0, claude_extension_setup_1.renderClaudeExtensionSettingsJson)(resolved, ide));
            return;
        }
    }
    catch (error) {
        console.error((0, ui_1.fail)(error.message));
        console.error((0, ui_1.dim)(`  Check ${(0, config_loader_facade_1.getCcsDir)()}/config.yaml or run ccs config for profile setup.`));
        process.exit(1);
    }
    if (Object.keys(envVars).length === 0) {
        console.error((0, ui_1.warn)(`No env vars resolved for profile '${profile}'.`));
        process.exit(1);
    }
    // Transform to requested format
    let output;
    switch (format) {
        case 'openai':
            output = transformToOpenAI(envVars);
            break;
        case 'anthropic': {
            // Filter to only Anthropic-relevant vars
            output = {};
            for (const [k, v] of Object.entries(envVars)) {
                if (k.startsWith('ANTHROPIC_')) {
                    output[k] = v;
                }
            }
            break;
        }
        case 'raw':
            output = envVars;
            break;
    }
    // Guard: format transformation may filter out all vars
    if (Object.keys(output).filter((k) => output[k]).length === 0) {
        console.error((0, ui_1.warn)(`No ${format}-format vars found for profile '${profile}'. Try --format raw`));
        process.exit(1);
    }
    // Output shell-formatted exports to stdout
    for (const [key, value] of Object.entries(output)) {
        if (!VALID_ENV_KEY.test(key)) {
            console.error((0, ui_1.dim)(`  Skipping invalid key: ${key}`));
            continue;
        }
        if (value) {
            console.log(formatExportLine(shell, key, value));
        }
    }
}
exports.handleEnvCommand = handleEnvCommand;
//# sourceMappingURL=env-command.js.map