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 manageDbClient_default from "../../../../data/db/manageDbClient.js";
import "../../../../data/db/index.js";
import { EvaluationService } from "../../services/EvaluationService.js";
import { createEvaluationResult, generateId, getConversation, getEvaluatorById, getEvaluatorsByIds, getProjectMainResolvedRef, updateEvaluationResult, withRef } from "@inkeep/agents-core";

//#region src/domains/evals/workflow/functions/evaluateConversation.ts
const logger = getLogger$1("workflow-evaluate-conversation");
async function getConversationStep(payload) {
	"use step";
	const { tenantId, projectId, conversationId } = payload;
	const conv = await getConversation(runDbClient_default)({
		scopes: {
			tenantId,
			projectId
		},
		conversationId
	});
	if (!conv) throw new Error(`Conversation not found: ${conversationId}`);
	return conv;
}
async function getEvaluatorsStep(payload) {
	"use step";
	const { tenantId, projectId, evaluatorIds } = payload;
	return await withRef(manageDbPool_default, await getProjectMainResolvedRef(manageDbClient_default)(tenantId, projectId), (db) => getEvaluatorsByIds(db)({
		scopes: {
			tenantId,
			projectId
		},
		evaluatorIds
	}));
}
async function executeEvaluatorStep(payload, evaluatorId, conversation) {
	"use step";
	const { tenantId, projectId, conversationId, evaluationRunId } = payload;
	const evaluator = await withRef(manageDbPool_default, await getProjectMainResolvedRef(manageDbClient_default)(tenantId, projectId), (db) => getEvaluatorById(db)({ scopes: {
		tenantId,
		projectId,
		evaluatorId
	} }));
	if (!evaluator) throw new Error(`Evaluator not found: ${evaluatorId}`);
	const evalResult = await createEvaluationResult(runDbClient_default)({
		id: generateId(),
		tenantId,
		projectId,
		conversationId,
		evaluatorId: evaluator.id,
		evaluationRunId
	});
	try {
		const output = await new EvaluationService().executeEvaluation({
			conversation,
			evaluator,
			tenantId,
			projectId
		});
		const updated = await updateEvaluationResult(runDbClient_default)({
			scopes: {
				tenantId,
				projectId,
				evaluationResultId: evalResult.id
			},
			data: { output }
		});
		logger.info({
			conversationId,
			evaluatorId: evaluator.id,
			resultId: evalResult.id
		}, "Evaluation completed successfully");
		return updated;
	} catch (error) {
		const errorMessage = error instanceof Error ? error.message : "Unknown error";
		logger.error({
			error,
			conversationId,
			evaluatorId: evaluator.id,
			resultId: evalResult.id
		}, "Evaluation execution failed");
		return await updateEvaluationResult(runDbClient_default)({
			scopes: {
				tenantId,
				projectId,
				evaluationResultId: evalResult.id
			},
			data: { output: { text: `Evaluation failed: ${errorMessage}` } }
		});
	}
}
/**
* Step: Log workflow progress
*/
async function logStep(message, data) {
	"use step";
	logger.info(data, message);
}
/**
* Main workflow function - orchestrates the evaluation steps.
*
* IMPORTANT: This runs in a deterministic sandbox.
* - Do NOT call Node.js APIs directly here (no DB, no fs, etc.)
* - All side effects must happen in step functions
*/
async function _evaluateConversationWorkflow(payload) {
	"use workflow";
	const { conversationId, evaluatorIds } = payload;
	await logStep("Starting conversation evaluation", payload);
	const conversation = await getConversationStep(payload);
	const evaluators = await getEvaluatorsStep(payload);
	if (evaluators.length === 0) {
		await logStep("No valid evaluators found", {
			conversationId,
			evaluatorIds
		});
		return {
			success: false,
			reason: "No valid evaluators"
		};
	}
	const results = [];
	for (const evaluator of evaluators) {
		const result = await executeEvaluatorStep(payload, evaluator.id, conversation);
		results.push(result);
	}
	return {
		success: true,
		conversationId,
		resultCount: results.length
	};
}
const evaluateConversationWorkflow = Object.assign(_evaluateConversationWorkflow, { workflowId: "workflow//./src/domains/evals/workflow/functions/evaluateConversation//_evaluateConversationWorkflow" });

//#endregion
export { evaluateConversationWorkflow };