import { logger } from '@pellux/goodvibes-sdk/platform/utils/logger';
import { compactMessages } from './context-compaction.js';
import { summarizeError } from '@pellux/goodvibes-sdk/platform/utils/error-display';
export async function compactConversation(host, registry, modelId, trigger = 'manual', provider, context) {
    if (host.getMessageCount() === 0)
        return;
    try {
        const llmMessages = host.getMessagesForLLM();
        const compactionContext = context ?? {
            messages: llmMessages,
            trigger,
            extractionModelId: modelId,
            extractionProvider: provider,
            sessionMemories: [],
            agents: [],
            wrfcChains: [],
            activePlan: null,
            lineageEntries: [],
            compactionCount: 0,
            contextWindow: 0,
        };
        const result = await compactMessages(compactionContext, registry);
        host.replaceMessagesForLLM(result.messages);
        const memoriesCount = host.getSessionMemoryStore()?.list().length ?? 0;
        const memoriesPart = memoriesCount > 0 ? `, ${memoriesCount} pinned memories` : '';
        const saved = result.tokensBeforeEstimate - result.tokensAfterEstimate;
        const savedKTokens = Math.round(saved / 1000);
        host.getSessionLineageTracker().addCompactionEntry(`${trigger} compact, saved ~${savedKTokens}K tokens${memoriesPart}.`);
        logger.info('Conversation compacted', {
            trigger,
            messagesBeforeCompaction: result.event.messagesBeforeCompaction,
            messagesAfterCompaction: result.event.messagesAfterCompaction,
            tokensBeforeEstimate: result.tokensBeforeEstimate,
            tokensAfterEstimate: result.tokensAfterEstimate,
            tokensSaved: saved,
        });
    }
    catch (err) {
        const msg = summarizeError(err);
        logger.error('Compact failed', { error: msg });
        throw err;
    }
}
