/**
 * Enhanced Tool Results Visualization
 *
 * Better display for tool execution results:
 * - Collapsible tool results
 * - Smart truncation with preview
 * - Size indicators (KB/MB)
 * - Copy to clipboard support
 * - Visual feedback for success/error
 */
import React, { useState, useMemo } from 'react';
import { Box, Text } from 'ink';
import { useTheme } from '../context/theme-context.js';
/**
 * Format file size in human-readable format
 */
function formatSize(bytes) {
    if (bytes < 1024)
        return `${bytes}B`;
    if (bytes < 1024 * 1024)
        return `${(bytes / 1024).toFixed(1)}KB`;
    if (bytes < 1024 * 1024 * 1024)
        return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
    return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;
}
/**
 * Format duration
 */
function formatDuration(ms) {
    if (ms < 1000)
        return `${ms}ms`;
    return `${(ms / 1000).toFixed(2)}s`;
}
/**
 * Truncate content intelligently
 */
function truncateContent(content, maxLines) {
    const lines = content.split('\n');
    const totalLines = lines.length;
    if (totalLines <= maxLines) {
        return {
            preview: content,
            isTruncated: false,
            totalLines,
            hiddenLines: 0,
        };
    }
    const previewLines = lines.slice(0, maxLines);
    return {
        preview: previewLines.join('\n'),
        isTruncated: true,
        totalLines,
        hiddenLines: totalLines - maxLines,
    };
}
/**
 * Enhanced Tool Result Component
 */
