import { Args, Flags } from '@oclif/core';
import chalk from 'chalk';
import inquirer from 'inquirer';
import { PromptCommand } from '../../lib/prompt-command.js';
import { machineOutputFlags } from '../../lib/pmo/index.js';
import { getWorkspaceInfo, validateAgentNames, addAgentsToWorkspace } from '../../lib/agents/commands.js';
import { ensureBuiltinThemes, BUILTIN_THEMES, isValidAgentName, normalizeAgentName } from '../../lib/themes.js';
import { getTheme, getThemes, getAvailableThemeNames, getActiveTheme } from '../../lib/database/index.js';
import { shouldOutputJson, outputPromptAsJson, outputErrorAsJson, createMetadata, buildPromptConfig, } from '../../lib/prompt-json.js';
export default class Add extends PromptCommand {
    static description = 'Add new agents to the workspace';
    static examples = [
        '<%= config.bin %> <%= command.id %> zeus',
        '<%= config.bin %> <%= command.id %> agent-1 agent-2',
        '<%= config.bin %> <%= command.id %> --theme billionaires',
        '<%= config.bin %> <%= command.id %> my-agent --no-container',
    ];
    static args = {
        names: Args.string({
            description: 'Agent names to add (space-separated)',
            required: false,
        }),
    };
    static flags = {
        'no-container': Flags.boolean({
            description: 'Skip devcontainer setup (not recommended for autonomous agents)',
            default: false,
        }),
        theme: Flags.string({
            char: 't',
            description: 'Pick agent name(s) from a theme (billionaires, toyotas, companies, or custom)',
        }),
        ...machineOutputFlags,
        clone: Flags.boolean({
            description: 'Use independent git clone instead of worktree (more isolation, no real-time sync)',
            default: false,
        }),
    };
    static strict = false; // Allow multiple agent names
    async run() {
        const { argv, flags } = await this.parse(Add);
        // Check if JSON output mode is active
        const jsonMode = shouldOutputJson(flags);
        try {
            // Get workspace information
            const workspaceInfo = getWorkspaceInfo();
            let agentNames = argv;
            let themeId;
            // Theme mode: pick from a specific theme
            if (flags.theme) {
                // Ensure built-in themes are seeded
                ensureBuiltinThemes(workspaceInfo.path);
                // Validate theme exists
                const theme = getTheme(workspaceInfo.path, flags.theme);
                if (!theme) {
                    const available = BUILTIN_THEMES.map(t => t.name).join(', ');
                    if (jsonMode) {
                        outputErrorAsJson('THEME_NOT_FOUND', `Theme "${flags.theme}" not found. Available: ${available}`, createMetadata('staff add', flags));
                        return;
                    }
                    this.error(`Theme "${flags.theme}" not found. Available: ${available}`);
                }
                themeId = theme.id;
                // Get available names from theme
                const availableNames = getAvailableThemeNames(workspaceInfo.path, themeId);
                if (availableNames.length === 0) {
                    if (jsonMode) {
                        outputErrorAsJson('NO_AVAILABLE_NAMES', `No available names in theme "${theme.display_name}". All names are in use.`, createMetadata('staff add', flags));
                        return;
                    }
                    this.error(`No available names in theme "${theme.display_name}". All names are in use.`);
                }
                // Build choices once, use for both JSON and interactive modes
                const nameChoices = availableNames.map(name => ({ name, value: name }));
                const selectMessage = `Select agent names from ${theme.display_name}:`;
                // In JSON mode, output theme names selection prompt
                if (jsonMode) {
                    outputPromptAsJson(buildPromptConfig('checkbox', 'names', selectMessage, nameChoices), createMetadata('staff add', flags));
                    return;
                }
                // Interactive selection from theme
                const { selected } = await this.prompt([{
                        type: 'checkbox',
                        name: 'selected',
                        message: selectMessage,
                        choices: nameChoices,
                        validate: (input) => input.length > 0 || 'Please select at least one name'
                    }], null);
                agentNames = selected;
            }
            // Interactive mode: show names from workspace's active theme
            else if (agentNames.length === 0) {
                // Ensure built-in themes are seeded
                ensureBuiltinThemes(workspaceInfo.path);
                // Check if workspace has an active theme
                const activeTheme = getActiveTheme(workspaceInfo.path);
                if (activeTheme) {
                    // Workspace has a theme - show names from it directly
                    themeId = activeTheme.id;
                    const availableNames = getAvailableThemeNames(workspaceInfo.path, activeTheme.id);
                    if (availableNames.length === 0) {
                        if (jsonMode) {
                            outputErrorAsJson('NO_AVAILABLE_NAMES', `No available names in ${activeTheme.display_name}. All names are in use.`, createMetadata('staff add', flags));
                            return;
                        }
                        this.log(chalk.yellow(`No available names in ${activeTheme.display_name}. All names are in use.`));
                        this.log(chalk.blue('Use --theme to pick from a different theme, or enter names directly.'));
                        return;
                    }
                    // Build choices once, use for both JSON and interactive modes
                    const nameChoices = [
                        ...availableNames.map(name => ({ name, value: name })),
                        { name: 'Enter custom name(s)...', value: '__custom__' },
                    ];
                    const selectMessage = `Select agents from ${activeTheme.display_name}:`;
                    // In JSON mode, output agent names selection prompt
                    if (jsonMode) {
                        outputPromptAsJson(buildPromptConfig('checkbox', 'names', selectMessage, nameChoices), createMetadata('staff add', flags));
                        return;
                    }
                    // Add separator before custom option for interactive mode
                    const choices = [
                        ...nameChoices.slice(0, -1),
                        new inquirer.Separator(),
                        { name: chalk.blue(nameChoices[nameChoices.length - 1].name), value: nameChoices[nameChoices.length - 1].value }
                    ];
                    const { selected } = await this.prompt([{
                            type: 'checkbox',
                            name: 'selected',
                            message: selectMessage,
                            choices,
                            pageSize: 20,
                            validate: (input) => input.length > 0 || 'Please select at least one name'
                        }], null);
                    // Check if custom was selected
                    const hasCustom = selected.includes('__custom__');
                    const themedSelections = selected.filter((s) => s !== '__custom__');
                    if (hasCustom) {
                        const { customNames } = await this.prompt([{
                                type: 'input',
                                name: 'customNames',
                                message: 'Enter custom agent names (space-separated):',
                                validate: (input) => {
                                    if (!input.trim())
                                        return 'Please enter at least one name';
                                    return true;
                                }
                            }], null);
                        const rawNames = customNames.trim().split(/\s+/);
                        const normalizedCustom = rawNames.map((n) => normalizeAgentName(n)).filter((n) => n && isValidAgentName(n));
                        agentNames.push(...normalizedCustom);
                    }
                    if (themedSelections.length > 0) {
                        agentNames.push(...themedSelections);
                    }
                }
                else {
                    // No active theme - prompt to pick one or enter custom names
                    const themes = getThemes(workspaceInfo.path);
                    const themesWithNames = themes.map(t => ({
                        theme: t,
                        availableCount: getAvailableThemeNames(workspaceInfo.path, t.id).length
                    })).filter(t => t.availableCount > 0);
                    // Build choices once, use for both JSON and interactive modes
                    const themeChoices = [
                        ...themesWithNames.map(({ theme, availableCount }) => ({
                            name: `${theme.display_name} (${availableCount} available)`,
                            value: theme.id
                        })),
                        { name: 'Enter custom name(s)', value: '__custom__' },
                    ];
                    const selectMessage = 'No theme set. Select a theme or enter custom names:';
                    // In JSON mode, output theme selection prompt
                    if (jsonMode) {
                        outputPromptAsJson(buildPromptConfig('list', 'theme', selectMessage, themeChoices), createMetadata('staff add', flags));
                        return;
                    }
                    // Add separator and styling for interactive mode
                    const interactiveChoices = [
                        ...themeChoices.slice(0, -1).map(c => ({
                            name: c.name.replace(/\((\d+) available\)/, chalk.dim(`($1 available)`)),
                            value: c.value
                        })),
                        new inquirer.Separator(),
                        { name: chalk.blue(themeChoices[themeChoices.length - 1].name), value: themeChoices[themeChoices.length - 1].value }
                    ];
                    const { selectedTheme } = await this.prompt([{
                            type: 'list',
                            name: 'selectedTheme',
                            message: selectMessage,
                            choices: interactiveChoices
                        }], null);
                    if (selectedTheme === '__custom__') {
                        const { customNames } = await this.prompt([{
                                type: 'input',
                                name: 'customNames',
                                message: 'Enter custom agent names (space-separated):',
                                validate: (input) => {
                                    if (!input.trim())
                                        return 'Please enter at least one name';
                                    return true;
                                }
                            }], null);
                        const rawNames = customNames.trim().split(/\s+/);
                        const normalizedCustom = rawNames.map((n) => ({
                            original: n,
                            normalized: normalizeAgentName(n)
                        })).filter((x) => x.normalized && isValidAgentName(x.normalized));
                        const changed = normalizedCustom.filter((x) => x.original !== x.normalized);
                        if (changed.length > 0) {
                            this.log(chalk.blue('Normalized names:'));
                            for (const { original, normalized } of changed) {
                                this.log(chalk.dim(`   ${original} → ${normalized}`));
                            }
                        }
                        agentNames = normalizedCustom.map((x) => x.normalized);
                    }
                    else {
                        themeId = selectedTheme;
                        const theme = getTheme(workspaceInfo.path, selectedTheme);
                        const availableNames = getAvailableThemeNames(workspaceInfo.path, selectedTheme);
                        const { selected } = await this.prompt([{
                                type: 'checkbox',
                                name: 'selected',
                                message: `Select agents from ${theme?.display_name}:`,
                                choices: availableNames.map(name => ({ name, value: name })),
                                pageSize: 20,
                                validate: (input) => input.length > 0 || 'Please select at least one name'
                            }], null);
                        agentNames = selected;
                    }
                }
                if (agentNames.length === 0) {
                    this.log(chalk.yellow('No agents specified.'));
                    return;
                }
            }
            // Validate agent names (skip for theme mode - already validated)
            if (!flags.theme) {
                const { valid, invalid } = validateAgentNames(agentNames);
                if (invalid.length > 0) {
                    this.log(chalk.red(`Invalid agent names: ${invalid.join(', ')}`));
                    this.log(chalk.yellow('Agent names must be lowercase alphanumeric with optional hyphens/underscores.'));
                    if (valid.length === 0) {
                        return;
                    }
                    this.log(chalk.blue(`Proceeding with valid agents: ${valid.join(', ')}`));
                }
                agentNames = valid;
            }
            // Add agents to workspace
            const addedAgents = await addAgentsToWorkspace(workspaceInfo, agentNames, {
                skipDevcontainer: flags['no-container'],
                themeId,
                mountMode: flags.clone ? 'clone' : 'worktree',
            });
            if (addedAgents.length === 0) {
                this.log(chalk.yellow('No new agents to add. All specified agents already exist.'));
                return;
            }
            this.log(chalk.green(`\n Successfully added ${addedAgents.length} agent(s): ${addedAgents.join(', ')}`));
            if (themeId) {
                const theme = getTheme(workspaceInfo.path, themeId);
                this.log(chalk.blue(`   From theme: ${theme?.display_name || themeId}`));
            }
            if (!flags['no-container']) {
                this.log(chalk.blue('   Devcontainer config created for isolated execution'));
            }
        }
        catch (error) {
            this.error(error instanceof Error ? error.message : String(error));
        }
    }
}
//# sourceMappingURL=add.js.map