"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toMynahIcon = toMynahIcon;
exports.toMynahButtons = toMynahButtons;
exports.toMynahHeader = toMynahHeader;
exports.toMynahFileList = toMynahFileList;
exports.toDetailsWithoutIcon = toDetailsWithoutIcon;
exports.toMynahContextCommand = toMynahContextCommand;
exports.contextListToHeader = contextListToHeader;
exports.createMcpToolSummaryItem = createMcpToolSummaryItem;
exports.prepareChatItemFromMessage = prepareChatItemFromMessage;
exports.chatMessageToChatItem = chatMessageToChatItem;
const mynah_ui_1 = require("@aws/mynah-ui");
const constants_1 = require("./constants");
function toMynahIcon(icon) {
    return icon && Object.values(mynah_ui_1.MynahIcons).includes(icon) ? icon : undefined;
}
function toMynahButtons(buttons) {
    return buttons?.map(button => ({ ...button, icon: toMynahIcon(button.icon) }));
}
function toMynahHeader(header) {
    if (!header)
        return undefined;
    // Create a new object with only the properties that are compatible with ChatItemContent['header']
    const { summary, ...headerWithoutSummary } = header;
    return {
        ...headerWithoutSummary,
        icon: toMynahIcon(header.icon),
        buttons: toMynahButtons(header.buttons),
        status: header.status ? { ...header.status, icon: toMynahIcon(header.status.icon) } : undefined,
        summary: header.summary,
    };
}
function toMynahFileList(fileList) {
    if (!fileList)
        return undefined;
    const fileListTree = {
        fileTreeTitle: '',
        filePaths: fileList.filePaths?.map(file => file),
        rootFolderTitle: fileList.rootFolderTitle ?? 'Context',
        flatList: true,
        hideFileCount: true,
        collapsed: true,
        details: Object.fromEntries(Object.entries(fileList.details || {}).map(([filePath, fileDetails]) => [
            filePath,
            {
                label: fileDetails.lineRanges
                    ?.map(range => range.first === -1 || range.second === -1 ? '' : `line ${range.first} - ${range.second}`)
                    .join(', ') || '',
                description: fileDetails.description,
                visibleName: filePath.split('/').filter(Boolean).pop() || filePath.split('/').slice(-2, -1)[0] || filePath,
                clickable: true,
                data: {
                    fullPath: fileDetails.fullPath || '',
                },
            },
        ])),
    };
    return fileListTree;
}
function toDetailsWithoutIcon(details) {
    return Object.fromEntries(Object.entries(details || {}).map(([filePath, fileDetails]) => [filePath, { ...fileDetails, icon: null }]));
}
function toMynahContextCommand(feature) {
    if (!feature || !feature.value.stringValue) {
        return {};
    }
    return {
        command: feature.value.stringValue,
        id: feature.value.stringValue,
        description: feature.variation,
    };
}
/**
 * Converts a contextList from ChatResult to a header format for ChatItem
 */
function contextListToHeader(contextList) {
    if (contextList === undefined) {
        return undefined;
    }
    return {
        fileList: {
            fileTreeTitle: '',
            filePaths: contextList.filePaths?.map(file => file),
            rootFolderTitle: contextList.rootFolderTitle ?? 'Context',
            flatList: true,
            collapsed: true,
            hideFileCount: true,
            details: Object.fromEntries(Object.entries(contextList.details || {}).map(([filePath, fileDetails]) => [
                filePath,
                {
                    label: fileDetails.lineRanges
                        ?.map(range => range.first === -1 || range.second === -1
                        ? ''
                        : `line ${range.first} - ${range.second}`)
                        .join(', ') || '',
                    description: fileDetails.description,
                    clickable: true,
                    data: {
                        fullPath: fileDetails.fullPath || '',
                    },
                },
            ])),
        },
    };
}
/**
 * Creates a properly formatted chat item for MCP tool summary with accordion view
 */
function createMcpToolSummaryItem(message, isPartialResult) {
    return {
        type: mynah_ui_1.ChatItemType.ANSWER,
        messageId: message.messageId,
        summary: {
            content: message.summary?.content
                ? {
                    padding: false,
                    wrapCodes: true,
                    header: message.summary.content.header
                        ? {
                            icon: message.summary.content.header.icon,
                            body: message.summary.content.header.body,
                            buttons: message.summary.content?.header?.buttons,
                            status: isPartialResult ? message.summary.content?.header?.status : undefined,
                            fileList: undefined,
                        }
                        : undefined,
                }
                : undefined,
            collapsedContent: message.summary?.collapsedContent?.map(item => ({
                body: item.body,
                header: item.header
                    ? {
                        body: item.header.body,
                    }
                    : undefined,
                fullWidth: true,
                padding: false,
                muted: false,
                wrapCodes: item.header?.body === 'Parameters' ? true : false,
                codeBlockActions: { copy: null, 'insert-to-cursor': null },
            })) || [],
        },
    };
}
/**
 * Prepares a ChatItem from a ChatMessage with proper formatting for tool cards,
 * file lists, MCP summaries, etc.
 */
