import { stringifyPromptContent } from '../../lib/promptUtils';
/**
 * Normalizes attachment metadata so downstream consumers can rely on required fields.
 */
export const sanitizeAttachment = (attachment) => {
    return {
        id: attachment.id,
        name: attachment.name,
        mimeType: attachment.mimeType,
        size: attachment.size,
        dateAdded: attachment.dateAdded ?? Date.now(),
        dataUrl: attachment.dataUrl,
        url: attachment.url,
        fileId: attachment.fileId,
        sourceUrl: attachment.sourceUrl
    };
};
/**
 * Converts a raw byte count into a human-readable size string.
 */
export const formatFileSize = (bytes) => {
    if (Number.isNaN(bytes) || bytes < 0) {
        return 'unknown size';
    }
    if (bytes < 1024) {
        return `${bytes} B`;
    }
    const kb = bytes / 1024;
    if (kb < 1024) {
        return `${kb.toFixed(1)} KB`;
    }
    const mb = kb / 1024;
    if (mb < 1024) {
        return `${mb.toFixed(1)} MB`;
    }
    const gb = mb / 1024;
    return `${gb.toFixed(1)} GB`;
};
/**
 * Builds a numbered summary describing each attachment for prompt enrichment.
 */
export const buildAttachmentSummaryText = (attachments) => {
    if (attachments.length === 0) {
        return '';
    }
    const lines = attachments.map((attachment, index) => {
        const position = index + 1;
        const details = [
            `name: ${attachment.name}`,
            `id: ${attachment.id}`,
            attachment.mimeType ? `type: ${attachment.mimeType}` : null,
            Number.isFinite(attachment.size) ? `size: ${formatFileSize(attachment.size)}` : null
        ].filter(Boolean).join(', ');
        return `${position}. ${details}`;
    });
    return lines.join('\n');
};
/**
 * Renders a human-readable summary of a slash command invocation, or null when absent.
 */
export const buildSlashCommandPromptSummary = (slashCommand) => {
    if (!slashCommand) {
        return null;
    }
    const sections = [];
    const displayTitle = slashCommand.title && slashCommand.title.trim().length > 0
        ? slashCommand.title.trim()
        : `/${slashCommand.name}`;
    const serverLabel = slashCommand.serverName?.trim();
    const header = serverLabel
        ? `Slash command: ${displayTitle} (server: ${serverLabel})`
        : `Slash command: ${displayTitle}`;
    sections.push(header);
    const argsEntries = Object.entries(slashCommand.args ?? {})
        .map(([key, value]) => [key, value?.trim?.() ?? ''])
        .filter(([, value]) => value.length > 0);
    if (argsEntries.length > 0) {
        const argLines = argsEntries.map(([key, value]) => `- ${key}: ${value}`);
        sections.push(['Arguments:', ...argLines].join('\n'));
    }
    const description = slashCommand.resolvedPrompt?.description?.trim();
    if (description) {
        sections.push(`Prompt description:\n${description}`);
    }
    const promptMessages = slashCommand.resolvedPrompt?.messages ?? [];
    if (promptMessages.length > 0) {
        const messageLines = promptMessages.map((promptMessage, index) => {
            const roleLabel = promptMessage.role?.toString?.().trim() || 'message';
            const contentText = stringifyPromptContent(promptMessage.content);
            const prefix = `${index + 1}. ${roleLabel}`;
            return contentText ? `${prefix}:\n${contentText}` : `${prefix}.`;
        });
        sections.push(['Prompt messages:', ...messageLines].join('\n'));
    }
    const summary = sections.join('\n\n').trim();
    return summary.length > 0 ? summary : null;
};
/**
 * Derives prompt content segments for a user message, including command summaries and attachments.
 */
export const buildUserContentSegments = (message) => {
    const segments = [];
    const slashCommandSummary = buildSlashCommandPromptSummary(message.slashCommand);
    if (slashCommandSummary) {
        segments.push(slashCommandSummary);
    }
    const trimmedContent = message.content.trim();
    if (trimmedContent.length > 0) {
        segments.push(message.content);
    }
    if ((message.attachments?.length ?? 0) > 0) {
        const summary = buildAttachmentSummaryText(message.attachments ?? []);
        const summaryText = [
            'Attachments referenced in this message:',
            summary,
            'Use the list_cached_files and get_cached_file tools with the attachment ids to inspect their contents.'
        ].filter(Boolean).join('\n');
        segments.push(summaryText);
    }
    if (segments.length === 0) {
        return ['(user sent attachments without additional text)'];
    }
    return segments;
};
/**
 * Compares two cached attachments for equality across the persisted fields we care about.
 */
export const attachmentsEqual = (a, b) => {
    if (!a)
        return false;
    return (a.dateAdded === b.dateAdded &&
        a.name === b.name &&
        a.mimeType === b.mimeType &&
        a.size === b.size &&
        a.dataUrl === b.dataUrl &&
        a.url === b.url &&
        a.fileId === b.fileId &&
        a.sourceUrl === b.sourceUrl);
};
