"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordCreateVariableExecutor = void 0;
exports.generateVariableStep = generateVariableStep;
const toolExecutor_types_1 = require("../toolExecutor-types");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const stepCapture_1 = require("../../background/capture/stepCapture");
const variable_utils_1 = require("../../sharedUtils/variable-utils");
const DEFAULT_ELEMENT_PROPERTY = 'innerText';
exports.recordCreateVariableExecutor = {
    needsFind: (toolCall) => {
        const toolParams = toolCall.toolParams;
        if (!isCreateVariableParams(toolParams)) {
            return false;
        }
        return !!toolParams.elementBoundingBox || !!toolParams.customFind;
    },
    getStepType: () => 'create_variable',
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall.toolParams;
        if (!isCreateVariableParams(toolParams)) {
            logger.error('Record create variable executor requires appropriate parameters');
            return {
                success: false,
            };
        }
        if (toolParams.elementBoundingBox || toolParams.customFind) {
            if (!payload.find ||
                !payload.contextInfo ||
                !(0, toolExecutor_types_1.isFindOneEventMessage)(payload.find)) {
                logger.error('Record create variable executor requires find and contextInfo');
                return {
                    success: false,
                };
            }
        }
        const target = (0, toolExecutor_types_1.isFindOneEventMessage)(payload.find)
            ? payload.find
            : undefined;
        if (target && target.availableAttrProps === undefined) {
            target.availableAttrProps = {
                [DEFAULT_ELEMENT_PROPERTY]: toolParams.variableValue ?? '',
            };
        }
        const contextInfo = payload.contextInfo ?? (await stateProvider.getActiveContextInfo());
        const result = await (0, toolExecutor_types_1.recordStepAndTrackResult)(() => generateVariableStep(eventHandler, stateProvider, toolParams.variableName, toolParams.variableValue, contextInfo, target, payload.toolCall.toolDescription), 0, stateProvider, eventHandler, logger);
        const resolvedValue = (0, variable_utils_1.getResolvedUserVariableValue)(stateProvider.getVariables(), toolParams.variableName, toolParams.variableValue);
        const variableName = `user.${toolParams.variableName}`;
        const existingVariable = stateProvider.getVariables()[variableName];
        if (existingVariable) {
            eventHandler.saveVariable({
                ...existingVariable,
                value: resolvedValue,
            });
        }
        return {
            ...result,
            variable_name: toolParams.variableName,
            variable_value: resolvedValue,
        };
    },
};
async function generateVariableStep(eventHandler, stateProvider, variableName, variableValue, contextInfo, target, descriptionOverride) {
    if (!stateProvider) {
        throw new Error('stateProvider is required for generateVariableStep');
    }
    const variable = target
        ? {
            variableType: mablscriptFind_1.VariableType.ELEMENT_PROPERTY,
            name: `user.${variableName}`,
            property: DEFAULT_ELEMENT_PROPERTY,
            value: variableValue,
            flowStepIndex: [],
            humanizedName: variableName,
            source: mablscriptFind_1.LegacyVariableSource.TEMPLATE,
            readOnly: false,
            maskDisplay: false,
        }
        : {
            variableType: mablscriptFind_1.VariableType.GENERATED,
            name: `user.${variableName}`,
            pattern: variableValue,
            value: variableValue,
            flowStepIndex: [],
            humanizedName: variableName,
            source: mablscriptFind_1.LegacyVariableSource.TEMPLATE,
            readOnly: false,
            maskDisplay: false,
        };
    const variableAction = {
        action: 'set-variable',
        listener: 'set-variable',
        variable: target
            ? {
                ...variable,
                target,
            }
            : variable,
    };
    eventHandler.saveVariable(variable);
    return (0, stepCapture_1.recordTrainedStep)(variableAction, contextInfo, true, descriptionOverride, stateProvider, eventHandler);
}
function isCreateVariableParams(toolParams) {
    return toolParams?.variableName !== undefined;
}
