/**
 * Helper utilities for built-in function and constant lookup/validation.
 */

import { BuiltInFunctions } from "./functionsRegistry.js";
import { BuiltInGlobalVariables } from "./globalVariablesRegistry.js";

function getFunctionReturnType(functionName) {
    const upperName = functionName.toUpperCase();
    const func = BuiltInFunctions[upperName];
    return func ? func.returns : null;
}

/**
 * Gets function signature information.
 * @param {string} functionName - The function name
 * @returns {Object|null} - Function signature or null
 */
function getFunctionSignature(functionName) {
    const upperName = functionName.toUpperCase();
    return BuiltInFunctions[upperName] || null;
}

/**
 * Checks if an identifier is a built-in constant.
 * @param {string} name - The identifier name
 * @returns {boolean} - True if it's a built-in constant
 */
function isBuiltInGlobalVariable(name) {
    const upperName = name.toUpperCase();
    return Object.prototype.hasOwnProperty.call(BuiltInGlobalVariables, upperName);
}

/**
 * Gets the type of a built-in constant.
 * @param {string} name - The constant name (case-insensitive)
 * @returns {string|null} - The constant type or null if not found
 */
function getGlobalVariableType(name) {
    const upperName = name.toUpperCase();
    return BuiltInGlobalVariables[upperName]?.type || null;
}

/**
 * Validates function call arguments.
 * @param {string} functionName - The function name
 * @param {string[]} argTypes - Array of argument types
 * @returns {Object} - { valid: boolean, error: string|null }
 */
function validateFunctionCall(functionName, argTypes) {
    const signature = getFunctionSignature(functionName);
    
    if (!signature) {
        return { valid: true, error: null }; // Unknown function, allow it
    }

    if (signature.varArgs) {
        return { valid: true, error: null }; // Variable args, allow any count
    }

    if (argTypes.length !== signature.params.length) {
        return {
            valid: false,
            error: `${functionName} expects ${signature.params.length} argument(s), but ${argTypes.length} provided`
        };
    }

    // Type checking could be added here for known types
    return { valid: true, error: null };
}

export {
    getFunctionReturnType,
    getFunctionSignature,
    isBuiltInGlobalVariable,
    getGlobalVariableType,
    validateFunctionCall
};
