import runDbClient_default from "../../../data/db/runDbClient.js";
import { getLogger as getLogger$1 } from "../../../logger.js";
import { formatEvent } from "../../../utils/conversationFormatter.js";
import { emitEventWebhook } from "../services/WebhookDeliveryService.js";
import { isAutoMintIdentity, stripIdentificationType } from "../utils/user-properties.js";
import { OpenAPIHono } from "@hono/zod-openapi";
import { EventApiInsertSchema, EventResponse, commonCreateErrorResponses, createEvent, generateId, getConversation, getConversationUserProperties, getMessageById, getMessageUserProperties } from "@inkeep/agents-core";
import { createProtectedRoute, inheritedRunApiKeyAuth } from "@inkeep/agents-core/middleware";

//#region src/domains/run/routes/events.ts
const logger = getLogger$1("run-events");
const app = new OpenAPIHono();
async function resolveAutoFillChain(params) {
	const { body, scopes } = params;
	const callerUserProperties = isAutoMintIdentity(body.userProperties) ? void 0 : stripIdentificationType(body.userProperties);
	const callerProperties = body.properties;
	let messageRow;
	let conversationRow;
	try {
		if (body.messageId) messageRow = await getMessageById(runDbClient_default)({
			scopes,
			messageId: body.messageId
		});
		const conversationId = body.conversationId ?? messageRow?.conversationId;
		if (conversationId && (callerUserProperties === void 0 || callerProperties === void 0)) conversationRow = await getConversation(runDbClient_default)({
			scopes,
			conversationId
		});
	} catch (err) {
		logger.warn({
			messageId: body.messageId,
			conversationId: body.conversationId,
			error: err instanceof Error ? err.message : String(err)
		}, "Auto-fill enrichment failed; proceeding with caller-supplied values");
		return {
			userProperties: callerUserProperties ?? null,
			properties: callerProperties ?? null,
			conversationId: body.conversationId ?? null
		};
	}
	const resolvedConversationId = body.conversationId ?? messageRow?.conversationId ?? null;
	let resolvedUserProperties;
	if (callerUserProperties !== void 0) resolvedUserProperties = callerUserProperties;
	else resolvedUserProperties = messageRow ? getMessageUserProperties(messageRow, conversationRow) : conversationRow ? getConversationUserProperties(conversationRow) : null;
	let resolvedProperties;
	if (callerProperties !== void 0) resolvedProperties = callerProperties;
	else resolvedProperties = messageRow?.properties ?? conversationRow?.properties ?? null;
	return {
		userProperties: resolvedUserProperties,
		properties: resolvedProperties,
		conversationId: resolvedConversationId
	};
}
app.openapi(createProtectedRoute({
	method: "post",
	path: "/",
	summary: "Log Event",
	description: "Log an application-level event for the authenticated project.",
	operationId: "log-event",
	tags: ["Events"],
	security: [{ bearerAuth: [] }],
	permission: inheritedRunApiKeyAuth(),
	request: { body: { content: { "application/json": { schema: EventApiInsertSchema } } } },
	responses: {
		201: {
			description: "Event logged successfully (new row inserted)",
			content: { "application/json": { schema: EventResponse } }
		},
		200: {
			description: "Event already exists (idempotent conflict on client-supplied id)",
			content: { "application/json": { schema: EventResponse } }
		},
		...commonCreateErrorResponses
	}
}), async (c) => {
	const executionContext = c.get("executionContext");
	const { tenantId, projectId } = executionContext;
	const body = c.req.valid("json");
	const { userProperties: resolvedUserProperties, properties: resolvedProperties, conversationId: resolvedConversationId } = await resolveAutoFillChain({
		body,
		scopes: {
			tenantId,
			projectId
		}
	});
	const result = await createEvent(runDbClient_default)({
		...body,
		id: body.id || generateId(),
		tenantId,
		projectId,
		conversationId: resolvedConversationId,
		agentId: body.agentId ?? executionContext.agentId ?? null,
		userProperties: resolvedUserProperties,
		properties: resolvedProperties,
		metadata: body.metadata ?? null,
		serverMetadata: { authMethod: executionContext.metadata?.authMethod }
	});
	logger.debug({
		tenantId,
		projectId,
		eventId: result.row.id,
		type: result.row.type,
		conflict: result.conflict
	}, "Logged event");
	const formatted = formatEvent(result.row);
	const resolvedRef = c.get("resolvedRef");
	const dispatchAgentId = result.row.agentId ?? executionContext.agentId;
	if (!resolvedRef || !dispatchAgentId) logger.debug({
		tenantId,
		projectId,
		eventId: result.row.id,
		type: result.row.type,
		hasResolvedRef: !!resolvedRef,
		hasAgentId: !!dispatchAgentId
	}, "Skipping event.created webhook dispatch (event persisted; no resolvedRef or agentId)");
	else await emitEventWebhook({
		tenantId,
		projectId,
		agentId: dispatchAgentId,
		resolvedRef,
		event: result.row
	});
	return c.json({ data: formatted }, result.conflict ? 200 : 201);
});
var events_default = app;

//#endregion
export { events_default as default };