export function EnhancedToolResult({ result, defaultCollapsed = true, previewLines = 10, showMetadata = true, }) {
    const { colors } = useTheme();
    const [isCollapsed, setIsCollapsed] = useState(defaultCollapsed);
    // Calculate metadata
    const metadata = useMemo(() => {
        const contentBytes = new TextEncoder().encode(result.content).length;
        const { preview, isTruncated, totalLines, hiddenLines } = truncateContent(result.content, previewLines);
        return {
            size: formatSize(contentBytes),
            sizeBytes: contentBytes,
            preview,
            isTruncated,
            totalLines,
            hiddenLines,
            duration: result.duration ? formatDuration(result.duration) : undefined,
        };
    }, [result.content, result.duration, previewLines]);
    // Determine status color
    const statusColor = result.success ? colors.success : colors.error;
    const statusIcon = result.success ? '✓' : '✗';
    // Toggle collapse (used via click handler)
    const _toggleCollapse = () => {
        if (metadata.isTruncated || result.content.length > 500) {
            setIsCollapsed((prev) => !prev);
        }
    };
    // Render content based on collapse state
    const displayContent = isCollapsed ? metadata.preview : result.content;
    const contentLines = displayContent.split('\n');
    return (React.createElement(Box, { flexDirection: "column", borderStyle: "round", borderColor: statusColor, paddingX: 1, marginY: 1 },
        React.createElement(Box, { justifyContent: "space-between" },
            React.createElement(Box, null,
                React.createElement(Text, { color: statusColor },
                    statusIcon,
                    " "),
                React.createElement(Text, { bold: true }, result.toolName),
                result.fileName && (React.createElement(Text, { color: colors.textMuted },
                    " \u2022 ",
                    result.fileName))),
            showMetadata && (React.createElement(Box, null,
                React.createElement(Text, { dimColor: true }, metadata.size),
                metadata.duration && (React.createElement(React.Fragment, null,
                    React.createElement(Text, { dimColor: true }, " \u2022 "),
                    React.createElement(Text, { dimColor: true }, metadata.duration))),
                React.createElement(Text, { dimColor: true }, " \u2022 "),
                React.createElement(Text, { dimColor: true },
                    metadata.totalLines,
                    " line",
                    metadata.totalLines !== 1 ? 's' : '')))),
        !result.success && result.error && (React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { color: colors.error },
                "\u23BF Error: ",
                result.error))),
        result.success && (React.createElement(Box, { flexDirection: "column", marginTop: 1 },
            React.createElement(Box, { flexDirection: "column" }, contentLines.map((line, index) => (React.createElement(Text, { key: index, dimColor: isCollapsed }, line)))),
            metadata.isTruncated && isCollapsed && (React.createElement(Box, { marginTop: 1 },
                React.createElement(Text, { color: colors.warning },
                    "\u00B7\u00B7\u00B7 ",
                    metadata.hiddenLines,
                    " more line",
                    metadata.hiddenLines !== 1 ? 's' : '',
                    " hidden"),
                React.createElement(Text, { dimColor: true }, " (click or press Enter to expand)"))),
            (metadata.isTruncated || metadata.sizeBytes > 500) && (React.createElement(Box, { marginTop: 1, borderStyle: "single", borderColor: colors.border, paddingX: 1 },
                React.createElement(Text, { dimColor: true },
                    "Press ",
                    React.createElement(Text, { bold: true, color: colors.accent }, "Space"),
                    " or ",
                    React.createElement(Text, { bold: true, color: colors.accent }, "Enter"),
                    " to ",
                    isCollapsed ? 'expand' : 'collapse'))))),
        React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { dimColor: true }, result.timestamp.toLocaleTimeString()))));
}
export function ToolResultsList({ results, maxResults = 10, groupByTool = false, }) {
    const { colors } = useTheme();
    // Group results by tool if requested
    const groupedResults = useMemo(() => {
        if (!groupByTool) {
            return { ungrouped: results.slice(0, maxResults) };
        }
        const groups = {};
        results.slice(0, maxResults).forEach((result) => {
            if (!groups[result.toolName]) {
                groups[result.toolName] = [];
            }
            groups[result.toolName].push(result);
        });
        return groups;
    }, [results, maxResults, groupByTool]);
    const hiddenCount = Math.max(0, results.length - maxResults);
    return (React.createElement(Box, { flexDirection: "column" },
        React.createElement(Box, { marginBottom: 1 },
            React.createElement(Text, { bold: true, color: colors.primary }, "\uD83D\uDD27 Tool Execution Results"),
            React.createElement(Text, { dimColor: true },
                " (",
                results.length,
                " total)")),
        Object.entries(groupedResults).map(([groupName, groupResults]) => (React.createElement(Box, { key: groupName, flexDirection: "column" },
            groupByTool && groupName !== 'ungrouped' && (React.createElement(Box, { marginBottom: 1 },
                React.createElement(Text, { bold: true, color: colors.secondary }, groupName),
                React.createElement(Text, { dimColor: true },
                    " (",
                    groupResults.length,
                    ")"))),
            groupResults.map((result, index) => (React.createElement(EnhancedToolResult, { key: `${result.toolName}-${result.timestamp.getTime()}-${index}`, result: result })))))),
        hiddenCount > 0 && (React.createElement(Box, { marginTop: 1 },
            React.createElement(Text, { dimColor: true },
                "... ",
                hiddenCount,
                " older result",
                hiddenCount !== 1 ? 's' : '',
                " hidden")))));
}
export function ToolExecutionSummary({ results }) {
    const { colors } = useTheme();
    const summary = useMemo(() => {
        const total = results.length;
        const successful = results.filter((r) => r.success).length;
        const failed = total - successful;
        const successRate = total > 0 ? (successful / total) * 100 : 0;
        // Calculate average duration
        const durationsAvailable = results.filter((r) => r.duration !== undefined);
        const avgDuration = durationsAvailable.length > 0
            ? durationsAvailable.reduce((sum, r) => sum + (r.duration || 0), 0) / durationsAvailable.length
            : 0;
        // Tool usage breakdown
        const toolCounts = {};
        results.forEach((r) => {
            toolCounts[r.toolName] = (toolCounts[r.toolName] || 0) + 1;
        });
        const mostUsedTool = Object.entries(toolCounts).sort((a, b) => b[1] - a[1])[0];
        return {
            total,
            successful,
            failed,
            successRate,
            avgDuration,
            mostUsedTool: mostUsedTool ? mostUsedTool[0] : 'N/A',
            mostUsedCount: mostUsedTool ? mostUsedTool[1] : 0,
        };
    }, [results]);
    return (React.createElement(Box, { flexDirection: "column", borderStyle: "single", borderColor: colors.border, paddingX: 1 },
        React.createElement(Box, { marginBottom: 1 },
            React.createElement(Text, { bold: true, color: colors.primary }, "\uD83D\uDCCA Tool Execution Summary")),
        React.createElement(Box, null,
            React.createElement(Text, null, "Total executions: "),
            React.createElement(Text, { bold: true }, summary.total)),
        React.createElement(Box, null,
            React.createElement(Text, null, "Success rate: "),
            React.createElement(Text, { bold: true, color: colors.success },
                summary.successRate.toFixed(1),
                "%"),
            React.createElement(Text, { dimColor: true },
                " (",
                summary.successful,
                " \u2713 / ",
                summary.failed,
                " \u2717)")),
        summary.avgDuration > 0 && (React.createElement(Box, null,
            React.createElement(Text, null, "Avg duration: "),
            React.createElement(Text, { bold: true }, formatDuration(summary.avgDuration)))),
        React.createElement(Box, null,
            React.createElement(Text, null, "Most used: "),
            React.createElement(Text, { bold: true, color: colors.accent }, summary.mostUsedTool),
            React.createElement(Text, { dimColor: true },
                " (",
                summary.mostUsedCount,
                "x)"))));
}
export default EnhancedToolResult;
//# sourceMappingURL=EnhancedToolResults.js.map