import { getLogger as getLogger$1 } from "../../../logger.js";
import manageDbPool_default from "../../../data/db/manageDbPool.js";
import runDbClient_default from "../../../data/db/runDbClient.js";
import { evaluateConversationWorkflow } from "../workflow/functions/evaluateConversation.js";
import "../workflow/index.js";
import { createEvaluationRun, generateId, 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");
const triggerConversationEvaluation = async (params) => {
	const { tenantId, projectId, conversationId, resolvedRef } = params;
	try {
		logger.info({
			tenantId,
			projectId,
			conversationId
		}, "Triggering conversation evaluation (eval-api handling all logic)");
		if (!await getConversation(runDbClient_default)({
			scopes: {
				tenantId,
				projectId
			},
			conversationId
		})) throw new Error(`Conversation not found: ${conversationId}`);
		const runConfigs = (await withRef(manageDbPool_default, resolvedRef, (db) => listEvaluationRunConfigsWithSuiteConfigs(db)({ scopes: {
			tenantId,
			projectId
		} }))).filter((config) => config.isActive);
		if (runConfigs.length === 0) throw new Error("No active evaluation run configs found");
		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 (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;
				}
			}
			const evaluatorIds = (await withRef(manageDbPool_default, resolvedRef, (db) => getEvaluationSuiteConfigEvaluatorRelations(db)({ scopes: {
				tenantId,
				projectId,
				evaluationSuiteConfigId: suiteConfigId
			} }))).map((r) => r.evaluatorId);
			if (evaluatorIds.length === 0) continue;
			const evaluationRunId = generateId();
			await createEvaluationRun(runDbClient_default)({
				id: evaluationRunId,
				tenantId,
				projectId,
				evaluationRunConfigId: runConfig.id
			});
			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,
			tenantId,
			projectId,
			conversationId
		}, "Failed to trigger conversation evaluation");
		logger.error({ error: error?.stack }, "Failed to trigger conversation evaluation");
		logger.error({ error: error?.message }, "Failed to trigger conversation evaluation");
		throw error;
	}
};

//#endregion
export { triggerConversationEvaluation };