import manageDbPool_default from "../../../data/db/manageDbPool.js";
import runDbClient_default from "../../../data/db/runDbClient.js";
import { getLogger as getLogger$1 } from "../../../logger.js";
import { evaluateConversationWorkflow } from "../workflow/functions/evaluateConversation.js";
import "../workflow/index.js";
import { createEvaluationRun, generateId, getAgentIdsForEvaluators, getConversation, getEvaluationSuiteConfigById, getEvaluationSuiteConfigEvaluatorRelations, listEvaluationRunConfigsWithSuiteConfigs, withRef } from "@inkeep/agents-core";
import { start } from "workflow/api";

//#region src/domains/evals/services/conversationEvaluation.ts
const logger = getLogger$1("ConversationEvaluation");
function extractSuiteFilterCriteria(filter) {
	if (!filter) return null;
	if ("and" in filter || "or" in filter) return null;
	return filter;
}
function conversationMatchesSuiteFilter(conversationAgentId, filters) {
	const criteria = extractSuiteFilterCriteria(filters);
	if (!criteria?.agentIds || criteria.agentIds.length === 0) return true;
	return !!conversationAgentId && criteria.agentIds.includes(conversationAgentId);
}
const triggerConversationEvaluation = async (params) => {
	const { tenantId, projectId, conversationId, resolvedRef } = params;
	try {
		const runConfigs = (await withRef(manageDbPool_default, resolvedRef, (db) => listEvaluationRunConfigsWithSuiteConfigs(db)({ scopes: {
			tenantId,
			projectId
		} }))).filter((config) => config.isActive);
		if (runConfigs.length === 0) {
			logger.debug({
				tenantId,
				projectId,
				conversationId
			}, "No active evaluation run configs found, skipping evaluation");
			return {
				success: true,
				message: "No active evaluation run configs found",
				evaluationsTriggered: 0
			};
		}
		logger.info({
			tenantId,
			projectId,
			conversationId,
			runConfigCount: runConfigs.length
		}, "Triggering conversation evaluation");
		const conversation = await getConversation(runDbClient_default)({
			scopes: {
				tenantId,
				projectId
			},
			conversationId
		});
		if (!conversation) throw new Error(`Conversation not found: ${conversationId}`);
		let evaluationsTriggered = 0;
		for (const runConfig of runConfigs) for (const suiteConfigId of runConfig.suiteConfigIds) {
			const suiteConfig = await withRef(manageDbPool_default, resolvedRef, (db) => getEvaluationSuiteConfigById(db)({ scopes: {
				tenantId,
				projectId,
				evaluationSuiteConfigId: suiteConfigId
			} }));
			if (!suiteConfig) {
				logger.warn({ suiteConfigId }, "Suite config not found, skipping");
				continue;
			}
			if (!conversationMatchesSuiteFilter(conversation.agentId, suiteConfig.filters)) {
				logger.info({
					suiteConfigId: suiteConfig.id,
					conversationAgentId: conversation.agentId,
					filterAgentIds: extractSuiteFilterCriteria(suiteConfig.filters)?.agentIds,
					conversationId
				}, "Conversation filtered out by agent filter");
				continue;
			}
			if (suiteConfig.sampleRate !== null && suiteConfig.sampleRate !== void 0) {
				const random = Math.random();
				if (random > suiteConfig.sampleRate) {
					logger.info({
						suiteConfigId: suiteConfig.id,
						sampleRate: suiteConfig.sampleRate,
						random,
						conversationId
					}, "Conversation filtered out by sample rate");
					continue;
				}
			}
			let evaluatorIds = (await withRef(manageDbPool_default, resolvedRef, (db) => getEvaluationSuiteConfigEvaluatorRelations(db)({ scopes: {
				tenantId,
				projectId,
				evaluationSuiteConfigId: suiteConfigId
			} }))).map((r) => r.evaluatorId);
			if (evaluatorIds.length === 0) continue;
			const { agentId: conversationAgentId } = conversation;
			if (conversationAgentId) {
				const agentIdsMap = await withRef(manageDbPool_default, resolvedRef, (db) => getAgentIdsForEvaluators(db)({
					scopes: {
						tenantId,
						projectId
					},
					evaluatorIds
				}));
				evaluatorIds = evaluatorIds.filter((evalId) => {
					const scopedAgents = agentIdsMap.get(evalId);
					if (!scopedAgents || scopedAgents.length === 0) return true;
					return scopedAgents.includes(conversationAgentId);
				});
				if (evaluatorIds.length === 0) {
					logger.info({
						suiteConfigId,
						conversationAgentId,
						conversationId
					}, "All evaluators filtered out by agent scoping");
					continue;
				}
			}
			const evaluationRunId = generateId();
			await createEvaluationRun(runDbClient_default)({
				id: evaluationRunId,
				tenantId,
				projectId,
				evaluationRunConfigId: runConfig.id,
				ref: resolvedRef
			});
			logger.info({
				conversationId,
				runConfigId: runConfig.id,
				evaluationRunId,
				evaluatorCount: evaluatorIds.length,
				sampleRate: suiteConfig.sampleRate
			}, "Created evaluation run, starting workflow");
			await start(evaluateConversationWorkflow, [{
				tenantId,
				projectId,
				conversationId,
				evaluatorIds,
				evaluationRunId
			}]);
			evaluationsTriggered++;
		}
		return {
			success: true,
			message: evaluationsTriggered > 0 ? `Triggered ${evaluationsTriggered} evaluation(s)` : "No evaluations matched (filtered by sample rate or no evaluators)",
			evaluationsTriggered
		};
	} catch (error) {
		logger.error({
			error: error?.message,
			errorStack: error?.stack,
			tenantId,
			projectId,
			conversationId
		}, "Failed to trigger conversation evaluation");
		throw error;
	}
};

//#endregion
export { triggerConversationEvaluation };