/**
 * Unified Cache Manager
 *
 * Central orchestrator for all caching subsystems.
 * Provides:
 * - Unified API for all cache operations
 * - Global statistics and monitoring
 * - Coordinated invalidation across caches
 * - Performance monitoring and optimization
 * - Memory pressure handling
 *
 * Based on research showing 60-70% reduction in expensive operations
 * through intelligent caching.
 */
import { EventEmitter } from 'events';
import { LLMResponseCache, LLMCacheStats } from './llm-response-cache.js';
import { FileContentCache, FileCacheStats } from './file-content-cache.js';
import { EmbeddingCache, EmbeddingCacheStats } from './embedding-cache.js';
import { SearchResultsCache, SearchCacheStats } from './search-results-cache.js';
import type { CodeBuddyMessage } from '../codebuddy/client.js';
export interface UnifiedCacheStats {
    llmResponse: LLMCacheStats;
    fileContent: FileCacheStats;
    embedding: EmbeddingCacheStats;
    searchResults: SearchCacheStats;
    overall: {
        totalEntries: number;
        totalHits: number;
        totalMisses: number;
        hitRate: number;
        estimatedCostSaved: number;
        estimatedTimeSaved: number;
        memoryUsageEstimate: number;
    };
}
export interface CacheManagerConfig {
    enabled: boolean;
    enableMemoryPressureHandling: boolean;
    memoryThresholdMB: number;
    /** Interval in ms for checking memory pressure (default: 30000 = 30 seconds) */
    memoryCheckIntervalMs: number;
    /** Percentage of cache entries to evict when memory pressure is detected (0-1) */
    memoryPressureEvictionRatio: number;
    /** Critical memory threshold as percentage of memoryThresholdMB (triggers aggressive eviction) */
    criticalMemoryRatio: number;
    enableMetrics: boolean;
    metricsFlushIntervalMs: number;
    /** Enable file watching for automatic invalidation */
    enableFileWatching: boolean;
    /** Debounce time for file change events (ms) */
    fileWatchDebounceMs: number;
    /** Patterns to watch (glob patterns) */
    watchPatterns: string[];
    /** Patterns to ignore */
    ignorePatterns: string[];
    /** Enable dependency tracking between files */
    enableDependencyTracking: boolean;
    /** Auto-persist on dispose */
    autoPersist: boolean;
}
export declare class CacheManager extends EventEmitter {
    private config;
    private cacheConfig;
    private llmCache;
    private fileCache;
    private embeddingCache;
    private searchCache;
    private metricsInterval;
    private memoryCheckInterval;
    private initialized;
    private lastMemoryCheck;
    private memoryPressureHistory;
    private readonly maxMemoryPressureHistory;
    private fileDependencies;
    private reverseDependencies;
    private pendingInvalidations;
    private invalidationTimeout;
    private metricsHistory;
    private readonly maxMetricsHistory;
    constructor(config?: Partial<CacheManagerConfig>);
    /**
     * Initialize the cache manager
     */
    initialize(): Promise<void>;
    /**
     * Start periodic memory pressure monitoring
     */
    private startMemoryMonitoring;
    /**
     * Stop memory pressure monitoring
     */
    private stopMemoryMonitoring;
    /**
     * Get cached LLM response
     */
    getLLMResponse(messages: CodeBuddyMessage[], model: string, options?: {
        systemPromptHash?: string;
        toolsHash?: string;
    }): Promise<import("./llm-response-cache.js").LLMCacheEntry | null>;
    /**
     * Cache LLM response
     */
    setLLMResponse(messages: CodeBuddyMessage[], response: {
        content: string | null;
        toolCalls?: unknown[];
        usage?: {
            promptTokens: number;
            completionTokens: number;
        };
    }, model: string, options?: {
        systemPromptHash?: string;
        toolsHash?: string;
    }): void;
    /**
     * Read file with caching
     */
    readFile(filePath: string, encoding?: BufferEncoding): Promise<{
        content: string;
        cached: boolean;
        hash: string;
    }>;
    /**
     * Invalidate file cache
     */
    invalidateFile(filePath: string): void;
    /**
     * Check if file has changed
     */
    hasFileChanged(filePath: string): Promise<boolean>;
    /**
     * Get file hash without reading content
     */
    getFileHash(filePath: string): string | null;
    /**
     * Get cached embedding
     */
    getEmbedding(content: string, model?: string): number[] | null;
    /**
     * Cache embedding
     */
    setEmbedding(content: string, embedding: number[], metadata?: {
        source?: string;
        chunkIndex?: number;
        tokenCount?: number;
    }): void;
    /**
     * Get or compute embedding
     */
    getOrComputeEmbedding(content: string, computeFn: () => Promise<number[]>, metadata?: {
        source?: string;
        chunkIndex?: number;
        tokenCount?: number;
    }): Promise<{
        embedding: number[];
        cached: boolean;
    }>;
    /**
     * Get cached search results
     */
    getSearchResults<T>(query: string, searchType: 'text' | 'file' | 'symbol' | 'reference', options?: Record<string, unknown>): T | null;
    /**
     * Cache search results
     */
    setSearchResults<T>(query: string, searchType: 'text' | 'file' | 'symbol' | 'reference', results: T, options?: {
        affectedFiles?: string[];
        executionTimeMs?: number;
        options?: Record<string, unknown>;
    }): void;
    /**
     * Get or compute search results
     */
    getOrComputeSearchResults<T>(query: string, searchType: 'text' | 'file' | 'symbol' | 'reference', computeFn: () => Promise<T>, options?: {
        affectedFiles?: string[];
        options?: Record<string, unknown>;
    }): Promise<{
        results: T;
        cached: boolean;
    }>;
    /**
     * Invalidate all caches for a file
     */
    invalidateForFile(filePath: string): void;
    /**
     * Invalidate all caches for a directory
     */
    invalidateForDirectory(dirPath: string): void;
    /**
     * Register a cache entry's dependency on files
     */
    registerDependency(cacheKey: string, filePaths: string[]): void;
    /**
     * Unregister a cache entry's dependencies
     */
    unregisterDependency(cacheKey: string): void;
    /**
     * Invalidate all cache entries that depend on a file
     */
    private invalidateDependents;
    /**
     * Queue a file for invalidation (debounced)
     */
    queueInvalidation(filePath: string): void;
    /**
     * Process all pending invalidations
     */
    private processPendingInvalidations;
    /**
     * Get dependency statistics
     */
    getDependencyStats(): {
        trackedFiles: number;
        trackedCacheKeys: number;
        totalDependencies: number;
    };
    /**
     * Clear all caches
     */
    clearAll(): void;
    /**
     * Get unified statistics
     */
    getStats(): UnifiedCacheStats;
    /**
     * Format statistics for display
     */
    formatStats(): string;
    /**
     * Check memory pressure and evict if needed
     * Uses actual process heap memory (process.memoryUsage().heapUsed)
     */
    private checkMemoryPressure;
    /**
     * Record a memory pressure event for history tracking
     */
    private recordMemoryPressureEvent;
    /**
     * Get memory pressure history for diagnostics
     */
    getMemoryPressureHistory(): Array<{
        timestamp: number;
        heapUsedMB: number;
        action: string;
    }>;
    /**
     * Get current memory status
     */
    getMemoryStatus(): {
        heapUsedMB: number;
        heapTotalMB: number;
        thresholdMB: number;
        usagePercent: number;
        status: 'normal' | 'warning' | 'critical';
    };
    /**
     * Evict low-priority entries to reduce memory
     * Uses LRU strategy across all caches
     */
    private evictLowPriorityEntries;
    /**
     * Force immediate memory pressure check and eviction if needed
     */
    forceMemoryCheck(): {
        evicted: boolean;
        status: {
            heapUsedMB: number;
            heapTotalMB: number;
            thresholdMB: number;
            usagePercent: number;
            status: 'normal' | 'warning' | 'critical';
        };
    };
    /**
     * Update memory threshold at runtime
     */
    setMemoryThreshold(thresholdMB: number): void;
    /**
     * Update memory check interval at runtime
     */
    setMemoryCheckInterval(intervalMs: number): void;
    /**
     * Log metrics periodically
     */
    private logMetrics;
    /**
     * Get metrics trend over time
     */
    getMetricsTrend(): {
        hitRateTrend: number[];
        entriesTrend: number[];
        memoryTrend: number[];
        timestamps: number[];
    };
    /**
     * Get detailed metrics report
     */
    getDetailedMetrics(): {
        current: UnifiedCacheStats;
        trend: {
            hitRateTrend: number[];
            entriesTrend: number[];
            memoryTrend: number[];
            timestamps: number[];
        };
        dependencies: {
            trackedFiles: number;
            trackedCacheKeys: number;
            totalDependencies: number;
        };
        health: {
            status: 'healthy' | 'warning' | 'critical';
            issues: string[];
        };
    };
    /**
     * Export all cache data for persistence
     */
    exportCacheState(): Promise<{
        timestamp: number;
        metrics: UnifiedCacheStats;
        dependencies: {
            fileDeps: [string, string[]][];
            reverseDeps: [string, string[]][];
        };
    }>;
    /**
     * Import cache state from persistence
     */
    importCacheState(state: Awaited<ReturnType<typeof this.exportCacheState>>): Promise<void>;
    /**
     * Setup event forwarding from individual caches
     */
    private setupEventForwarding;
    /**
     * Get individual cache instances for advanced usage
     */
    getCaches(): {
        llm: LLMResponseCache;
        file: FileContentCache;
        embedding: EmbeddingCache;
        search: SearchResultsCache<unknown>;
    };
    /**
     * Persist all cache state to disk for long sessions
     */
    persistToDisk(basePath?: string): Promise<void>;
    /**
     * Restore cache state from disk
     */
    restoreFromDisk(basePath?: string): Promise<boolean>;
    /**
     * Clean up old cache files
     */
    cleanupOldCacheFiles(basePath?: string, maxAgeDays?: number): Promise<number>;
    /**
     * Dispose resources
     */
    dispose(): Promise<void>;
}
export declare function getCacheManager(config?: Partial<CacheManagerConfig>): CacheManager;
export declare function initializeCacheManager(config?: Partial<CacheManagerConfig>): Promise<CacheManager>;
export declare function resetCacheManager(): Promise<void>;
