"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContextCompactor = exports.DEFAULT_CONTEXT_COMPACTOR_CONFIG = void 0;
exports.getContextCompactor = getContextCompactor;
exports.setContextCompactor = setContextCompactor;
exports.resetContextCompactor = resetContextCompactor;
exports.createContextCompactor = createContextCompactor;
/**
 * Context Compactor
 *
 * 上下文压缩服务
 * 当上下文超过阈值时自动压缩，防止 token 溢出
 */
const compactionTypes_1 = require("./compactionTypes");
const tokenEstimator_1 = require("./tokenEstimator");
const slidingWindowStrategy_1 = require("./strategies/slidingWindowStrategy");
/**
 * 默认配置
 */
exports.DEFAULT_CONTEXT_COMPACTOR_CONFIG = {
    ...compactionTypes_1.DEFAULT_COMPACTION_CONFIG,
    enabled: true, // 默认启用，防止 token 溢出
    logCompaction: false,
};
/**
 * Context Compactor
 */
class ContextCompactor {
    constructor(config = {}) {
        this.config = { ...exports.DEFAULT_CONTEXT_COMPACTOR_CONFIG, ...config };
        this.tokenEstimator = (0, tokenEstimator_1.getTokenEstimator)();
        this.strategies = new Map();
        this.sessionStates = new Map();
        // 注册内置策略
        this.registerStrategy(new slidingWindowStrategy_1.SlidingWindowStrategy(this.tokenEstimator));
    }
    // ===========================================================================
    // Strategy Management
    // ===========================================================================
    /**
     * 注册压缩策略
     */
    registerStrategy(strategy) {
        this.strategies.set(strategy.name, strategy);
    }
    /**
     * 获取策略
     */
    getStrategy(name) {
        return this.strategies.get(name);
    }
    // ===========================================================================
    // Main Methods
    // ===========================================================================
    /**
     * 检查是否需要压缩
     */
    needsCompaction(context) {
        if (!this.config.enabled) {
            return false;
        }
        return this.tokenEstimator.needsCompaction(context, this.config.compactionThreshold);
    }
    /**
     * 执行压缩
     */
    async compact(context, reason = 'threshold_exceeded') {
        // 获取策略
        const strategy = this.strategies.get(this.config.strategy);
        if (!strategy) {
            throw new Error(`Unknown compaction strategy: ${this.config.strategy}`);
        }
        // 执行压缩
        const result = await strategy.compact(context, this.config);
        result.metadata.reason = reason;
        // 更新会话状态
        this.updateSessionState(context.sessionId, result);
        // 记录日志
        if (this.config.logCompaction) {
            this.logCompactionResult(result);
        }
        return result;
    }
    /**
     * 自动压缩（如果需要）
     */
    async compactIfNeeded(context) {
        if (!this.needsCompaction(context)) {
            return context;
        }
        const result = await this.compact(context, 'threshold_exceeded');
        return result.compactedContext;
    }
    /**
     * 估算上下文 token 数
     */
    estimateTokens(context) {
        return this.tokenEstimator.estimate(context).total;
    }
    /**
     * 获取详细的 token 估算
     */
    getDetailedEstimate(context) {
        return this.tokenEstimator.estimateWithThreshold(context, this.config);
    }
    // ===========================================================================
    // Session State Management
    // ===========================================================================
    /**
     * 获取会话压缩状态
     */
    getSessionState(sessionId) {
        return this.sessionStates.get(sessionId);
    }
    /**
     * 更新会话状态
     */
    updateSessionState(sessionId, result) {
        let state = this.sessionStates.get(sessionId);
        if (!state) {
            state = {
                sessionId,
                compactionCount: 0,
                totalRemovedResults: 0,
                totalRemovedFindings: 0,
                accumulatedSummaries: [],
                lastCompactionTime: 0,
            };
        }
        state.compactionCount++;
        state.totalRemovedResults += result.removedResultsCount;
        state.totalRemovedFindings += result.removedFindingsCount;
        state.lastCompactionTime = result.metadata.timestamp;
        if (result.summary) {
            state.accumulatedSummaries.push(result.summary);
        }
        this.sessionStates.set(sessionId, state);
    }
    /**
     * 清除会话状态
     */
    clearSessionState(sessionId) {
        this.sessionStates.delete(sessionId);
    }
    // ===========================================================================
    // Configuration
    // ===========================================================================
    /**
     * 启用/禁用压缩
     */
    setEnabled(enabled) {
        this.config.enabled = enabled;
    }
    /**
     * 检查是否启用
     */
    isEnabled() {
        return this.config.enabled;
    }
    /**
     * 更新配置
     */
    updateConfig(config) {
        this.config = { ...this.config, ...config };
    }
    /**
     * 获取配置
     */
    getConfig() {
        return { ...this.config };
    }
    // ===========================================================================
    // Logging
    // ===========================================================================
    /**
     * 记录压缩结果
     */
    logCompactionResult(result) {
        console.log(`[ContextCompactor] Compaction completed:`);
        console.log(`  - Strategy: ${result.metadata.strategy}`);
        console.log(`  - Original tokens: ${result.originalTokens}`);
        console.log(`  - Compacted tokens: ${result.compactedTokens}`);
        console.log(`  - Compression ratio: ${(result.compressionRatio * 100).toFixed(1)}%`);
        console.log(`  - Removed results: ${result.removedResultsCount}`);
        console.log(`  - Removed findings: ${result.removedFindingsCount}`);
        console.log(`  - Has summary: ${result.hasSummary}`);
    }
}
exports.ContextCompactor = ContextCompactor;
// =============================================================================
// Singleton and Factory
// =============================================================================
let _globalContextCompactor = null;
/**
 * 获取全局 Context Compactor
 */
function getContextCompactor() {
    if (!_globalContextCompactor) {
        _globalContextCompactor = new ContextCompactor();
    }
    return _globalContextCompactor;
}
/**
 * 设置全局 Context Compactor
 */
function setContextCompactor(compactor) {
    _globalContextCompactor = compactor;
}
/**
 * 重置全局 Context Compactor
 */
function resetContextCompactor() {
    _globalContextCompactor = null;
}
/**
 * 创建 Context Compactor
 */
function createContextCompactor(config = {}) {
    return new ContextCompactor(config);
}
exports.default = ContextCompactor;
//# sourceMappingURL=contextCompactor.js.map