import { isTTYLike } from "./tui.js";
/**
 * Output formatting utilities for agent-friendly CLI
 */
// Store global options for access by output utilities
let globalOutputOptions = null;
/**
 * Set global output options (called during CLI initialization)
 */
export function setOutputOptions(options) {
    globalOutputOptions = options;
}
/**
 * Get current global output options
 */
export function getOutputOptions() {
    return globalOutputOptions;
}
/**
 * Check if JSON output mode is enabled
 */
export function isJSONMode(options) {
    return options.json === true;
}
/**
 * Check if quiet mode is enabled
 */
export function isQuietMode(options) {
    return options.quiet === true;
}
/**
 * Check if progress indicators should be disabled
 */
export function shouldDisableProgress(options) {
    return (options.noProgress === true ||
        options.json === true ||
        options.quiet === true ||
        options.logLevel === 'debug' ||
        options.logLevel === 'trace');
}
/**
 * Check if colors should be disabled
 */
export function shouldDisableColors(options) {
    if (options.color === 'never') {
        return true;
    }
    if (options.color === 'always') {
        return false;
    }
    // auto mode - disable in JSON/quiet mode or non-TTY
    return options.json === true || options.quiet === true || !isTTYLike();
}
/**
 * Filter data to only include specified fields.
 * Supports dot notation for nested fields (e.g., "id,name,properties.title").
 * For arrays, applies the filter to each element.
 */
function filterFields(data, fields) {
    if (Array.isArray(data)) {
        return data.map((item) => filterFields(item, fields));
    }
    if (data && typeof data === 'object') {
        const result = {};
        for (const field of fields) {
            const parts = field.split('.');
            let current = data;
            let target = result;
            for (let i = 0; i < parts.length; i++) {
                const part = parts[i];
                if (current &&
                    typeof current === 'object' &&
                    part in current) {
                    if (i === parts.length - 1) {
                        target[part] = current[part];
                    }
                    else {
                        target[part] = target[part] || {};
                        target = target[part];
                        current = current[part];
                    }
                }
                else {
                    break; // path segment not found — stop traversal for this field
                }
            }
        }
        return result;
    }
    return data;
}
/**
 * Output JSON to stdout (for agent consumption)
 */
export function outputJSON(data) {
    let output = data;
    const options = getOutputOptions();
    if (options?.fields) {
        const fields = options.fields.split(',').map((f) => f.trim());
        output = filterFields(output, fields);
    }
    console.log(JSON.stringify(output, null, 2));
}
/**
 * Output success message (respects quiet/json mode)
 */
export function outputSuccess(message, options, jsonData) {
    if (isJSONMode(options)) {
        if (jsonData) {
            outputJSON({ success: true, ...jsonData });
        }
        else {
            outputJSON({ success: true, message });
        }
    }
    else if (!isQuietMode(options)) {
        console.log(message);
    }
}
/**
 * Output info message (respects quiet/json mode)
 */
export function outputInfo(message, options) {
    if (isJSONMode(options)) {
        // In JSON mode, info messages are typically suppressed
        // unless they're critical (use outputJSON directly for those)
        return;
    }
    if (!isQuietMode(options)) {
        console.log(message);
    }
}
/**
 * Output warning message (respects json mode but not quiet - warnings should be seen)
 */
export function outputWarning(message, options) {
    if (isJSONMode(options)) {
        outputJSON({ warning: message });
    }
    else {
        console.warn(message);
    }
}
/**
 * Check if interactive prompts should be allowed
 */
export function canPrompt(options) {
    // Disable prompts in JSON mode, quiet mode, non-TTY, or when interactivity
    // is explicitly turned off via --no-interactive / AGENTUITY_NON_INTERACTIVE / CI.
    if (options.interactive === false ||
        process.env.AGENTUITY_NON_INTERACTIVE === '1' ||
        process.env.CI) {
        return false;
    }
    return (!isJSONMode(options) &&
        !isQuietMode(options) &&
        !!process.stdin.isTTY &&
        !!process.stdout.isTTY);
}
/**
 * Check if validate mode is enabled
 */
export function isValidateMode(options) {
    return options.validate === true;
}
/**
 * Create a success JSON response
 */
export function createSuccessResponse(data, message, metadata) {
    const response = { success: true };
    if (data !== undefined) {
        response.data = data;
    }
    if (message) {
        response.message = message;
    }
    if (metadata) {
        response.metadata = metadata;
    }
    return response;
}
/**
 * Create an error JSON response
 */
export function createErrorResponse(code, message, details, metadata) {
    const response = {
        success: false,
        error: {
            code,
            message,
            details,
        },
    };
    if (metadata) {
        response.metadata = metadata;
    }
    return response;
}
/**
 * Create response metadata with timestamp and optional execution time
 */
export function createMetadata(startTime, extra) {
    const metadata = {
        timestamp: new Date().toISOString(),
        ...extra,
    };
    if (startTime !== undefined) {
        const duration = Date.now() - startTime;
        metadata.executionTime = `${duration}ms`;
    }
    return metadata;
}
/**
 * Create a batch operation result
 */
export function createBatchResult(results) {
    const succeeded = results.filter((r) => r.success).length;
    const failed = results.filter((r) => !r.success).length;
    return {
        success: failed === 0,
        totalItems: results.length,
        succeeded,
        failed,
        results,
    };
}
/**
 * Output batch operation result
 */
export function outputBatchResult(result, options) {
    if (isJSONMode(options)) {
        outputJSON(result);
    }
    else {
        console.log(`Completed: ${result.succeeded}/${result.totalItems} succeeded, ${result.failed}/${result.totalItems} failed`);
        if (result.failed > 0) {
            console.log('\nFailed items:');
            for (const item of result.results.filter((r) => !r.success)) {
                console.log(`  ${item.item}: ${item.error?.message || 'Unknown error'}`);
            }
        }
    }
}
/**
 * Output validation result
 */
export function outputValidation(result, options) {
    if (isJSONMode(options) || options.validate) {
        outputJSON(result);
    }
    else {
        if (result.valid) {
            console.log('✓ Validation passed');
        }
        else {
            console.log('✗ Validation failed');
            if (result.errors) {
                for (const err of result.errors) {
                    console.log(`  ${err.field}: ${err.message}`);
                }
            }
        }
    }
}
//# sourceMappingURL=output.js.map