"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordFlowExecutor = void 0;
const variable_utils_1 = require("../../sharedUtils/variable-utils");
const toolExecutor_types_1 = require("../toolExecutor-types");
const generation_types_1 = require("../../sharedUtils/generation-types");
const RecordCreateVariableExecutor_1 = require("./RecordCreateVariableExecutor");
function qualifyIterationValue(iterationType, iterationValue) {
    if (iterationType === 'variable' && !iterationValue.includes('.')) {
        return `user.${iterationValue}`;
    }
    return iterationValue;
}
exports.recordFlowExecutor = {
    needsFind: () => false,
    getStepType: () => 'flow',
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const flowId = (0, generation_types_1.getFlowIdForRecordFlowStep)(payload.toolCall);
        if (!flowId) {
            logger.error('Record Flow executor requires flow id');
            return {
                success: false,
            };
        }
        const flow = await stateProvider.getFlow(flowId);
        if (!flow) {
            logger.error(`Record Flow executor requires flow ${flowId}`);
            return {
                success: false,
            };
        }
        let flowParameterOverrides;
        const toolParams = payload.toolCall
            .toolParams;
        const parameters = toolParams?.parameters ?? {};
        const iterationConfig = toolParams?.loop
            ? {
                iteration_type: toolParams.loop.iteration_type,
                iteration_value: qualifyIterationValue(toolParams.loop.iteration_type, toolParams.loop.iteration_value),
            }
            : undefined;
        const createdVariables = {};
        if (flow.parameters?.length) {
            flowParameterOverrides = parameters;
        }
        else if (flow.variables?.inputs?.length) {
            flowParameterOverrides = {};
            const variablesList = (0, variable_utils_1.getUsableVariablesAsList)(stateProvider.getVariables(), stateProvider.getNextStepIndex());
            const contextInfo = await stateProvider.getActiveContextInfo();
            const variablesToCreate = [];
            Object.entries(parameters).forEach(([key, value]) => {
                const variableName = key;
                const requestedVariableValue = value;
                let variableShouldBeSet = true;
                for (const variable of variablesList) {
                    if (variable.humanizedName === variableName) {
                        if (variable.value === requestedVariableValue) {
                            variableShouldBeSet = false;
                        }
                        if (!variable.name.startsWith('user')) {
                            variableShouldBeSet = false;
                        }
                    }
                }
                if (variableShouldBeSet) {
                    variablesToCreate.push({
                        name: variableName,
                        value: requestedVariableValue,
                    });
                }
            });
            for (const variable of variablesToCreate) {
                await (0, RecordCreateVariableExecutor_1.generateVariableStep)(eventHandler, stateProvider, variable.name, variable.value, contextInfo);
                const resolvedValue = (0, variable_utils_1.getResolvedUserVariableValue)(stateProvider.getVariables(), variable.name, variable.value);
                createdVariables[variable.name] = resolvedValue;
            }
        }
        else {
            flowParameterOverrides = {};
        }
        await eventHandler.insertFlowAndReplay(flow, flowParameterOverrides, iterationConfig);
        const { success, errorMessage } = (0, toolExecutor_types_1.isReplayResponsePassed)(stateProvider);
        const result = {
            success,
            errorMessage,
        };
        if (Object.keys(createdVariables).length > 0) {
            result.created_variables = createdVariables;
        }
        if (!success) {
            const failure = stateProvider.getLastFlowFailure();
            if (failure && failure.failedSteps.length > 0) {
                result.failed_step_details = failure.failedSteps.map((step) => ({
                    stepPath: step.stepPath,
                    stepDescription: step.stepDescription,
                    reason: step.reason,
                }));
                const screenshots = failure.failedSteps
                    .filter((step) => typeof step.screenshot === 'string' && step.screenshot.length > 0)
                    .map((step) => ({
                    type: 'image-data',
                    image_data: step.screenshot,
                    media_type: 'image/png',
                }));
                if (screenshots.length > 0) {
                    result.imageContentItems = screenshots;
                }
            }
        }
        return result;
    },
};
