// engine/token-optimizer/incremental.ts — Incremental/delta responses (SPEC-082 AC-06)
import { createHash } from 'node:crypto';
/**
 * Tracks previous responses and computes deltas for incremental updates.
 */
export class IncrementalTracker {
    // key = toolName + inputHash -> previous response
    snapshots = new Map();
    /**
     * Build a composite key from tool name and input.
     */
    static buildKey(toolName, input) {
        const inputHash = createHash('sha256').update(input).digest('hex').slice(0, 12);
        return `${toolName}:${inputHash}`;
    }
    /**
     * Compare current response against previous snapshot.
     * If first time or changed, stores new snapshot.
     */
    compare(key, currentResponse) {
        const previous = this.snapshots.get(key);
        const fullSize = currentResponse.length;
        if (previous === undefined) {
            // First time — store and return full
            this.snapshots.set(key, currentResponse);
            return { changed: true, delta: currentResponse, fullSize, deltaSize: fullSize };
        }
        if (previous === currentResponse) {
            // No change
            return { changed: false, delta: '', fullSize, deltaSize: 0 };
        }
        // Compute line-level delta
        const delta = this.computeDelta(previous, currentResponse);
        this.snapshots.set(key, currentResponse);
        return {
            changed: true,
            delta,
            fullSize,
            deltaSize: delta.length,
        };
    }
    /**
     * Clear snapshot for a specific key.
     */
    clearKey(key) {
        this.snapshots.delete(key);
    }
    /**
     * Clear all snapshots.
     */
    clear() {
        this.snapshots.clear();
    }
    /**
     * Get the number of stored snapshots.
     */
    size() {
        return this.snapshots.size;
    }
    // --- Internal ---
    computeDelta(previous, current) {
        const prevLines = previous.split('\n');
        const currLines = current.split('\n');
        const prevSet = new Set(prevLines);
        const added = [];
        const removed = [];
        for (const line of currLines) {
            if (!prevSet.has(line)) {
                added.push(`+ ${line}`);
            }
        }
        const currSet = new Set(currLines);
        for (const line of prevLines) {
            if (!currSet.has(line)) {
                removed.push(`- ${line}`);
            }
        }
        const parts = [];
        if (removed.length > 0) {
            parts.push('--- Removed:', ...removed);
        }
        if (added.length > 0) {
            parts.push('+++ Added:', ...added);
        }
        return parts.join('\n');
    }
}
//# sourceMappingURL=incremental.js.map