{lib}: let
  inherit (lib) flatten mapAttrs attrValues filterAttrs mapAttrsToList filter groupBy length unique attrByPath splitString;

  # Generic function to aggregate any attribute across nodes
  aggregateFromNodes = {
    nodes,
    attributePath, # e.g. "homelab.monitoring.metrics" or "homelab.backups.jobs"
    enhancer ? null, # optional function to enhance each item with node context
  }: let
    # Extract the attribute from each node using the path
    getNestedAttr = path: config: let
      pathList = splitString "." path;
    in
      attrByPath pathList [] config;

    # Get all items from all nodes
    allItems = flatten (mapAttrsToList
      (nodeName: nodeConfig: let
        items = getNestedAttr attributePath nodeConfig.config;
        baseEnhancer = item:
          item
          // {
            _nodeName = nodeName;
            _nodeConfig = nodeConfig;
            _nodeAddress = nodeConfig.config.networking.hostName or nodeName;
          };
        finalEnhancer =
          if enhancer != null
          then (item: enhancer (baseEnhancer item))
          else baseEnhancer;
      in
        map finalEnhancer items)
      nodes);
  in {
    # Raw aggregated data
    all = allItems;

    # Common grouping patterns
    byNode = groupBy (item: item._nodeName) allItems;
    byType = groupBy (item: item.type or "unknown") allItems;
    byService = groupBy (item: item.service or "unknown") allItems;

    # Utility functions for filtering
    filterBy = predicate: filter predicate allItems;
    ofType = type: filter (item: (item.type or "") == type) allItems;
    ofNode = nodeName: filter (item: item._nodeName == nodeName) allItems;
    enabled = filter (item: item.enabled or true) allItems;

    # Counting utilities
    count = length allItems;
    countBy = fn: mapAttrs (key: items: length items) (groupBy fn allItems);
  };
in {
  inherit aggregateFromNodes;
}
