/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * Connects the raw AgentChatHistory to the ContextManager.
 * It maps raw messages into Episodic Intermediate Representation (Context Graph)
 * and evaluates background triggers whenever history changes.
 */
export class HistoryObserver {
    chatHistory;
    eventBus;
    tracer;
    tokenCalculator;
    graphMapper;
    unsubscribeHistory;
    seenNodeIds = new Set();
    constructor(chatHistory, eventBus, tracer, tokenCalculator, graphMapper) {
        this.chatHistory = chatHistory;
        this.eventBus = eventBus;
        this.tracer = tracer;
        this.tokenCalculator = tokenCalculator;
        this.graphMapper = graphMapper;
    }
    processEvent = (event) => {
        let nodes = [];
        if (event.type === 'CLEAR') {
            this.seenNodeIds.clear();
        }
        nodes = this.graphMapper.applyEvent(event, this.tokenCalculator);
        const newNodes = new Set();
        for (const node of nodes) {
            if (!this.seenNodeIds.has(node.id)) {
                newNodes.add(node.id);
                this.seenNodeIds.add(node.id);
            }
        }
        this.tracer.logEvent('HistoryObserver', `Rebuilt pristine graph from ${event.type} event`, { nodesSize: nodes.length, newNodesCount: newNodes.size });
        this.eventBus.emitPristineHistoryUpdated({
            nodes,
            newNodes,
        });
    };
    start() {
        if (this.unsubscribeHistory) {
            this.unsubscribeHistory();
        }
        this.unsubscribeHistory = this.chatHistory.subscribe(this.processEvent);
        // Process any existing history immediately upon start
        const existing = this.chatHistory.get();
        if (existing && existing.length > 0) {
            this.processEvent({ type: 'SYNC_FULL', payload: existing });
        }
    }
    stop() {
        if (this.unsubscribeHistory) {
            this.unsubscribeHistory();
            this.unsubscribeHistory = undefined;
        }
    }
}
//# sourceMappingURL=historyObserver.js.map