import runDbClient_default from "../../../data/db/runDbClient.js";
import { getLogger as getLogger$1 } from "../../../logger.js";
import { runDatasetItemWorkflow } from "../workflow/functions/runDatasetItem.js";
import { markScheduledTriggerInvocationFailed } from "@inkeep/agents-core";
import { start } from "workflow/api";

//#region src/domains/evals/services/datasetRun.ts
async function queueDatasetRunItems(params) {
	const { tenantId, projectId, datasetRunId, items, evaluatorIds, evaluationRunId, ref } = params;
	const logger = getLogger$1("workflow-triggers");
	const results = await Promise.allSettled(items.map(async (item) => {
		await start(runDatasetItemWorkflow, [{
			tenantId,
			projectId,
			agentId: item.agentId,
			datasetItemId: item.id ?? (() => {
				throw new Error(`Dataset item missing id for agent ${item.agentId}`);
			})(),
			datasetItemInput: item.input,
			datasetItemExpectedOutput: item.expectedOutput,
			datasetRunId,
			scheduledTriggerInvocationId: item.scheduledTriggerInvocationId,
			evaluatorIds,
			evaluationRunId,
			ref
		}]);
	}));
	const failures = results.map((r, i) => r.status === "rejected" ? {
		item: items[i],
		reason: r.reason
	} : null).filter((f) => f !== null);
	await Promise.all(failures.map(({ item, reason }) => {
		logger.error({
			err: reason,
			datasetItemId: item.id,
			agentId: item.agentId
		}, "Failed to queue dataset item workflow");
		return markScheduledTriggerInvocationFailed(runDbClient_default)({
			scopes: {
				tenantId,
				projectId,
				agentId: item.agentId
			},
			scheduledTriggerId: datasetRunId,
			invocationId: item.scheduledTriggerInvocationId
		}).catch((err) => logger.warn({
			err,
			invocationId: item.scheduledTriggerInvocationId
		}, "Failed to mark trigger invocation as failed"));
	}));
	return {
		queued: results.length - failures.length,
		failed: failures.length
	};
}

//#endregion
export { queueDatasetRunItems };