import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Sparkles, Loader2, GitBranch, Diff, GitCommit, Check, Terminal, FileText, FileEdit, Search, FolderTree, List, AlertCircle, XOctagon, Brain, Database, } from 'lucide-react';
import { Fragment, memo, } from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { ToolApprovalCard } from './ToolApprovalCard';
import { ToolResultRenderer, ReasoningRenderer, } from './renderers';
import { CopyButton } from './renderers/shared';
function getToolCallPayload(part) {
    const fromJson = part.contentJson;
    if (fromJson && typeof fromJson === 'object') {
        return fromJson;
    }
    try {
        if (part.content) {
            const parsed = JSON.parse(part.content);
            if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
                return parsed;
            }
        }
    }
    catch { }
    return null;
}
function getToolCallArgs(part) {
    const payload = getToolCallPayload(part);
    if (!payload)
        return undefined;
    const args = payload.args;
    if (args && typeof args === 'object' && !Array.isArray(args)) {
        return args;
    }
    return undefined;
}
function getPrimaryCommand(args) {
    if (!args)
        return null;
    const candidates = ['cmd', 'command', 'script', 'input'];
    for (const key of candidates) {
        const value = args[key];
        if (typeof value === 'string' && value.trim().length > 0) {
            return value.trim();
        }
    }
    return null;
}
function normalizeToolTarget(toolName, args) {
    if (!args)
        return null;
    const candidates = [
        { key: 'path', match: true },
        { key: 'file', match: true },
        { key: 'target', match: true },
        { key: 'cwd', match: true },
        { key: 'query', match: true },
        { key: 'pattern', match: true },
        { key: 'glob', match: true },
        { key: 'dir', match: true },
    ];
    for (const { key } of candidates) {
        const value = args[key];
        if (typeof value === 'string' && value.trim().length > 0) {
            return { key, value: value.trim() };
        }
    }
    if (toolName === 'bash') {
        const command = args.command;
        if (typeof command === 'string' && command.trim().length > 0) {
            return { key: 'command', value: command.trim() };
        }
    }
    return null;
}
function formatArgsPreview(args, skipKey) {
    if (!args)
        return null;
    const pieces = [];
    for (const [key, value] of Object.entries(args)) {
        if (skipKey && key === skipKey)
            continue;
        if (typeof value === 'string' || typeof value === 'number') {
            const rendered = `${key}=${String(value)}`;
            pieces.push(rendered);
        }
        if (pieces.length >= 3)
            break;
    }
    if (!pieces.length)
        return null;
    const joined = pieces.join('  ');
    return joined.length > 120 ? `${joined.slice(0, 117)}…` : joined;
}
export const MessagePartItem = memo(function MessagePartItem({ part, showLine, isLastToolCall, isLastProgressUpdate, onNavigateToSession, compact, pendingApproval, onApprove, onReject, sessionId, onRetry, }) {
    // Show tool_call if it's the last one OR if it has a pending approval
    if (part.type === 'tool_call' && !isLastToolCall && !pendingApproval) {
        return null;
    }
    if (part.type === 'tool_result' &&
        part.toolName === 'progress_update' &&
        !isLastProgressUpdate) {
        return null;
    }
    if (part.type === 'text') {
        const data = part.contentJson || part.content;
        let content = '';
        if (data && typeof data === 'object' && 'text' in data) {
            content = String(data.text);
        }
        else if (typeof data === 'string') {
            content = data;
        }
        if (!content || !content.trim()) {
            return null;
        }
    }
    if (part.type === 'reasoning') {
        const data = part.contentJson || part.content;
        let content = '';
        if (data && typeof data === 'object' && 'text' in data) {
            content = String(data.text);
        }
        else if (typeof data === 'string') {
            content = data;
        }
        if (!content || !content.trim()) {
            return null;
        }
    }
    const isToolMessage = part.type === 'tool_call' || part.type === 'tool_result';
    const contentClasses = ['flex-1', 'min-w-0', 'max-w-full'];
    if (isToolMessage || part.type === 'reasoning') {
        contentClasses.push('pt-1');
    }
    else if (part.type === 'error') {
        contentClasses.push('pt-0.5');
    }
    else if (part.type === 'text') {
        contentClasses.push('pt-0');
        contentClasses.push('-mt-0.5');
    }
    else {
        contentClasses.push('pt-0');
    }
    const contentClassName = contentClasses.join(' ');
    const renderIcon = () => {
        if (part.type === 'reasoning') {
            return (_jsx(Brain, { className: "h-4 w-4 text-indigo-600 dark:text-indigo-300" }));
        }
        if (part.type === 'tool_call') {
            return (_jsx(Loader2, { className: "h-4 w-4 text-amber-600 dark:text-amber-300 animate-spin" }));
        }
        if (part.type === 'error') {
            const payload = getToolCallPayload(part);
            const isAborted = payload?.isAborted === true;
            return isAborted ? (_jsx(XOctagon, { className: "h-4 w-4 text-amber-600 dark:text-amber-400" })) : (_jsx(AlertCircle, { className: "h-4 w-4 text-red-600 dark:text-red-400" }));
        }
        if (part.type === 'tool_result') {
            const toolName = part.toolName || '';
            if (toolName === 'read')
                return (_jsx(FileText, { className: "h-4 w-4 text-blue-600 dark:text-blue-300" }));
            if (toolName === 'write')
                return (_jsx(FileEdit, { className: "h-4 w-4 text-emerald-600 dark:text-emerald-300" }));
            if (toolName === 'edit')
                return (_jsx(FileEdit, { className: "h-4 w-4 text-purple-600 dark:text-purple-300" }));
            if (toolName === 'ls')
                return _jsx(List, { className: "h-4 w-4 text-cyan-600 dark:text-cyan-300" });
            if (toolName === 'tree')
                return (_jsx(FolderTree, { className: "h-4 w-4 text-cyan-600 dark:text-cyan-300" }));
            if (toolName === 'bash')
                return _jsx(Terminal, { className: "h-4 w-4 text-muted-foreground" });
            if (toolName === 'ripgrep' ||
                toolName === 'grep' ||
                toolName === 'glob')
                return (_jsx(Search, { className: "h-4 w-4 text-amber-600 dark:text-amber-300" }));
            if (toolName === 'apply_patch')
                return (_jsx(Diff, { className: "h-4 w-4 text-purple-600 dark:text-purple-300" }));
            if (toolName === 'git_status')
                return (_jsx(GitBranch, { className: "h-4 w-4 text-blue-600 dark:text-blue-300" }));
            if (toolName === 'git_diff')
                return (_jsx(Diff, { className: "h-4 w-4 text-purple-600 dark:text-purple-300" }));
            if (toolName === 'git_commit')
                return (_jsx(GitCommit, { className: "h-4 w-4 text-emerald-600 dark:text-emerald-300" }));
            if (toolName === 'finish')
                return (_jsx(Check, { className: "h-4 w-4 text-emerald-600 dark:text-emerald-300" }));
            if (toolName === 'query_sessions' ||
                toolName === 'query_messages' ||
                toolName === 'search_history' ||
                toolName === 'get_session_context' ||
                toolName === 'get_parent_session')
                return (_jsx(Database, { className: "h-4 w-4 text-teal-600 dark:text-teal-300" }));
            return _jsx(Terminal, { className: "h-4 w-4 text-muted-foreground" });
        }
        return (_jsx(Sparkles, { className: "h-4 w-4 text-violet-600 dark:text-violet-300" }));
    };
    const renderToolResult = () => {
        const toolName = part.toolName || '';
        let contentJson;
        try {
            if (part.contentJson && typeof part.contentJson === 'object') {
                contentJson = part.contentJson;
            }
            else if (typeof part.content === 'string') {
                contentJson = JSON.parse(part.content);
            }
            else {
                contentJson = {};
            }
        }
        catch {
            contentJson = { result: part.content };
        }
        return (_jsx(ToolResultRenderer, { toolName: toolName, contentJson: contentJson, toolDurationMs: part.toolDurationMs, debug: false, onNavigateToSession: onNavigateToSession, compact: compact }));
    };
    const renderContent = () => {
        if (part.type === 'reasoning') {
            return _jsx(ReasoningRenderer, { part: part });
        }
        if (part.type === 'text') {
            let content = '';
            const data = part.contentJson || part.content;
            if (data && typeof data === 'object' && 'text' in data) {
                content = String(data.text);
            }
            else if (typeof data === 'string') {
                content = data;
            }
            else if (data) {
                content = JSON.stringify(data, null, 2);
            }
            return (_jsxs("div", { className: "relative group", children: [_jsx("div", { className: "absolute -top-1 right-0 opacity-0 group-hover:opacity-100 transition-opacity z-10", children: _jsx(CopyButton, { text: content, className: "bg-background/80 backdrop-blur-sm border border-border/50 shadow-sm", size: "md" }) }), _jsx("div", { className: "text-base text-foreground leading-relaxed markdown-content max-w-full overflow-hidden", children: _jsx(ReactMarkdown, { remarkPlugins: [remarkGfm], components: {
                                a: ({ href, children, ...props }) => (_jsx("a", { href: href, target: "_blank", rel: "noopener noreferrer", onClick: (e) => {
                                        if (window.self !== window.top && href) {
                                            e.preventDefault();
                                            window.parent.postMessage({
                                                type: 'agi-open-url',
                                                url: href,
                                            }, '*');
                                        }
                                    }, ...props, children: children })),
                                pre: ({ children, ...props }) => {
                                    const codeContent = (() => {
                                        if (!children)
                                            return '';
                                        const child = Array.isArray(children)
                                            ? children[0]
                                            : children;
                                        if (child &&
                                            typeof child === 'object' &&
                                            'props' in child) {
                                            const codeProps = child.props;
                                            if (typeof codeProps.children === 'string') {
                                                return codeProps.children;
                                            }
                                        }
                                        return '';
                                    })();
                                    return (_jsxs("div", { className: "relative group/code my-3", children: [_jsx("div", { className: "absolute top-2 right-2 opacity-0 group-hover/code:opacity-100 transition-opacity z-10", children: _jsx(CopyButton, { text: codeContent, className: "bg-background/80 backdrop-blur-sm border border-border/50 shadow-sm", size: "sm" }) }), _jsx("pre", { ...props, className: "overflow-x-auto", children: children })] }));
                                },
                            }, children: content }) }), content.length > 500 && (_jsx("div", { className: "absolute -bottom-1 right-0 opacity-0 group-hover:opacity-100 transition-opacity z-10", children: _jsx(CopyButton, { text: content, className: "bg-background/80 backdrop-blur-sm border border-border/50 shadow-sm", size: "md" }) }))] }));
        }
        if (part.type === 'error') {
            let contentJson;
            try {
                if (part.contentJson && typeof part.contentJson === 'object') {
                    contentJson = part.contentJson;
                }
                else if (typeof part.content === 'string') {
                    contentJson = JSON.parse(part.content);
                }
                else {
                    contentJson = {};
                }
            }
            catch {
                contentJson = {
                    message: part.content || 'Unknown error',
                };
            }
            return (_jsx(ToolResultRenderer, { toolName: "error", contentJson: contentJson, toolDurationMs: part.toolDurationMs, debug: false, compact: compact, sessionId: sessionId, onRetry: onRetry }));
        }
        if (part.type === 'tool_call') {
            const payload = getToolCallPayload(part);
            const rawToolName = part.toolName ||
                (typeof payload?.name === 'string'
                    ? payload.name
                    : 'tool');
            const toolLabel = rawToolName.replace(/_/g, ' ');
            // Use args from pending approval if available (for early approval display)
            // Fall back to part args for normal tool calls
            const partArgs = getToolCallArgs(part);
            const approvalArgs = pendingApproval?.args;
            const args = partArgs || approvalArgs;
            const primary = normalizeToolTarget(rawToolName, args);
            const argsPreview = formatArgsPreview(args, primary?.key);
            const command = rawToolName === 'bash' ? getPrimaryCommand(args) : null;
            const segments = [];
            if (command) {
                segments.push({
                    key: 'cmd',
                    node: (_jsx("code", { className: "font-mono text-foreground/90 truncate max-w-xs", children: command })),
                });
            }
            else if (primary) {
                segments.push({
                    key: 'primary',
                    node: (_jsx("code", { className: "font-mono text-foreground/85 truncate max-w-xs", children: primary.value })),
                });
            }
            if (argsPreview) {
                segments.push({
                    key: 'args',
                    node: (_jsx("span", { className: "text-muted-foreground/80 truncate max-w-xs", children: argsPreview })),
                });
            }
            // Check if this tool call has a pending approval
            const hasPendingApproval = pendingApproval && pendingApproval.callId === part.toolCallId;
            if (hasPendingApproval && onApprove && onReject) {
                return (_jsx(ToolApprovalCard, { toolName: rawToolName, args: args, pendingApproval: pendingApproval, onApprove: onApprove, onReject: onReject }));
            }
            else if (segments.length === 0) {
                segments.push({
                    key: 'running',
                    node: _jsx("span", { className: "text-muted-foreground/75", children: "running\u2026" }),
                });
            }
            const containerClasses = [
                'flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-foreground/80 max-w-full',
            ];
            if (part.ephemeral)
                containerClasses.push('animate-pulse');
            return (_jsxs("div", { className: containerClasses.join(' '), children: [_jsx("span", { className: "font-medium text-foreground", children: toolLabel }), segments.map((segment) => (_jsxs(Fragment, { children: [_jsx("span", { className: "text-muted-foreground/65", children: "\u00B7" }), segment.node] }, segment.key)))] }));
        }
        if (part.type === 'tool_result') {
            return renderToolResult();
        }
        return null;
    };
    return (_jsxs("div", { className: "flex gap-3 pb-2 relative max-w-full overflow-hidden", children: [_jsxs("div", { className: "flex-shrink-0 w-6 flex items-start justify-center relative pt-0.5", children: [_jsx("div", { className: "flex h-5 w-5 shrink-0 items-center justify-center rounded-full relative bg-background", children: renderIcon() }), showLine && (_jsx("div", { className: "absolute left-1/2 -translate-x-1/2 w-[2px] bg-border z-0", style: { top: '1.25rem', bottom: '-0.5rem' } }))] }), _jsx("div", { className: contentClassName, children: renderContent() })] }));
}, (prevProps, nextProps) => {
    return (prevProps.part.id === nextProps.part.id &&
        prevProps.part.content === nextProps.part.content &&
        prevProps.part.contentJson === nextProps.part.contentJson &&
        prevProps.part.ephemeral === nextProps.part.ephemeral &&
        prevProps.part.completedAt === nextProps.part.completedAt &&
        prevProps.showLine === nextProps.showLine &&
        prevProps.isLastToolCall === nextProps.isLastToolCall &&
        prevProps.isLastProgressUpdate === nextProps.isLastProgressUpdate &&
        prevProps.onNavigateToSession === nextProps.onNavigateToSession &&
        prevProps.pendingApproval?.callId === nextProps.pendingApproval?.callId &&
        prevProps.onApprove === nextProps.onApprove &&
        prevProps.onReject === nextProps.onReject);
});
//# sourceMappingURL=MessagePartItem.js.map