import runDbClient_default from "../../../data/db/runDbClient.js";
import { cleanupTenantCache, clearContextConfigCache, clearConversationCache, generateId, getCacheEntry, getLogger, invalidateHeadersCache, invalidateInvocationDefinitionsCache, setCacheEntry } from "@inkeep/agents-core";

//#region src/domains/run/context/contextCache.ts
const logger = getLogger("context-cache");
/**
* Context cache with request hash-based invalidation and graceful error handling.
*
* Implements conversation-scoped caching with smart cache invalidation based on
* request hash changes. All cache errors are treated as cache misses to ensure
* system reliability.
*/
var ContextCache = class {
	executionContext;
	constructor(executionContext) {
		this.executionContext = executionContext;
		logger.info({ tenantId: this.executionContext.tenantId }, "ContextCache initialized");
	}
	/**
	* Get cached context data for a conversation
	*/
	async get({ conversationId, contextConfigId, contextVariableKey, requestHash }) {
		try {
			let cacheEntry = null;
			cacheEntry = await getCacheEntry(runDbClient_default)({
				conversationId,
				contextConfigId,
				contextVariableKey,
				requestHash
			});
			if (!cacheEntry) return null;
			return {
				contextConfigId: cacheEntry.contextConfigId,
				contextVariableKey: cacheEntry.contextVariableKey,
				conversationId: cacheEntry.conversationId,
				value: cacheEntry.value,
				requestHash: cacheEntry.requestHash || void 0,
				tenantId: this.executionContext.tenantId
			};
		} catch (error) {
			logger.error({
				conversationId,
				contextConfigId,
				contextVariableKey,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to get cache entry");
			return null;
		}
	}
	/**
	* Set cached context data for a conversation
	*/
	async set(entry) {
		try {
			const { tenantId, projectId } = this.executionContext;
			const cacheData = {
				id: generateId(),
				tenantId,
				projectId,
				conversationId: entry.conversationId,
				contextConfigId: entry.contextConfigId,
				contextVariableKey: entry.contextVariableKey,
				value: entry.value,
				requestHash: entry.requestHash,
				fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
				fetchSource: `${entry.contextConfigId}:${entry.contextVariableKey}`,
				createdAt: (/* @__PURE__ */ new Date()).toISOString(),
				updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
				ref: this.executionContext.resolvedRef
			};
			await setCacheEntry(runDbClient_default)(cacheData);
			logger.debug({
				conversationId: entry.conversationId,
				contextConfigId: entry.contextConfigId,
				contextVariableKey: entry.contextVariableKey
			}, "Cache entry set successfully");
		} catch (error) {
			logger.error({
				conversationId: entry.conversationId,
				contextConfigId: entry.contextConfigId,
				contextVariableKey: entry.contextVariableKey,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to set cache entry");
		}
	}
	/**
	* Clear cache entries for a specific conversation
	*/
	async clearConversation(tenantId, projectId, conversationId) {
		try {
			const result = await clearConversationCache(runDbClient_default)({
				scopes: {
					tenantId,
					projectId
				},
				conversationId
			});
			logger.info({
				conversationId,
				rowsCleared: result
			}, "Conversation cache cleared successfully");
		} catch (error) {
			logger.error({
				conversationId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to clear conversation cache");
			throw error;
		}
	}
	/**
	* Clear all cache entries for a specific context configuration
	*/
	async clearContextConfig(tenantId, projectId, contextConfigId) {
		try {
			const result = await clearContextConfigCache(runDbClient_default)({
				scopes: {
					tenantId,
					projectId
				},
				contextConfigId
			});
			logger.info({
				contextConfigId,
				rowsCleared: result
			}, "Context config cache cleared successfully");
		} catch (error) {
			logger.error({
				contextConfigId,
				error: error instanceof Error ? error.message : "Unknown error"
			}, "Failed to clear context config cache");
			throw error;
		}
	}
	/**
	* Clean up expired or orphaned cache entries
	*/
	async cleanup() {
		try {
			const { tenantId, projectId } = this.executionContext;
			const result = await cleanupTenantCache(runDbClient_default)({ scopes: {
				tenantId,
				projectId
			} });
			logger.info({ rowsCleared: result }, "Cache cleanup completed");
		} catch (error) {
			logger.error({ error: error instanceof Error ? error.message : "Unknown error" }, "Failed to cleanup cache");
			throw error;
		}
	}
	async invalidateInvocationDefinitions(tenantId, projectId, conversationId, contextConfigId, definitionIds) {
		await invalidateInvocationDefinitionsCache(runDbClient_default)({
			scopes: {
				tenantId,
				projectId
			},
			conversationId,
			contextConfigId,
			invocationDefinitionIds: definitionIds
		});
	}
	async invalidateHeaders(tenantId, projectId, conversationId, contextConfigId) {
		await invalidateHeadersCache(runDbClient_default)({
			scopes: {
				tenantId,
				projectId
			},
			conversationId,
			contextConfigId
		});
	}
};

//#endregion
export { ContextCache };