"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.wrapWithEvents = wrapWithEvents;
const logger_1 = require("../../../lib/logger");
const publish_1 = require("../../../lib/events/publish");
/**
 * Wrap a worker callback with activity lifecycle event publishing.
 * Publishes activity.started before and activity.completed/failed after.
 */
function wrapWithEvents(activity, appId, stepIndex, totalSteps, callback) {
    return async (data) => {
        const meta = data.metadata;
        const jid = meta?.jid || 'unknown';
        const wfn = meta?.wfn || appId;
        const eventBase = {
            workflowId: jid,
            workflowName: wfn,
            taskQueue: appId,
            activityName: activity.activity_id,
            data: {
                title: activity.title,
                toolName: activity.mcp_tool_name,
                toolSource: activity.tool_source,
                stepIndex,
                totalSteps,
            },
        };
        (0, publish_1.publishActivityEvent)({ type: 'activity.started', ...eventBase });
        try {
            const result = await callback(data);
            (0, publish_1.publishActivityEvent)({ type: 'activity.completed', ...eventBase });
            return result;
        }
        catch (err) {
            logger_1.loggerRegistry.error(`[yaml-worker] ${activity.activity_id} failed: ${err.message}`);
            (0, publish_1.publishActivityEvent)({
                type: 'activity.failed',
                ...eventBase,
                data: { ...eventBase.data, error: err.message },
            });
            // Return the error as data instead of throwing — prevents HotMesh
            // retry storms when the engine reprocesses failed stream messages.
            return {
                metadata: { ...data.metadata },
                data: { error: err.message, is_error: true },
            };
        }
    };
}
