{
  config,
  lib,
  pkgs,
  ...
}:
with lib; let
  cfg = config.homelab.services.alertmanager;
  homelabCfg = config.homelab;

  # Default alertmanager configuration
  defaultConfig = {
    global = {
      smtp_smarthost = cfg.smtp.host;
      smtp_from = cfg.smtp.from;
      smtp_auth_username = cfg.smtp.username;
      smtp_auth_password = cfg.smtp.password;
    };

    # Inhibit rules to prevent spam
    inhibit_rules = [
      {
        source_match = {
          severity = "critical";
        };
        target_match = {
          severity = "warning";
        };
        equal = ["alertname" "dev" "instance"];
      }
    ];

    route = {
      group_by = ["alertname"];
      group_wait = "10s";
      group_interval = "10s";
      repeat_interval = "1h";
      receiver = "web.hook";
      routes = cfg.routes;
    };

    receivers =
      [
        {
          name = "web.hook";
          webhook_configs = [
            {
              url = "http://127.0.0.1:5001/";
            }
          ];
        }
      ]
      ++ cfg.receivers;
  };

  # Merge with user config
  alertmanagerConfig = recursiveUpdate defaultConfig cfg.extraConfig;
in {
  options.homelab.services.alertmanager = {
    enable = mkEnableOption "Alertmanager for handling alerts";

    port = mkOption {
      type = types.port;
      default = 9093;
      description = "Port for Alertmanager web interface";
    };

    openFirewall = mkOption {
      type = types.bool;
      default = true;
      description = "Whether to open firewall ports";
    };

    dataDir = mkOption {
      type = types.str;
      default = "/var/lib/alertmanager";
      description = "Directory to store Alertmanager data";
    };

    smtp = {
      host = mkOption {
        type = types.str;
        default = "localhost:587";
        description = "SMTP server host:port";
      };

      from = mkOption {
        type = types.str;
        default = "alertmanager@${homelabCfg.externalDomain}";
        description = "From email address";
      };

      username = mkOption {
        type = types.str;
        default = "";
        description = "SMTP username";
      };

      password = mkOption {
        type = types.str;
        default = "";
        description = "SMTP password";
      };
    };

    routes = mkOption {
      type = types.listOf types.attrs;
      default = [];
      description = "Additional routing rules";
      example = literalExpression ''
        [
          {
            match = {
              service = "gatus";
            };
            receiver = "discord-webhook";
          }
          {
            match = {
              severity = "critical";
            };
            receiver = "email-alerts";
          }
        ]
      '';
    };

    receivers = mkOption {
      type = types.listOf types.attrs;
      default = [];
      description = "Alert receivers configuration";
      example = literalExpression ''
        [
          {
            name = "email-alerts";
            email_configs = [{
              to = "admin@example.com";
              subject = "{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}";
              body = "{{ range .Alerts }}{{ .Annotations.description }}{{ end }}";
            }];
          }
          {
            name = "discord-webhook";
            webhook_configs = [{
              url = "https://discord.com/api/webhooks/...";
              title = "{{ range .Alerts }}{{ .Annotations.summary }}{{ end }}";
            }];
          }
        ]
      '';
    };

    extraConfig = mkOption {
      type = types.attrs;
      default = {};
      description = "Additional Alertmanager configuration";
    };

    webExternalUrl = mkOption {
      type = types.str;
      default = "https://alertmanager.${homelabCfg.externalDomain}";
      description = "External URL for Alertmanager web interface";
    };
  };

  config = mkIf cfg.enable {
    services.prometheus.alertmanager = {
      enable = true;
      port = cfg.port;
      listenAddress = "0.0.0.0";
      webExternalUrl = cfg.webExternalUrl;
      dataDir = cfg.dataDir;

      # Write configuration to file
      configuration = alertmanagerConfig;
    };

    # Open firewall if requested
    networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [cfg.port];

    # Add to monitoring endpoints
    homelab.monitoring.metrics = [
      {
        name = "alertmanager";
        port = cfg.port;
        path = "/metrics";
        jobName = "alertmanager";
        labels = {
          service = "alertmanager";
          component = "monitoring";
        };
      }
    ];

    # Add health checks
    homelab.monitoring.healthChecks = [
      {
        name = "alertmanager-web-interface";
        port = cfg.port;
        path = "/-/healthy";
        interval = "30s";
        conditions = [
          "[STATUS] == 200"
          "[RESPONSE_TIME] < 1000"
        ];
        group = "monitoring";
        labels = {
          service = "alertmanager";
          component = "web-interface";
        };
      }
      {
        name = "alertmanager-ready";
        port = cfg.port;
        path = "/-/ready";
        interval = "30s";
        conditions = [
          "[STATUS] == 200"
        ];
        group = "monitoring";
        labels = {
          service = "alertmanager";
          component = "readiness";
        };
      }
    ];

    # Add reverse proxy entry
    homelab.reverseProxy.entries = [
      {
        subdomain = "alertmanager";
        host = homelabCfg.hostname;
        port = cfg.port;
      }
    ];
  };
}
