/**
 * Machine-readable output helper for interactive prompts
 *
 * Provides utilities for outputting prompt configurations as JSON
 * instead of rendering interactive UI, enabling AI agents and scripts
 * to interact with the CLI programmatically.
 *
 * Design notes:
 * - Stateless functions for easy unit testing
 * - Designed for future extraction as standalone npm package
 * - Supports both explicit --json flag and automatic non-TTY detection
 *
 * Exit code conventions:
 * - EXIT_SUCCESS (0): Command completed successfully
 * - EXIT_ERROR (1): Command failed with an error
 * - EXIT_NEEDS_INPUT (2): Command needs additional input (prompt required)
 */
/**
 * Exit code for successful command completion
 */
export const EXIT_SUCCESS = 0;
/**
 * Exit code for command failure/error
 */
export const EXIT_ERROR = 1;
/**
 * Exit code when command needs additional input (prompt required)
 * Use this exit code when outputting a prompt in JSON mode to signal
 * to scripts/agents that the command didn't fail, but needs more input.
 */
export const EXIT_NEEDS_INPUT = 2;
/**
 * Check if the current environment is non-TTY (piped output)
 *
 * @returns true if stdout is not a TTY (e.g., piped to another process)
 */
export function isNonTTY() {
    return !process.stdout.isTTY;
}
/**
 * Determine if JSON output mode is active (for AI agents)
 *
 * Returns true if:
 * - The --json flag is set (or -m/--machine aliases)
 * - The environment is non-TTY (piped output)
 *
 * @param flags - Command flags object
 * @returns true if JSON mode should be used
 */
export function shouldOutputJson(flags) {
    // --json flag (includes -m and --machine aliases)
    if (flags.json === true) {
        return true;
    }
    // Automatic detection for non-TTY environments
    return isNonTTY();
}
/**
 * Alias for shouldOutputJson - clearer name for agent-focused code
 */
export const isAgentMode = shouldOutputJson;
/**
 * Determine if machine-readable output mode is active (for AI agents/scripts)
 *
 * Returns true if:
 * - The --json flag is set (or -m/--machine aliases)
 * - The environment is non-TTY (piped output)
 *
 * @param flags - Command flags object
 * @returns true if machine-readable output mode should be used
 */
export function isMachineOutput(flags) {
    // --json flag (includes -m and --machine aliases)
    if (flags.json === true) {
        return true;
    }
    // Automatic detection for non-TTY environments
    return isNonTTY();
}
/**
 * Create metadata object for JSON output
 *
 * @param command - Command name (e.g., "work spawn")
 * @param flags - Flags passed to the command
 * @returns Metadata object
 */
export function createMetadata(command, flags) {
    // Filter out internal/sensitive flags
    const filteredFlags = {};
    for (const [key, value] of Object.entries(flags)) {
        // Skip undefined values and internal flags
        if (value !== undefined && !key.startsWith('_')) {
            filteredFlags[key] = value;
        }
    }
    return {
        command,
        flags: filteredFlags,
        timestamp: new Date().toISOString(),
    };
}
/**
 * Output a prompt configuration as JSON and exit
 *
 * Use this when a command would normally show an interactive prompt.
 * Outputs the prompt config so agents can understand what input is needed,
 * then exits with EXIT_NEEDS_INPUT (2) to signal the command needs more input.
 *
 * @param config - Prompt configuration
 * @param metadata - Command metadata
 */
export function outputPromptAsJson(config, metadata) {
    const output = {
        prompt: config,
        metadata,
    };
    console.log(JSON.stringify(output, null, 2));
    process.exit(EXIT_NEEDS_INPUT);
}
/**
 * Output success result as JSON and exit
 *
 * Use this when all required data was provided via flags
 * and no prompt is needed. Exits with EXIT_SUCCESS (0) to signal
 * successful command completion.
 *
 * @param result - Command-specific result data
 * @param metadata - Command metadata
 */
export function outputSuccessAsJson(result, metadata) {
    const output = {
        prompt: null,
        success: true,
        result,
        metadata,
    };
    console.log(JSON.stringify(output, null, 2));
    process.exit(EXIT_SUCCESS);
}
/**
 * Output error as JSON and exit
 *
 * Use this when an error occurs and --json flag is active.
 * Provides structured error output for programmatic handling,
 * then exits with EXIT_ERROR (1).
 *
 * @param code - Machine-readable error code (e.g., "NO_TICKETS_AVAILABLE")
 * @param message - Human-readable error message
 * @param metadata - Command metadata
 */
export function outputErrorAsJson(code, message, metadata) {
    const output = {
        error: {
            code,
            message,
        },
        metadata,
    };
    console.log(JSON.stringify(output, null, 2));
    process.exit(EXIT_ERROR);
}
/**
 * Convert inquirer choices to PromptChoice format
 *
 * Handles both simple string choices and object choices,
 * filtering out Separator instances.
 *
 * @param choices - Inquirer choices array
 * @returns Array of PromptChoice objects
 */
export function normalizeChoices(choices) {
    const normalized = [];
    for (const choice of choices) {
        // Skip Separator instances (they have a 'type' property set to 'separator')
        if (typeof choice === 'object' &&
            choice !== null &&
            'type' in choice &&
            choice.type === 'separator') {
            continue;
        }
        // Handle string choices
        if (typeof choice === 'string') {
            normalized.push({ name: choice, value: choice });
            continue;
        }
        // Handle object choices
        if (typeof choice === 'object' &&
            choice !== null &&
            'name' in choice &&
            'value' in choice) {
            const obj = choice;
            normalized.push({
                name: obj.name,
                value: String(obj.value),
                ...(obj.disabled !== undefined && { disabled: Boolean(obj.disabled) }),
                ...(obj.command !== undefined && { command: obj.command }),
            });
        }
    }
    return normalized;
}
/**
 * Build a prompt config object from inquirer prompt options
 *
 * @param type - Prompt type
 * @param name - Field name
 * @param message - User-facing message
 * @param choices - Optional choices array
 * @param defaultValue - Optional default value
 * @returns PromptConfig object
 */
export function buildPromptConfig(type, name, message, choices, defaultValue) {
    const config = {
        type,
        name,
        message,
    };
    if (choices) {
        config.choices = normalizeChoices(choices);
    }
    if (defaultValue !== undefined) {
        config.default = defaultValue;
    }
    return config;
}
/**
 * Build a form prompt config with multiple fields
 *
 * @param fields - Array of form field configurations
 * @returns PromptConfig object with type 'form'
 */
export function buildFormPromptConfig(fields) {
    return {
        type: 'form',
        fields,
    };
}
