/**
 * src/agent/compaction.ts
 *
 * (Audit C3) Conversation compaction. When a chat session goes long, the
 * naive last-10-messages window drops everything earlier. OpenClaw's
 * session-memory hook handles this by summarizing on /new or /reset.
 * Muassis runs compaction continuously: at 20+ turns, summarize the
 * older half into a single "session summary" message and persist it
 * to customer memory so future turns can recall it via getCustomerMemory.
 */
import { createChildLogger } from '../utils/logger.js';
import { callWithFailover } from '../models/failover.js';
const log = createChildLogger('agent:compaction');
const COMPACT_TRIGGER_AT = 20;
const KEEP_RECENT = 6;
export function shouldCompact(messageCount) {
    return messageCount >= COMPACT_TRIGGER_AT;
}
/**
 * Summarize the older portion of the conversation. The result + the
 * most-recent KEEP_RECENT messages become the brain's history window
 * for this turn.
 */
export async function compactConversationHistory(tenantId, customerId, history) {
    if (history.length < COMPACT_TRIGGER_AT) {
        return { summary: '', recent: history, compactedCount: 0 };
    }
    // Keep the last KEEP_RECENT messages verbatim. Summarize everything older.
    const olderCount = history.length - KEEP_RECENT;
    const older = history.slice(0, olderCount);
    const recent = history.slice(-KEEP_RECENT);
    const transcript = older
        .map((m) => `${m.role === 'user' ? 'العميل' : 'المؤسس'}: ${m.content}`)
        .join('\n');
    const messages = [
        {
            role: 'system',
            content: 'لخّص هذه المحادثة بين العميل والمؤسس في فقرة قصيرة (8-12 سطر) تركّز على:\n' +
                '1. ما طلبه العميل (الموضوعات الرئيسية)\n' +
                '2. ما قرر/التزم/وعد به المؤسس\n' +
                '3. القرارات المعلّقة أو الأسئلة المفتوحة\n' +
                '4. أرقام/مبالغ/أسماء/تواريخ مهمة (للذاكرة الدقيقة)\n\n' +
                'اكتب بنفس لغة المحادثة. لا تضف اقتباسات حرفية. لا تضف عبارات مثل "هذا ملخص". ابدأ مباشرة.',
        },
        {
            role: 'user',
            content: `محادثة بـ ${older.length} رسالة:\n\n${transcript}`,
        },
    ];
    let summary = '';
    try {
        const result = await callWithFailover('flash', messages, { temperature: 0.2, maxTokens: 600 }, tenantId);
        summary = result.content?.trim() || '';
    }
    catch (err) {
        log.warn({ tenantId, customerId, err: err.message }, 'compaction LLM call failed — keeping full history');
        return { summary: '', recent: history, compactedCount: 0 };
    }
    if (!summary) {
        return { summary: '', recent: history, compactedCount: 0 };
    }
    // Persist the summary into customer memory so the next time we can include
    // it as a "previously in this thread" context block.
    try {
        const { updateCustomerMemory } = await import('./memory.js');
        const stamp = new Date().toISOString().split('T')[0];
        await updateCustomerMemory(tenantId, customerId, `## ملخّص الجلسة (${stamp}, ${older.length} رسالة)\n${summary}`, undefined);
    }
    catch (err) {
        log.debug({ err: err.message }, 'failed to persist compaction summary');
    }
    log.info({ tenantId, customerId, originalCount: history.length, kept: recent.length, summarized: older.length }, 'conversation compacted');
    return { summary, recent, compactedCount: older.length };
}
//# sourceMappingURL=compaction.js.map