/**
 * Token Optimizer Engine
 *
 * Intelligent token allocation using AdaptiveKVMerge principles.
 */
export class TokenOptimizer {
    maxTokens;
    qualityThreshold = 0.64;
    compressionHistory = new Map();
    constructor(maxTokens = 128000) {
        this.maxTokens = maxTokens;
    }
    /**
     * Assess task complexity (0-1)
     */
    assessComplexity(task) {
        // Simple heuristic-based assessment
        const indicators = {
            simple: ['what', 'when', 'who', 'where', 'is', 'are', '?', 'list'],
            complex: ['build', 'create', 'design', 'implement', 'develop', 'explain why', 'analyze']
        };
        let score = 0.5;
        const taskLower = task.toLowerCase();
        for (const word of indicators.simple) {
            if (taskLower.includes(word))
                score -= 0.1;
        }
        for (const word of indicators.complex) {
            if (taskLower.includes(word))
                score += 0.15;
        }
        return Math.max(0, Math.min(1, score));
    }
    /**
     * Determine compression ratio based on complexity
     */
    getCompressionRatio(complexity) {
        if (complexity < 0.3)
            return 8.0; // Aggressive for simple
        if (complexity < 0.7)
            return 5.0; // Moderate for normal
        return 3.0; // Conservative for complex
    }
    /**
     * Optimize token allocation
     */
    optimize(context, task) {
        const complexity = this.assessComplexity(task);
        const ratio = this.getCompressionRatio(complexity);
        // Estimate tokens needed
        const baseTokens = context.reduce((sum, c) => sum + c.length / 4, 0);
        const optimizedTokens = Math.floor(baseTokens / ratio);
        return {
            tokens: Math.min(optimizedTokens, this.maxTokens),
            ratio,
            strategy: complexity < 0.3 ? 'aggressive' :
                complexity < 0.7 ? 'moderate' : 'conservative'
        };
    }
    /**
     * Track compression for learning
     */
    trackCompression(taskType, quality) {
        this.compressionHistory.set(taskType, quality);
    }
    /**
     * Get average quality for a task type
     */
    getAverageQuality(taskType) {
        const history = this.compressionHistory.get(taskType);
        return history || 0.5;
    }
}
export const createTokenOptimizer = (maxTokens) => new TokenOptimizer(maxTokens);
