{
  config,
  lib,
  namespace,
  ...
}:
with lib;
let
  # inherit (lib.${namespace}) mkModule mkOpt mkBoolOpt enableForSystem;
  cfg = config.${namespace}.services.grafana;
  upsUser = "nas-admin";
in
{
  options.${namespace}.services.grafana = {
    enable = mkEnableOption "enable grafana";
  };

  config = lib.mkIf cfg.enable {
    services = {
      prometheus = {
        enable = true;
        exporters = {
          node = {
            enable = true;
            enabledCollectors = [
              "filesystem"
              "diskstats"
              "meminfo"
              "cpu"
              "systemd" # Ensures systemd collector is enabled
              "processes"
            ];
            extraFlags = [
              "--collector.filesystem.mount-points-exclude=^/(dev|proc|sys|run)($|/)"
            ];
          };
          libvirt = {
            enable = false;
            openFirewall = true;
          };
          nut = {
            enable = true;
            openFirewall = true;
            passwordPath = config.sops.secrets."jallen-nas/ups_password".path;
            nutUser = upsUser;
          };
          # restic = {
          #   enable = true;
          #   openFirewall = true;
          #   resticPort = 8008;
          # };
        };
        scrapeConfigs = [
          {
            job_name = "node";
            static_configs = [
              {
                targets = [ "localhost:${toString config.services.prometheus.exporters.node.port}" ];
              }
            ];
          }
          {
            job_name = "traefik";
            static_configs = [
              {
                targets = [ "localhost:8082" ];
              }
            ];
          }
        ];
      };

      grafana = {
        enable = true;
        settings = {
          server = {
            http_port = 9999;
            http_addr = "0.0.0.0";
          };
        };

        dataDir = "/media/nas/main/nix-app-data/grafana";

        provision = {
          enable = true;
          datasources.settings.datasources = [
            {
              name = "Prometheus";
              type = "prometheus";
              access = "proxy";
              url = "http://localhost:${toString config.services.prometheus.port}";
            }
          ];
        };
      };
    };
    # Open firewall ports for Grafana
    networking.firewall = {
      allowedTCPPorts = [ 9999 ];
      allowedUDPPorts = [ 9999 ];
    };
  };
}
