"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.recordPreexistingSnippetExecutor = 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 variable_constants_1 = require("../../sharedUtils/variable-constants");
exports.recordPreexistingSnippetExecutor = {
    needsFind: () => false,
    getStepType: () => mablApi_1.ExecuteToolName.PreexistingSnippet,
    execute: async (payload, stateProvider, eventHandler, logger) => {
        const toolParams = payload.toolCall
            .toolParams;
        if (!toolParams?.snippet_id) {
            logger.error('Record snippet executor requires snippet_id');
            return {
                success: false,
                errorMessage: 'snippet_id parameter is required',
            };
        }
        const snippetId = toolParams.snippet_id;
        const snippetParameters = toolParams.parameters ?? {};
        const saveResultToVariable = toolParams.save_result_to_variable;
        try {
            const snippet = await stateProvider.getSnippet(snippetId);
            if (!snippet) {
                return {
                    success: false,
                    errorMessage: `Snippet with ID ${snippetId} not found`,
                };
            }
            eventHandler.registerSnippet(snippet);
            const parameterOverrides = Object.entries(snippetParameters)
                .map(([paramName, value]) => {
                const snippetParameter = snippet.parameters?.find((param) => param.name === paramName);
                if (!snippetParameter) {
                    logger.warn(`Snippet parameter '${paramName}' not found in snippet ${snippetId}`);
                    return undefined;
                }
                return {
                    id: snippetParameter.id,
                    value: String(value),
                };
            })
                .filter((override) => override !== undefined);
            const isNewStyleSnippet = !!(snippet.id && snippet.invariant_id);
            const javaScriptDescriptor = isNewStyleSnippet
                ? {
                    snippetId: snippet.id,
                    snippetInvariantId: snippet.invariant_id,
                    parameterOverrides,
                }
                : {
                    snippetInvariantId: snippet.invariant_id,
                };
            let step;
            if (saveResultToVariable) {
                const variable = {
                    variableType: mablscriptFind_1.VariableType.JAVASCRIPT,
                    name: `user.${saveResultToVariable}`,
                    humanizedName: saveResultToVariable,
                    value: variable_constants_1.EMPTY_VARIABLE_VALUE_PLACEHOLDER,
                    javaScript: javaScriptDescriptor,
                    snippet,
                };
                step = new CreateVariableStep_1.default(variable);
                eventHandler.saveVariable(variable);
            }
            else {
                step = new EvaluateJSStep_1.default(javaScriptDescriptor, false, undefined, snippet);
            }
            return (0, toolExecutor_types_1.recordStepAndTrackResult)(() => Promise.resolve({ steps: [step], stepsToReplay: 1, step }), 0, stateProvider, eventHandler, logger);
        }
        catch (error) {
            logger.error('Error executing snippet tool:', error);
            return {
                success: false,
                errorMessage: error instanceof Error ? error.message : 'Unknown error',
            };
        }
    },
};
