"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BlocklyParser = void 0;
/**
 * Utility class for parsing Blockly state into TestSteps
 */
class BlocklyParser {
    /**
     * Extract steps from Blockly serialization state or direct step array
     */
    static extractSteps(state) {
        if (!state || typeof state !== 'object')
            return [];
        const stateObj = state;
        // Handle Blockly serialization format
        if ('blocks' in stateObj && typeof stateObj.blocks === 'object') {
            const blocks = stateObj.blocks;
            if ('blocks' in blocks && Array.isArray(blocks.blocks)) {
                return this.blocksToSteps(blocks.blocks);
            }
        }
        // Handle direct array of steps
        if (Array.isArray(state)) {
            return state;
        }
        return [];
    }
    /**
     * Convert Blockly blocks array to TestSteps
     */
    static blocksToSteps(blocks) {
        const steps = [];
        for (const block of blocks) {
            const step = this.blockToStep(block);
            if (step) {
                steps.push(step);
                // Handle next block in chain
                let currentBlock = block;
                while (currentBlock.next) {
                    const nextBlock = currentBlock.next.block;
                    const nextStep = this.blockToStep(nextBlock);
                    if (nextStep) {
                        steps.push(nextStep);
                    }
                    currentBlock = nextBlock;
                }
            }
        }
        return steps;
    }
    /**
     * Convert a single Blockly block to a TestStep
     */
    static blockToStep(block) {
        if (!block || !block.type)
            return null;
        const step = {
            id: block.id || `step-${Date.now()}`,
            type: block.type,
            params: {},
        };
        // Extract field values
        if (block.fields && typeof block.fields === 'object') {
            for (const [name, value] of Object.entries(block.fields)) {
                step.params[name] = value;
            }
        }
        // Extract inputs (connected blocks)
        if (block.inputs && typeof block.inputs === 'object') {
            for (const [name, input] of Object.entries(block.inputs)) {
                const inputObj = input;
                if (inputObj.block) {
                    // Recursively convert connected block
                    const connectedStep = this.blockToStep(inputObj.block);
                    if (connectedStep) {
                        step.params[name] = connectedStep;
                    }
                }
            }
        }
        return step;
    }
}
exports.BlocklyParser = BlocklyParser;
