import runDbClient_default from "../../../data/db/runDbClient.js";
import { getLogger as getLogger$1 } from "../../../logger.js";
import { scheduledTriggerRunnerWorkflow } from "../workflow/functions/scheduledTriggerRunner.js";
import { advanceScheduledTriggerNextRunAt, computeNextRunAt, findDueScheduledTriggersAcrossProjects } from "@inkeep/agents-core";
import { start } from "workflow/api";

//#region src/domains/run/services/triggerDispatcher.ts
const logger = getLogger$1("triggerDispatcher");
async function dispatchDueTriggers() {
	const now = /* @__PURE__ */ new Date();
	const dueTriggers = await findDueScheduledTriggersAcrossProjects(runDbClient_default)({ asOf: now.toISOString() });
	if (dueTriggers.length === 0) return { dispatched: 0 };
	logger.info({ dueCount: dueTriggers.length }, "Found due triggers");
	const results = await Promise.allSettled(dueTriggers.map((trigger) => dispatchSingleTrigger(trigger)));
	let dispatched = 0;
	for (let i = 0; i < results.length; i++) {
		const result = results[i];
		if (result.status === "fulfilled") dispatched++;
		else {
			const trigger = dueTriggers[i];
			logger.error({
				error: result.reason,
				scheduledTriggerId: trigger.id,
				tenantId: trigger.tenantId,
				projectId: trigger.projectId,
				agentId: trigger.agentId
			}, "Dispatch failed unexpectedly");
		}
	}
	return { dispatched };
}
async function dispatchSingleTrigger(trigger) {
	const { tenantId, projectId, agentId, id: scheduledTriggerId } = trigger;
	const nextRunAt = !trigger.cronExpression ? null : computeNextRunAt({
		cronExpression: trigger.cronExpression,
		cronTimezone: trigger.cronTimezone,
		runAt: trigger.runAt,
		lastScheduledFor: trigger.nextRunAt
	});
	await start(scheduledTriggerRunnerWorkflow, [{
		tenantId,
		projectId,
		agentId,
		scheduledTriggerId,
		scheduledFor: trigger.nextRunAt ?? (/* @__PURE__ */ new Date()).toISOString(),
		ref: trigger.ref
	}]);
	try {
		await advanceScheduledTriggerNextRunAt(runDbClient_default)({
			scopes: {
				tenantId,
				projectId,
				agentId
			},
			scheduledTriggerId,
			nextRunAt
		});
	} catch (err) {
		logger.error({
			scheduledTriggerId,
			err
		}, "Failed to advance next_run_at after workflow start; next tick will retry (idempotent)");
	}
	logger.info({
		scheduledTriggerId,
		scheduledFor: trigger.nextRunAt
	}, "Trigger dispatched");
}

//#endregion
export { dispatchDueTriggers };