// Copyright (c) 2026 Hellmai Ltd
// SPDX-License-Identifier: AGPL-3.0-only
import { getErrorMessage } from '@lumenflow/core/error-handler';
import { LUMENFLOW_WU_TOOL_ENV } from '@lumenflow/core/micro-worktree';
import { emitWUFlowEvent } from '@lumenflow/core/telemetry';
function resolveEventFields(builder, value) {
    if (!builder) {
        return {};
    }
    return typeof builder === 'function' ? builder(value) : builder;
}
export function emitWuCommandEvent(context, event) {
    emitWUFlowEvent({
        script: context.script,
        ...(context.wuId ? { wu_id: context.wuId } : {}),
        ...(context.lane ? { lane: context.lane } : {}),
        ...event,
    });
}
export async function withWuToolEnv(toolName, fn) {
    const previousWuTool = process.env[LUMENFLOW_WU_TOOL_ENV];
    process.env[LUMENFLOW_WU_TOOL_ENV] = toolName;
    try {
        return await fn();
    }
    finally {
        if (previousWuTool === undefined) {
            Reflect.deleteProperty(process.env, LUMENFLOW_WU_TOOL_ENV);
        }
        else {
            process.env[LUMENFLOW_WU_TOOL_ENV] = previousWuTool;
        }
    }
}
export async function runWuMutationCommand(options) {
    const execute = typeof options.toolName === 'string' && options.toolName.length > 0
        ? () => withWuToolEnv(options.toolName, options.execute)
        : options.execute;
    try {
        const result = await execute();
        emitWuCommandEvent(options.context, {
            step: options.step,
            outcome: 'success',
            ...resolveEventFields(options.success, result),
        });
        return result;
    }
    catch (error) {
        emitWuCommandEvent(options.context, {
            step: options.step,
            outcome: 'error',
            error_message: getErrorMessage(error),
            ...resolveEventFields(options.failure, error),
        });
        throw error;
    }
}
//# sourceMappingURL=wu-command-harness.js.map