/**
 * Risk Management Generators Definitions
 *
 * This file contains generator functions for each block defined in
 * risk_management_blocks.js. Each generator translates a Blockly block into a JSON
 * object representing risk management operations.
 */

export function defineRiskManagementGenerators() {

    // Ensure the base generator is initialized
    if (!Blockly.JSON) {
        console.error("Blockly.JSON not initialized.");
        return;
    }

    /**
     * Helper Function: processNumericInput
     * Processes a numeric input and returns the value.
     *
     * @param {Blockly.Block} block - The block containing the input.
     * @param {string} inputName - The name of the input field.
     * @param {*} defaultValue - The default value to use if the input is invalid.
     * @returns {*} - The value from the input.
     */
    Blockly.JSON.processNumericInput = function(block, inputName, defaultValue) {
        const inputBlock = block.getInputTargetBlock(inputName);
        if (inputBlock) {
            const generator = Blockly.JSON[inputBlock.type];
            if (typeof generator === 'function') {
                const inputJson = generator(inputBlock);

                // Handle dynamic_value
                if (inputJson && inputJson.type === 'dynamic_value' && Array.isArray(inputJson.values)) {
                    const firstValue = inputJson.values[0];
                    if (typeof firstValue === 'number' || typeof firstValue === 'object') {
                        return firstValue;
                    } else {
                        console.warn(`Invalid value in '${inputName}'. Using default value ${defaultValue}.`);
                        return defaultValue;
                    }
                } else if (typeof inputJson === 'number' || typeof inputJson === 'object') {
                    return inputJson;
                } else {
                    console.warn(`Invalid input for '${inputName}'. Using default value ${defaultValue}.`);
                    return defaultValue;
                }
            } else {
                console.warn(`No generator found for block type '${inputBlock.type}'. Using default value ${defaultValue}.`);
                return defaultValue;
            }
        } else {
            console.warn(`No block connected to '${inputName}'. Using default value ${defaultValue}.`);
            return defaultValue;
        }
    };

    /**
     * Generator for 'set_leverage' Block
     */
    Blockly.JSON['set_leverage'] = function(block) {
        // Process the 'LEVERAGE' input using processNumericInput
        const leverageValue = Blockly.JSON.processNumericInput(block, 'LEVERAGE', 1);

        // Validate the leverage value
        let leverage = leverageValue;

        if (typeof leverageValue === 'number') {
            // Enforce limits (e.g., leverage between 1 and 100)
            if (leverageValue < 1) {
                console.warn(`Leverage value too low. Clamping to 1.`);
                leverage = 1;
            } else if (leverageValue > 100) {
                console.warn(`Leverage value too high. Clamping to 100.`);
                leverage = 100;
            }
        } else if (typeof leverageValue === 'object' && leverageValue !== null) {
            // Include the object directly (e.g., if it's an operation)
            leverage = leverageValue;
        } else {
            console.warn(`Invalid leverage value. Defaulting to 1.`);
            leverage = 1;
        }

        // Create operation object
        const json = {
            type: 'set_leverage',
            inputs: {
                LEVERAGE: leverage
            }
        };

        // Return the operation object directly
        return json;
    };

    /**
     * Generator for 'current_margin' Block
     */
    Blockly.JSON['current_margin'] = function(block) {
        // Create operation object
        const json = {
            type: 'current_margin',
            inputs: {}
        };

        // Return the operation object directly
        return json;
    };

    /**
     * Generator for 'risk_ratio' Block
     */
    Blockly.JSON['risk_ratio'] = function(block) {
        // Create operation object
        const json = {
            type: 'risk_ratio',
            inputs: {}
        };

        // Return the operation object directly
        return json;
    };

    /**
     * Generator for 'max_position_size' Block
     */
    Blockly.JSON['max_position_size'] = function(block) {
        // Process the 'MAX_SIZE' input using processNumericInput
        const maxSizeValue = Blockly.JSON.processNumericInput(block, 'MAX_SIZE', 1);

        let maxSize = maxSizeValue;

        if (typeof maxSizeValue === 'number') {
            // Enforce limits (e.g., minimum of 1)
            if (maxSizeValue < 1) {
                console.warn(`Max position size too low. Clamping to 1.`);
                maxSize = 1;
            }
        } else if (typeof maxSizeValue === 'object' && maxSizeValue !== null) {
            // Include the object directly (e.g., if it's an operation)
            maxSize = maxSizeValue;
        } else {
            console.warn(`Invalid max position size value. Defaulting to 1.`);
            maxSize = 1;
        }

        // Create operation object
        const json = {
            type: 'max_position_size',
            inputs: {
                MAX_SIZE: maxSize
            }
        };

        // Return the action object directly
        return json;
    };
}
