const DEFAULT_TTL_MS = 15 * 60_000;
const DEFAULT_MAX_ENTRIES = 256;
function sweepExpired(entries, now) {
    for (const [key, entry] of entries) {
        if (entry.expiresAtMs <= now) {
            entries.delete(key);
        }
    }
}
function evictOldest(entries, maxEntries) {
    while (entries.size >= maxEntries) {
        let oldest;
        for (const entry of entries.values()) {
            if (oldest === undefined || entry.touchedAtMs < oldest.touchedAtMs) {
                oldest = entry;
            }
        }
        if (oldest === undefined) {
            return;
        }
        entries.delete(oldest.assistantMessageId);
    }
}
export function createGroundedTurnRegistry(ttlMs = DEFAULT_TTL_MS, maxEntries = DEFAULT_MAX_ENTRIES) {
    const entries = new Map();
    return {
        remember(record, nowMs = Date.now) {
            const now = nowMs();
            sweepExpired(entries, now);
            evictOldest(entries, maxEntries);
            entries.set(record.assistantMessageId, {
                ...record,
                touchedAtMs: now,
                expiresAtMs: now + ttlMs,
            });
        },
        lookup(assistantMessageId, nowMs = Date.now) {
            const now = nowMs();
            sweepExpired(entries, now);
            const entry = entries.get(assistantMessageId);
            if (entry === undefined) {
                return undefined;
            }
            entry.touchedAtMs = now;
            entry.expiresAtMs = now + ttlMs;
            return entry;
        },
        clearConversation(chatId) {
            for (const [key, entry] of entries) {
                if (entry.chatId === chatId) {
                    entries.delete(key);
                }
            }
        },
        clearWorkspace(workspaceRoot) {
            for (const [key, entry] of entries) {
                if (entry.workspaceRoot === workspaceRoot) {
                    entries.delete(key);
                }
            }
        },
        clearAll() {
            entries.clear();
        },
    };
}
export const groundedTurnRegistry = createGroundedTurnRegistry();
export function rememberGroundedTurn(record, nowMs) {
    groundedTurnRegistry.remember(record, nowMs);
}
export function lookupGroundedTurn(assistantMessageId, nowMs) {
    return groundedTurnRegistry.lookup(assistantMessageId, nowMs);
}
export function clearGroundedTurnsForConversation(chatId) {
    groundedTurnRegistry.clearConversation(chatId);
}
export function clearGroundedTurnsForWorkspace(workspaceRoot) {
    groundedTurnRegistry.clearWorkspace(workspaceRoot);
}
export function clearAllGroundedTurns() {
    groundedTurnRegistry.clearAll();
}
