import { buildUserContentSegments } from './attachments';
/**
 * Transforms chat history into both modern agent items and legacy fallbacks for compatibility layers.
 */
export const buildThreadVariants = (history) => {
    const modern = [];
    const legacy = [];
    for (const message of history) {
        if (message.role === 'user') {
            const segments = buildUserContentSegments(message);
            const legacyContent = segments.join('\n\n').trim() || '(user sent attachments without additional text)';
            legacy.push({ role: 'user', content: legacyContent });
            const contentItems = segments.map((text) => ({
                type: 'input_text',
                text
            }));
            modern.push({
                role: 'user',
                type: 'message',
                content: contentItems,
                metadata: message.slashCommand ? { slashCommand: { ...message.slashCommand } } : undefined
            });
            continue;
        }
        legacy.push({ role: 'assistant', content: message.content });
        modern.push({
            role: 'assistant',
            type: 'message',
            content: [{ type: 'output_text', text: message.content }],
            status: 'completed'
        });
    }
    return { modern, legacy };
};
/**
 * Collects attachment metadata indexed by id so the agent can resolve cached files during a run.
 */
export const collectAttachmentContext = (history, cache) => {
    const context = {};
    for (const message of history) {
        for (const attachment of message.attachments ?? []) {
            const cached = cache[attachment.id];
            context[attachment.id] = {
                id: attachment.id,
                name: attachment.name,
                mimeType: attachment.mimeType,
                size: Number.isFinite(attachment.size) ? attachment.size : cached?.size ?? 0,
                url: cached?.url ?? attachment.url,
                fileId: cached?.fileId ?? attachment.fileId,
                sourceUrl: cached?.sourceUrl ?? attachment.sourceUrl
            };
        }
    }
    return context;
};
