llmApp.factory('DescParamsService', [function () {
    var service = {};
    var registeredDescParams = null;



    // Parent controller calls this to register the desc params
    service.registerDescParams = function (scope) {
        if (scope && scope.$parent && scope.$parent.$parent &&
            scope.$parent.$parent.desc && scope.$parent.$parent.desc.params) {
            registeredDescParams = scope.$parent.$parent.desc.params;
        }
    };

    service.getParamConfigByName = function (name) {
        if (!registeredDescParams) {
            console.warn("DescParamsService: getParamConfigByName called before params were registered.");
            return null;
        }

        // Use a simple, non-recursive find on the top-level array
        return registeredDescParams.find(p => p.name === name) || null;
    };



    // Children controllers call this to get the desc params
    service.getDescParams = function () {
        return registeredDescParams;
    };

    service.getSelectChoices = function (fieldName) {
        if (!registeredDescParams) {
            return null;
        }

        // Find the field by name
        const field = registeredDescParams.find(item => item.name === fieldName && item.type === "SELECT");

        // Return the selectChoices array or empty array if not found
        return field ? field.selectChoices : [];
    };

    // Optional: Update the registered params
    service.setDescParams = function (params) {
        registeredDescParams = params;
    };

    service.getDefaultValue = function (paramName) {
        if (!registeredDescParams) {
            return null;
        }

        function findParamRecursive(params, name) {
            for (const param of params) {
                if (param.name === name) {
                    return param;
                }
                if (param.subParams) {
                    const found = findParamRecursive(param.subParams, name);
                    if (found) {
                        return found;
                    }
                }
            }
            return null;
        }

        const param = findParamRecursive(registeredDescParams, paramName);

        // Return explicit default value if it exists
        if (param && param.hasOwnProperty('defaultValue')) {
            return param.defaultValue;
        }

        return null;
    };




    return service;
}]);