"use strict";
/**
 * Globals and Snippets Loader
 *
 * Loads shared configuration from:
 * - globals.json - Shared variables across all test files
 * - snippets/ - Reusable block sequences (composite blocks)
 */
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.setGlobalsDirectory = setGlobalsDirectory;
exports.getGlobalsDirectory = getGlobalsDirectory;
exports.loadGlobals = loadGlobals;
exports.getGlobals = getGlobals;
exports.getGlobalVariables = getGlobalVariables;
exports.getGlobalProcedures = getGlobalProcedures;
exports.getTestIdAttribute = getTestIdAttribute;
exports.setTestIdAttribute = setTestIdAttribute;
exports.discoverSnippets = discoverSnippets;
exports.loadSnippet = loadSnippet;
exports.loadAllSnippets = loadAllSnippets;
exports.getSnippet = getSnippet;
exports.getAllSnippets = getAllSnippets;
exports.initializeGlobalsAndSnippets = initializeGlobalsAndSnippets;
exports.clearGlobalsAndSnippets = clearGlobalsAndSnippets;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const core_1 = require("../core");
// Store loaded globals and snippets
let globalsDirectory = process.cwd();
let loadedGlobals = {};
const loadedSnippets = new Map();
/**
 * Set the directory to look for globals.json and snippets/
 */
function setGlobalsDirectory(dir) {
    globalsDirectory = path.isAbsolute(dir) ? dir : path.join(process.cwd(), dir);
}
/**
 * Get the current globals directory
 */
function getGlobalsDirectory() {
    return globalsDirectory;
}
/**
 * Load globals.json from the globals directory
 */
function loadGlobals() {
    const globalsPath = path.join(globalsDirectory, 'globals.json');
    if (!fs.existsSync(globalsPath)) {
        console.log(`No globals.json found at ${globalsPath}`);
        return {};
    }
    try {
        const content = fs.readFileSync(globalsPath, 'utf-8');
        loadedGlobals = JSON.parse(content);
        console.log(`Loaded globals from ${globalsPath}`);
        return loadedGlobals;
    }
    catch (error) {
        console.error(`Failed to load globals.json:`, error);
        return {};
    }
}
/**
 * Get the loaded globals
 */
function getGlobals() {
    return loadedGlobals;
}
/**
 * Get global variables
 */
function getGlobalVariables() {
    return loadedGlobals.variables || {};
}
/**
 * Get global procedures from globals.json
 */
function getGlobalProcedures() {
    return loadedGlobals.procedures || {};
}
/**
 * Get the configured test ID attribute (defaults to 'data-testid')
 */
function getTestIdAttribute() {
    return loadedGlobals.testIdAttribute || 'data-testid';
}
/**
 * Set the test ID attribute and persist to globals.json
 */
function setTestIdAttribute(attribute) {
    const config = loadedGlobals;
    config.testIdAttribute = attribute;
    saveGlobals();
}
/**
 * Save globals.json to disk
 */
function saveGlobals() {
    const globalsPath = path.join(globalsDirectory, 'globals.json');
    try {
        fs.writeFileSync(globalsPath, JSON.stringify(loadedGlobals, null, 2), 'utf-8');
        console.log(`Saved globals to ${globalsPath}`);
    }
    catch (error) {
        console.error(`Failed to save globals.json:`, error);
    }
}
/**
 * Discover snippet files in the snippets directory
 */
function discoverSnippets() {
    const snippetsDir = path.join(globalsDirectory, 'snippets');
    if (!fs.existsSync(snippetsDir)) {
        console.log(`No snippets directory found at ${snippetsDir}`);
        return [];
    }
    const files = fs.readdirSync(snippetsDir);
    const snippets = [];
    for (const file of files) {
        if (file.endsWith('.snippet.json') || file.endsWith('.testblocks.json')) {
            const snippetName = file.replace(/\.(snippet|testblocks)\.json$/, '');
            snippets.push(snippetName);
        }
    }
    console.log(`Discovered ${snippets.length} snippet(s): ${snippets.join(', ')}`);
    return snippets;
}
/**
 * Load a specific snippet by name
 */
function loadSnippet(snippetName) {
    if (loadedSnippets.has(snippetName)) {
        return loadedSnippets.get(snippetName);
    }
    const snippetsDir = path.join(globalsDirectory, 'snippets');
    const snippetPath = path.join(snippetsDir, `${snippetName}.snippet.json`);
    const altPath = path.join(snippetsDir, `${snippetName}.testblocks.json`);
    let filePath = null;
    if (fs.existsSync(snippetPath)) {
        filePath = snippetPath;
    }
    else if (fs.existsSync(altPath)) {
        filePath = altPath;
    }
    if (!filePath) {
        console.error(`Snippet not found: ${snippetName}`);
        return null;
    }
    try {
        const content = fs.readFileSync(filePath, 'utf-8');
        const snippet = JSON.parse(content);
        // Ensure name is set
        if (!snippet.name) {
            snippet.name = snippetName;
        }
        loadedSnippets.set(snippetName, snippet);
        console.log(`Loaded snippet: ${snippetName}`);
        // Register as a block
        registerSnippetAsBlock(snippet);
        return snippet;
    }
    catch (error) {
        console.error(`Failed to load snippet ${snippetName}:`, error);
        return null;
    }
}
/**
 * Load all discovered snippets
 */
function loadAllSnippets() {
    const snippetNames = discoverSnippets();
    for (const name of snippetNames) {
        loadSnippet(name);
    }
}
/**
 * Register a snippet as a custom composite block
 */
function registerSnippetAsBlock(snippet) {
    const blockType = `snippet_${snippet.name.toLowerCase().replace(/[^a-z0-9]/g, '_')}`;
    // Check if already registered
    if ((0, core_1.getBlock)(blockType)) {
        return;
    }
    const blockDef = {
        type: blockType,
        category: snippet.category || 'Snippets',
        color: snippet.color || '#795548',
        tooltip: snippet.description || `Snippet: ${snippet.name}`,
        inputs: (snippet.params || []).map(param => ({
            name: param.name.toUpperCase(),
            type: 'field',
            fieldType: param.type === 'number' ? 'number' : 'text',
            default: param.default,
        })),
        previousStatement: true,
        nextStatement: true,
        execute: async (params, context) => {
            context.logger.info(`Executing snippet: ${snippet.name}`);
            // Set snippet parameters as variables
            if (snippet.params) {
                for (const param of snippet.params) {
                    const value = params[param.name.toUpperCase()] ?? param.default;
                    context.variables.set(`snippet_${param.name}`, value);
                }
            }
            // Return the steps to be executed by the executor
            return {
                compoundAction: `snippet:${snippet.name}`,
                steps: snippet.steps,
                _summary: `Run snippet: ${snippet.name}`,
            };
        },
    };
    (0, core_1.registerBlock)(blockDef);
    console.log(`Registered snippet block: ${blockType}`);
}
/**
 * Get a loaded snippet by name
 */
function getSnippet(snippetName) {
    return loadedSnippets.get(snippetName);
}
/**
 * Get all loaded snippets
 */
function getAllSnippets() {
    return Array.from(loadedSnippets.values());
}
/**
 * Initialize globals and snippets from a directory
 */
function initializeGlobalsAndSnippets(dir) {
    if (dir) {
        setGlobalsDirectory(dir);
    }
    loadGlobals();
    loadAllSnippets();
}
/**
 * Clear loaded globals and snippets
 */
function clearGlobalsAndSnippets() {
    loadedGlobals = {};
    loadedSnippets.clear();
}
