"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordCreateSnippetExecutor = void 0;
const toolExecutor_types_1 = require("../toolExecutor-types");
const CreateVariableStep_1 = __importDefault(require("../../sharedUtils/mablscript/canonical/CreateVariableStep"));
const EvaluateJSStep_1 = __importDefault(require("../../sharedUtils/mablscript/canonical/EvaluateJSStep"));
const mablscriptFind_1 = require("@mablhq/test-model/mablscriptFind");
const mablApi_1 = require("../../../mablApi");
const encodingUtil_1 = require("../../../util/encodingUtil");
const variable_constants_1 = require("../../sharedUtils/variable-constants");
const variableCanonical_1 = require("@mablhq/test-model/variableCanonical");
exports.recordCreateSnippetExecutor = {
    needsFind: () => false,
    getStepType: () => mablApi_1.ExecuteToolName.Javascript,
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall
            .toolParams;
        if (!toolParams?.snippet_body) {
            logger.error('Record create snippet executor requires snippet_body');
            return {
                success: false,
                errorMessage: 'snippet_body parameter is required',
            };
        }
        const { snippet_body: snippetBody, snippet_name: snippetName, snippet_description: snippetDescription, save_result_to_variable: saveResultToVariable, parameters: snippetParameters, record_step: recordStep, } = toolParams;
        if (recordStep === false) {
            if (saveResultToVariable) {
                return {
                    success: false,
                    errorMessage: 'record_step is false, so save_result_to_variable cannot be used (there ' +
                        'is no step to attach a variable to). Read the value from `result`, or set ' +
                        'record_step to true to persist the result as a variable.',
                };
            }
            if (!eventHandler.evaluateSnippet) {
                logger.error('Event handler does not support evaluateSnippet (record_step: false)');
                return {
                    success: false,
                    errorMessage: 'Running a snippet without recording a step is not supported in this ' +
                        'environment. Set record_step to true to record the snippet as a step.',
                };
            }
            try {
                const { result, currentUrl } = await eventHandler.evaluateSnippet(snippetBody);
                return {
                    success: true,
                    message: 'Snippet evaluated without recording a step.',
                    result,
                    current_url: currentUrl,
                };
            }
            catch (error) {
                logger.error('Error evaluating snippet:', error);
                return {
                    success: false,
                    errorMessage: error instanceof Error ? error.message : 'Unknown error',
                };
            }
        }
        try {
            const snippetParameterDefinitions = [];
            const parameterOverrides = [];
            if (snippetParameters) {
                for (const [name, value] of Object.entries(snippetParameters)) {
                    snippetParameterDefinitions.push({ id: name, name });
                    parameterOverrides.push({ id: name, value: String(value) });
                }
            }
            const inlineSnippet = {
                snippet_type: 'javascript',
                body: (0, encodingUtil_1.b64EncodeUnicodeInNode)(snippetBody),
                name: snippetName,
                description: snippetDescription,
                parameters: snippetParameterDefinitions,
            };
            const javaScriptDescriptor = {
                inlineSnippet,
                parameterOverrides,
            };
            let step;
            if (saveResultToVariable) {
                const variable = {
                    variableType: mablscriptFind_1.VariableType.JAVASCRIPT,
                    name: `user.${saveResultToVariable}`,
                    humanizedName: saveResultToVariable,
                    value: variable_constants_1.EMPTY_VARIABLE_VALUE_PLACEHOLDER,
                    flowStepIndex: [],
                    readOnly: false,
                    javaScript: javaScriptDescriptor,
                    snippet: inlineSnippet,
                };
                step = new CreateVariableStep_1.default(variable);
                eventHandler.saveVariable(variable);
            }
            else {
                step = new EvaluateJSStep_1.default(javaScriptDescriptor, false, undefined, inlineSnippet);
            }
            const result = await (0, toolExecutor_types_1.recordStepAndTrackResult)(() => Promise.resolve({ steps: [step], stepsToReplay: 1, step }), 0, stateProvider, eventHandler, logger);
            if (!saveResultToVariable) {
                return result;
            }
            const existingVariable = (0, variableCanonical_1.flattenVariables)(stateProvider.getVariables())[`user.${saveResultToVariable}`];
            const rawValue = existingVariable?.value;
            const hasRealValue = rawValue !== undefined && rawValue !== variable_constants_1.EMPTY_VARIABLE_VALUE_PLACEHOLDER;
            if (hasRealValue && existingVariable) {
                eventHandler.saveVariable({
                    ...existingVariable,
                    value: rawValue,
                });
            }
            const variableValue = !hasRealValue
                ? variable_constants_1.EMPTY_VARIABLE_VALUE_PLACEHOLDER
                : typeof rawValue === 'string'
                    ? rawValue
                    : JSON.stringify(rawValue);
            return {
                ...result,
                variable_name: saveResultToVariable,
                variable_value: variableValue,
            };
        }
        catch (error) {
            logger.error('Error executing create snippet tool:', error);
            return {
                success: false,
                errorMessage: error instanceof Error ? error.message : 'Unknown error',
            };
        }
    },
};
