/**
 * Agent Context Facade
 *
 * Encapsulates all context and memory management operations for agents.
 * This facade handles:
 * - Token counting and context window management
 * - Memory system (cross-session persistence)
 * - Context statistics and compression
 */
import { getEnhancedMemory } from '../../memory/index.js';
import { getErrorMessage } from '../../errors/index.js';
import { logger } from '../../utils/logger.js';
/**
 * Facade for context and memory management in agents.
 *
 * Responsibilities:
 * - Token counting and context window monitoring
 * - Memory storage, retrieval, and summarization
 * - Context statistics and configuration
 */
export class AgentContextFacade {
    tokenCounter;
    contextManager;
    getSessionId;
    _memory = null;
    memoryEnabled = true;
    constructor(deps) {
        this.tokenCounter = deps.tokenCounter;
        this.contextManager = deps.contextManager;
        this.getSessionId = deps.getSessionId;
    }
    // ============================================================================
    // Memory System (Lazy-loaded)
    // ============================================================================
    /**
     * Get or initialize the memory system
     */
    get memory() {
        if (!this._memory) {
            this._memory = getEnhancedMemory({
                enabled: this.memoryEnabled,
                embeddingEnabled: true,
                useSQLite: true,
                maxMemories: 10000,
                autoSummarize: true,
            });
            const cwd = process.cwd();
            if (cwd) {
                this._memory.setProjectContext(cwd).catch(err => {
                    logger.warn('Failed to set project context for memory', { error: getErrorMessage(err) });
                });
            }
        }
        return this._memory;
    }
    // ============================================================================
    // Context Management
    // ============================================================================
    /**
     * Get context statistics for the current messages
     */
    getStats(messages) {
        return this.contextManager.getStats(messages);
    }
    /**
     * Format context statistics as a human-readable string
     */
    formatStats(messages) {
        const stats = this.contextManager.getStats(messages);
        const status = stats.isCritical ? '🔴 Critical' : stats.isNearLimit ? '🟡 Warning' : '🟢 Normal';
        return `Context: ${stats.totalTokens}/${stats.maxTokens} tokens (${stats.usagePercent.toFixed(1)}%) ${status} | Messages: ${stats.messageCount} | Summaries: ${stats.summarizedSessions}`;
    }
    /**
     * Update context manager configuration
     */
    updateConfig(config) {
        this.contextManager.updateConfig(config);
    }
    /**
     * Get the context manager instance (for advanced operations)
     */
    getContextManager() {
        return this.contextManager;
    }
    /**
     * Get the token counter instance (for advanced operations)
     */
    getTokenCounter() {
        return this.tokenCounter;
    }
    // ============================================================================
    // Memory Operations
    // ============================================================================
    /**
     * Store a memory entry
     */
    async remember(type, content, options = {}) {
        if (!this.memoryEnabled) {
            throw new Error('Memory system is disabled');
        }
        return this.memory.store({ type, content, ...options });
    }
    /**
     * Recall memories matching the query
     */
    async recall(query, options = {}) {
        if (!this.memoryEnabled)
            return [];
        return this.memory.recall({ query, ...options });
    }
    /**
     * Build context string from relevant memories
     */
    async getMemoryContext(query) {
        if (!this.memoryEnabled)
            return '';
        return this.memory.buildContext({
            query,
            includePreferences: true,
            includeProject: true,
            includeRecentSummaries: true,
        });
    }
    /**
     * Store a conversation summary for long-term memory
     */
    async storeConversationSummary(summary, topics, decisions, messageCount) {
        if (!this.memoryEnabled)
            return;
        const sessionId = this.getSessionId() || `session-${Date.now()}`;
        await this.memory.storeSummary({
            sessionId,
            summary,
            topics,
            decisions,
            messageCount,
        });
    }
    // ============================================================================
    // Memory Configuration
    // ============================================================================
    /**
     * Enable or disable the memory system
     */
    setMemoryEnabled(enabled) {
        this.memoryEnabled = enabled;
        if (!enabled && this._memory) {
            this._memory.dispose();
            this._memory = null;
        }
    }
    /**
     * Check if memory is enabled
     */
    isMemoryEnabled() {
        return this.memoryEnabled;
    }
    /**
     * Get memory statistics
     */
    getMemoryStats() {
        if (!this.memoryEnabled || !this._memory)
            return null;
        return this.memory.getStats();
    }
    /**
     * Format memory status as a human-readable string
     */
    formatMemoryStatus() {
        if (!this.memoryEnabled)
            return '🧠 Memory: Disabled';
        if (!this._memory)
            return '🧠 Memory: Not initialized';
        return this.memory.formatStatus();
    }
    // ============================================================================
    // Lifecycle
    // ============================================================================
    /**
     * Dispose of all resources
     */
    dispose() {
        if (this.tokenCounter)
            this.tokenCounter.dispose();
        if (this.contextManager)
            this.contextManager.dispose();
        if (this._memory) {
            this._memory.dispose();
            this._memory = null;
        }
    }
}
//# sourceMappingURL=agent-context-facade.js.map