"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordCountElementsExecutor = void 0;
const toolExecutor_types_1 = require("../toolExecutor-types");
const stepCapture_1 = require("../../background/capture/stepCapture");
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const variable_constants_1 = require("../../sharedUtils/variable-constants");
function buildCountFindDescriptor(selectorType, selector) {
    const primarySelectors = {
        uuid: '',
        ...(selectorType === 'xpath' ? { xpath: selector } : { css_query: selector }),
    };
    const foundElementSelectors = {
        uuid: '',
        selector_type: 'element',
        ...(selectorType === 'xpath' ? { xpath: selector } : { css_query: selector }),
    };
    return {
        type: 'find_all',
        primarySelectors,
        foundElementSelectors,
    };
}
exports.recordCountElementsExecutor = {
    needsFind: () => false,
    getStepType: () => 'create_variable',
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall.toolParams;
        if (!toolParams?.variableName ||
            !toolParams.selector ||
            (toolParams.selectorType !== 'css' && toolParams.selectorType !== 'xpath')) {
            logger.error('RecordCountElementsExecutor requires variableName, selector, and selectorType');
            return { success: false };
        }
        const variableName = toolParams.variableName;
        const namespacedName = `user.${variableName}`;
        const variable = {
            variableType: mablscriptFind_1.VariableType.ELEMENT_COUNT,
            name: namespacedName,
            humanizedName: variableName,
            value: variable_constants_1.EMPTY_VARIABLE_VALUE_PLACEHOLDER,
            flowStepIndex: [],
            source: mablscriptFind_1.LegacyVariableSource.TEMPLATE,
            readOnly: false,
            maskDisplay: false,
        };
        const findDescriptor = buildCountFindDescriptor(toolParams.selectorType, toolParams.selector);
        const action = {
            action: 'set-variable',
            listener: 'set-variable',
            variable,
            findDescriptor,
        };
        eventHandler.saveVariable(variable);
        const contextInfo = await stateProvider.getActiveContextInfo();
        const result = await (0, toolExecutor_types_1.recordStepAndTrackResult)(() => (0, stepCapture_1.recordTrainedStep)(action, contextInfo, true, payload.toolCall.toolDescription, stateProvider, eventHandler), 0, stateProvider, eventHandler, logger);
        return {
            ...result,
            variable_name: variableName,
            variable_value: variable_constants_1.EMPTY_VARIABLE_VALUE_PLACEHOLDER,
        };
    },
};
