/**
 * ToolResultBlock — 工具结果块
 */

import { Box, Typography, Stack } from '@mui/material';
import { FileText } from 'lucide-react';
import type { ToolCallInfo } from '@renderer/stores/agent-store';
import { formatDuration } from '@renderer/lib/formatters';
import { toDisplayResult } from '@renderer/lib/tool-result-display';

interface ToolResultBlockProps { toolCall: ToolCallInfo; }

export function ToolResultBlock({ toolCall }: ToolResultBlockProps): React.JSX.Element {
  if (toolCall.status !== 'success' || toolCall.result == null) return <></>;
  // 渲染前剥离 dataUrl 等超大 base64 字段，避免 ~6.7MB/张的 dataUrl 进 DOM 导致渲染进程 OOM
  // store 内原始 result 不变（LLM 看图能力不受影响）
  const displayResult = toDisplayResult(toolCall.result);
  const resultStr = typeof displayResult === 'string' ? displayResult : JSON.stringify(displayResult, null, 2);

  return (
    <Box sx={{ borderRadius: 1.5, border: '1px solid', borderColor: 'divider', borderLeft: '3px solid', borderLeftColor: 'info.main', bgcolor: 'secondary.main', px: 1.5, py: 1, mb: 1, animation: 'fadeInUp 300ms ease-out' }}>
      <Stack direction="row" spacing={1} sx={{ mb: 0.5, alignItems: 'center' }}>
        <FileText size={12} style={{ color: '#22d3ee' }} />
        <Typography variant="caption" sx={{ fontWeight: 500, color: 'text.primary' }}>{toolCall.name} 结果</Typography>
        {toolCall.durationMs != null && <Typography variant="caption" sx={{ ml: 'auto', color: 'text.secondary' }}>{formatDuration(toolCall.durationMs)}</Typography>}
      </Stack>
      <Box component="pre" sx={{ fontSize: 11, borderRadius: 1, px: 1, py: 0.75, overflowX: 'auto', overflowY: 'auto', bgcolor: 'background.default', color: 'text.secondary', fontFamily: "'SF Mono',monospace", maxHeight: 300, m: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
        {resultStr}
      </Box>
    </Box>
  );
}