function prepareChatItemFromMessage(message, isPairProgrammingMode, isPartialResult) {
    const contextHeader = contextListToHeader(message.contextList);
    const header = contextHeader || toMynahHeader(message.header); // Is this mutually exclusive?
    const fileList = toMynahFileList(message.fileList);
    let processedHeader = header;
    if (message.type === 'tool') {
        // Handle MCP tool summary with accordion view
        if (message.summary) {
            return createMcpToolSummaryItem(message, isPartialResult);
        }
        processedHeader = { ...header };
        if (header?.buttons) {
            processedHeader.buttons = header.buttons.map(button => ({
                ...button,
                status: button.status ?? 'clear',
            }));
        }
        if (header?.fileList) {
            processedHeader.fileList = {
                ...header.fileList,
                fileTreeTitle: '',
                hideFileCount: true,
                details: toDetailsWithoutIcon(header.fileList.details),
                renderAsPills: !header.fileList.details ||
                    (Object.values(header.fileList.details).every(detail => !detail.changes) &&
                        (!header.buttons || !header.buttons.some(button => button.id === constants_1.BUTTON_UNDO_CHANGES)) &&
                        !header.status?.icon),
            };
        }
        if (!isPartialResult) {
            if (processedHeader && !message.header?.status) {
                processedHeader.status = undefined;
            }
        }
    }
    // Check if header should be included
    const includeHeader = processedHeader &&
        ((processedHeader.buttons !== undefined &&
            processedHeader.buttons !== null &&
            processedHeader.buttons.length > 0) ||
            processedHeader.status !== undefined ||
            processedHeader.icon !== undefined ||
            processedHeader.fileList !== undefined);
    const padding = message.type === 'tool' ? (fileList ? true : message.messageId?.endsWith(constants_1.SUFFIX_PERMISSION)) : undefined;
    const processedButtons = toMynahButtons(message.buttons)?.map(button => button.id === constants_1.BUTTON_UNDO_ALL_CHANGES ? { ...button, position: 'outside' } : button);
    // Adding this conditional check to show the stop message in the center.
    const contentHorizontalAlignment = undefined;
    // If message.header?.status?.text is Stopped or Rejected or Ignored etc.. card should be in disabled state.
    const shouldMute = message.header?.status?.text !== undefined &&
        ['Stopped', 'Rejected', 'Ignored', 'Failed', 'Error'].includes(message.header.status.text);
    return {
        body: message.body,
        header: includeHeader ? processedHeader : undefined,
        buttons: processedButtons,
        fileList,
        // file diffs in the header need space
        fullWidth: message.type === 'tool' && includeHeader ? true : undefined,
        padding,
        contentHorizontalAlignment,
        wrapCodes: message.type === 'tool',
        codeBlockActions: message.type === 'tool'
            ? { 'insert-to-cursor': null, copy: null }
            : isPairProgrammingMode
                ? { 'insert-to-cursor': null }
                : undefined,
        ...(shouldMute ? { muted: true } : {}),
    };
}
/**
 * Converts a ChatMessage (e.g., from history restoration) to a ChatItem for MynahUI rendering.
 * This applies the same transformations as prepareChatItemFromMessage to ensure tool cards,
 * file lists, MCP summaries, etc. render correctly.
 */
function chatMessageToChatItem(message, isPairProgrammingMode = false) {
    // Convert message type to ChatItemType
    const typeMap = {
        prompt: mynah_ui_1.ChatItemType.PROMPT,
        answer: mynah_ui_1.ChatItemType.ANSWER,
        'answer-stream': mynah_ui_1.ChatItemType.ANSWER_STREAM,
        directive: mynah_ui_1.ChatItemType.DIRECTIVE,
        tool: mynah_ui_1.ChatItemType.ANSWER,
        'system-prompt': mynah_ui_1.ChatItemType.SYSTEM_PROMPT,
    };
    const msgType = message.type ?? 'answer';
    const chatItemType = typeMap[msgType] ?? mynah_ui_1.ChatItemType.ANSWER;
    // Use prepareChatItemFromMessage for consistent rendering
    const preparedItem = prepareChatItemFromMessage(message, isPairProgrammingMode, false);
    return {
        type: chatItemType,
        messageId: message.messageId,
        relatedContent: message.relatedContent,
        codeReference: message.codeReference,
        canBeVoted: message.canBeVoted,
        followUp: message.followUp,
        ...preparedItem,
    };
}
//# sourceMappingURL=utils.js.map