"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.attemptMigrationToParameterizedStep = attemptMigrationToParameterizedStep;
exports.attemptReusableSnippetParameterization = attemptReusableSnippetParameterization;
exports.hasVariableReferences = hasVariableReferences;
exports.normalizeScript = normalizeScript;
const mablApi_1 = require("../mablApi");
const encodingUtil_1 = require("./encodingUtil");
const esprima = __importStar(require("esprima"));
const escodegen = __importStar(require("escodegen"));
const loggingProvider_1 = require("../providers/logging/loggingProvider");
function attemptMigrationToParameterizedStep(descriptor) {
    let hasVariables;
    let migrationDisabled;
    try {
        const decodedJS = (0, encodingUtil_1.b64DecodeUnicodeInNode)(descriptor.encodedJS);
        migrationDisabled = isMigrationDisabled(decodedJS);
        hasVariables = hasVariableReferences(decodedJS);
    }
    catch (error) {
        loggingProvider_1.logger.warn(`Failed to determine if the inline snippet uses variables: ${error}`);
        return descriptor;
    }
    if (migrationDisabled) {
        return descriptor;
    }
    if (hasVariables) {
        return descriptor;
    }
    loggingProvider_1.logger.info('Converting legacy inline JavaScript step to parameterized step.');
    return migrateInlineDescriptor(descriptor);
}
function migrateInlineDescriptor(descriptor) {
    return {
        inlineSnippet: {
            body: descriptor.encodedJS,
            description: '',
            name: 'Unnamed snippet',
            parameters: [],
            snippet_type: mablApi_1.SnippetTypeEnum.Javascript,
        },
        actionCode: descriptor.actionCode,
        parameterOverrides: [],
    };
}
function attemptReusableSnippetParameterization(snippet) {
    if (Array.isArray(snippet.parameters)) {
        return;
    }
    if (!snippet.body) {
        return;
    }
    let hasVariables;
    let migrationDisabled;
    try {
        const decodedJS = (0, encodingUtil_1.b64DecodeUnicodeInNode)(snippet.body);
        migrationDisabled = isMigrationDisabled(decodedJS);
        hasVariables = hasVariableReferences(decodedJS);
    }
    catch (error) {
        loggingProvider_1.logger.warn(`Failed to determine if the reusable snippet uses variables: ${error}`);
        return;
    }
    if (migrationDisabled) {
        return;
    }
    if (hasVariables) {
        loggingProvider_1.logger.info(`Skipping snippet parameter conversion due to variable usage. Snippet ID: ${snippet.id}`);
        return;
    }
    loggingProvider_1.logger.info(`Migrating legacy snippet to parameterized snippet. Snippet ID: ${snippet.id}`);
    snippet.parameters = [];
}
function isMigrationDisabled(decodedScript) {
    return decodedScript.indexOf('@mabl-disable-parameterization') >= 0;
}
function hasVariableReferences(decodedScript) {
    const normalizedCode = normalizeScript(decodedScript);
    const hasSignature = normalizedCode.indexOf('function mablJavaScriptStep(mablInputs') >= 0;
    if (!hasSignature) {
        throw new Error('Did not find expected mabl JavaScript function signature.');
    }
    const rex = /mablInputs/gi;
    const match = normalizedCode.match(rex);
    const matchCount = match ? match.length : 0;
    return matchCount > 1;
}
function normalizeScript(decodedScript) {
    const tree = esprima.parseScript(decodedScript, { tolerant: true });
    return escodegen.generate(tree);
}
