import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import { Box, Text } from 'ink';
import React from 'react';
import { ErrorMessage } from '../components/message-box.js';
import ToolMessage from '../components/tool-message.js';
import { useTheme } from '../hooks/useTheme.js';
import { generateKey } from '../session/key-generator.js';
import { parseToolArguments } from '../utils/tool-args-parser.js';
/**
 * Tools that should always show expanded (full formatter) output,
 * even when compact display mode is enabled.
 */
export const ALWAYS_EXPANDED_TOOLS = new Set(['write_tasks']);
/**
 * Task tools that should render in the live area (updating in-place)
 * instead of appending to the static chat queue each time.
 */
export const LIVE_TASK_TOOLS = new Set(['write_tasks']);
/**
 * Compact tool result display - shows "⚒ toolName  description" in tool color.
 */
function CompactToolResult({ toolName, description, }) {
    const { colors } = useTheme();
    return (_jsxs(Text, { color: colors.tool, children: ['\u2692', " ", description] }));
}
/**
 * Compact tool error display - shows "\u2692 toolName failed" in error red.
 * Used in compact display mode so failures don't dump the full verbose
 * error; the model still receives the full error in conversation history,
 * so this only trims what the user sees.
 */
function CompactToolError({ toolName }) {
    const { colors } = useTheme();
    return (_jsxs(Text, { color: colors.error, children: ['\u2692', " ", toolName, " failed"] }));
}
/**
 * Generate a compact grouped description for N calls of the same tool.
 * Always uses count-based phrasing for consistency.
 */
function getGroupedCompactDescription(toolName, count) {
    const s = count === 1 ? '' : 's';
    switch (toolName) {
        case 'read_file':
            return `Read ${count} file${s}`;
        case 'write_file':
            return `Wrote ${count} file${s}`;
        case 'string_replace':
            return `Made ${count} edit${s}`;
        case 'execute_bash':
            return `Ran ${count} command${s}`;
        case 'search_file_contents':
            return `Searched for ${count} pattern${s}`;
        case 'find_files':
            return `Ran ${count} file search${count === 1 ? '' : 'es'}`;
        case 'list_directory':
            return `Listed ${count} director${count === 1 ? 'y' : 'ies'}`;
        case 'web_search':
            return `Ran ${count} web search${count === 1 ? '' : 'es'}`;
        case 'fetch_url':
            return `Fetched ${count} URL${s}`;
        case 'git_status':
        case 'git_diff':
        case 'git_log':
            return `Ran ${count} git command${s}`;
        case 'lsp_get_diagnostics':
            return `Got diagnostics ${count} time${s}`;
        case 'ask_question':
            return `Asked ${count} question${s}`;
        case 'agent':
            return `Delegated ${count} task${s} to subagent${s}`;
        default:
            return `Executed ${toolName} \u00d7 ${count}`;
    }
}
/**
 * Live display component for running compact tool counts.
 * Shows accumulated counts during execution (e.g. "⚒ Read 7 files").
 * Rendered in the live area (not Static) so it updates in-place.
 */
export function LiveCompactCounts({ counts }) {
    const { colors } = useTheme();
    return (_jsx(Box, { flexDirection: "column", marginBottom: 1, children: Object.entries(counts).map(([toolName, count]) => (_jsxs(Text, { color: colors.tool, children: ['\u2692', " ", getGroupedCompactDescription(toolName, count)] }, toolName))) }));
}
/**
 * Flush accumulated compact counts to the static chat queue.
 * Called when the conversation loop finishes to persist the summary.
 */
export function displayCompactCountsSummary(counts, addToChatQueue, options) {
    const entries = Object.entries(counts);
    if (entries.length === 0)
        return;
    // Indent the summary so it visually groups beneath its Thought header.
    // When no Thought precedes it (non-thinking models), render flat so the
    // summary doesn't look orphaned. marginBottom keeps spacing between turn
    // groups.
    const indent = options?.indent ?? true;
    addToChatQueue(_jsx(Box, { flexDirection: "column", marginLeft: indent ? 2 : 0, marginBottom: 1, children: entries.map(([toolName, count]) => (_jsx(CompactToolResult, { toolName: toolName, description: getGroupedCompactDescription(toolName, count) }, toolName))) }, generateKey('tool-compact-summary')));
}
/**
 * Display tool result with proper formatting
 * Extracted to eliminate duplication between useChatHandler and useToolHandler
 *
 * @param toolCall - The tool call that was executed
 * @param result - The result from tool execution
 * @param toolManager - The tool manager instance (for formatters)
 * @param addToChatQueue - Function to add components to chat queue
 * @param compact - When true, show one-liner instead of full formatter output
 */
export async function displayToolResult(toolCall, result, toolManager, addToChatQueue, compact) {
    // Check if this is an error result. Generic failures are prefixed "Error: ";
    // validation failures (bad arg types, failed per-tool validators) come back
    // as "⚒ Validation failed: …" — both should render as a red error so the
    // user sees the same feedback the model gets.
    const isValidationError = result.content.startsWith('⚒ Validation failed');
    const isError = result.content.startsWith('Error: ') || isValidationError;
    if (isError) {
        // Compact mode: condense failures to a short red one-liner
        // ("⚒ write_file ") instead of the full error output.
        // The model still receives the full error in conversation history,
        // so this only trims the user-facing display.
        if (compact && !ALWAYS_EXPANDED_TOOLS.has(result.name)) {
            addToChatQueue(_jsx(CompactToolError, { toolName: result.name }, generateKey(`tool-error-compact-${result.tool_call_id}`)));
            return;
        }
        // Display as error message - shown in full
        const errorMessage = isValidationError
            ? result.content
            : result.content.replace(/^Error: /, '');
        addToChatQueue(_jsx(ErrorMessage, { message: errorMessage, hideBox: true }, generateKey(`tool-error-${result.tool_call_id}`)));
        return;
    }
    // Compact mode: show count-based one-liner instead of full formatter output
    // (skip for tools that should always show expanded output)
    if (compact && !ALWAYS_EXPANDED_TOOLS.has(result.name)) {
        const description = getGroupedCompactDescription(result.name, 1);
        addToChatQueue(_jsx(CompactToolResult, { toolName: result.name, description: description }, generateKey(`tool-compact-${result.tool_call_id}`)));
        return;
    }
    if (toolManager) {
        const formatter = toolManager.getToolFormatter(result.name);
        if (formatter) {
            try {
                const parsedArgs = parseToolArguments(toolCall.function.arguments);
                const formattedResult = await formatter(parsedArgs, result.content);
                if (React.isValidElement(formattedResult)) {
                    addToChatQueue(React.cloneElement(formattedResult, {
                        key: generateKey(`tool-result-${result.tool_call_id}`),
                    }));
                }
                else {
                    addToChatQueue(_jsx(ToolMessage, { title: `⚒ ${result.name}`, message: String(formattedResult), hideBox: true }, generateKey(`tool-result-${result.tool_call_id}`)));
                }
            }
            catch {
                // If formatter fails, show raw result
                addToChatQueue(_jsx(ToolMessage, { title: `⚒ ${result.name}`, message: result.content, hideBox: true }, generateKey(`tool-result-${result.tool_call_id}`)));
            }
        }
        else {
            // No formatter, show raw result
            addToChatQueue(_jsx(ToolMessage, { title: `⚒ ${result.name}`, message: result.content, hideBox: true }, generateKey(`tool-result-${result.tool_call_id}`)));
        }
    }
}
//# sourceMappingURL=tool-result-display.js.map