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

  # Build alertmanager configuration
  alertmanagerConfig = {
    route = {
      receiver = cfg.defaultReceiver;
      group_by = cfg.groupBy;
      group_wait = cfg.groupWait;
      group_interval = cfg.groupInterval;
      repeat_interval = cfg.repeatInterval;
      routes = cfg.routes;
    };

    receivers =
      [
        {name = cfg.defaultReceiver;}
      ]
      ++ cfg.receivers;

    inhibit_rules = cfg.inhibitRules;

    templates = cfg.templates;
  };
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";
    };

    webExternalUrl = mkOption {
      type = types.str;
      default = "http://${homelabCfg.hostname}.${homelabCfg.domain}:${toString cfg.port}";
      description = "External URL for Alertmanager web interface";
    };

    environmentFile = mkOption {
      type = types.nullOr types.path;
      default = null;
      description = "Environment file for secrets (e.g., Telegram bot token)";
      example = "/run/secrets/alertmanager-env";
    };

    # Routing configuration
    defaultReceiver = mkOption {
      type = types.str;
      default = "null";
      description = "Default receiver for unmatched alerts";
    };

    groupBy = mkOption {
      type = types.listOf types.str;
      default = ["alertname"];
      description = "Labels to group alerts by";
    };

    groupWait = mkOption {
      type = types.str;
      default = "10s";
      description = "Time to wait before sending initial notification";
    };

    groupInterval = mkOption {
      type = types.str;
      default = "5m";
      description = "Time to wait before sending updates for a group";
    };

    repeatInterval = mkOption {
      type = types.str;
      default = "4h";
      description = "Time to wait before re-sending an alert";
    };

    routes = mkOption {
      type = types.listOf types.attrs;
      default = [];
      description = "Alert routing rules";
      example = literalExpression ''
        [
          {
            receiver = "telegram";
            matchers = ["severity =~ \"warning|critical\""];
            group_wait = "10s";
            continue = true;
          }
        ]
      '';
    };

    receivers = mkOption {
      type = types.listOf types.attrs;
      default = [];
      description = "Alert receivers configuration";
      example = literalExpression ''
        [
          {
            name = "telegram";
            telegram_configs = [{
              api_url = "https://api.telegram.org";
              bot_token = "$TELEGRAM_BOT_TOKEN";
              chat_id = -1002642560007;
              message_thread_id = 4;
              parse_mode = "HTML";
              send_resolved = true;
              message = "{{ template \"telegram.message\" . }}";
            }];
          }
        ]
      '';
    };

    inhibitRules = mkOption {
      type = types.listOf types.attrs;
      default = [
        {
          source_match = {severity = "critical";};
          target_match = {severity = "warning";};
          equal = ["alertname" "instance"];
        }
      ];
      description = "Rules for inhibiting alerts";
    };

    templates = mkOption {
      type = types.listOf types.path;
      default = [];
      description = "Template files for alert formatting";
      example = literalExpression ''
        [
          (pkgs.writeText "telegram.tmpl" '''
            {{- define "telegram.message" -}}
            {{- if gt (len .Alerts.Firing) 0 -}}
            🔥 <b>FIRING</b> 🔥
            {{- range .Alerts.Firing }}
            <b>{{ .Annotations.summary }}</b>
            {{ .Annotations.description }}
            {{- end }}
            {{- end }}
            {{- if gt (len .Alerts.Resolved) 0 -}}
            ✅ <b>RESOLVED</b> ✅
            {{- range .Alerts.Resolved }}
            <b>{{ .Annotations.summary }}</b>
            {{- end }}
            {{- end }}
            {{- end -}}
          ''')
        ]
      '';
    };

    # Convenience options for common receivers
    telegram = {
      enable = mkOption {
        type = types.bool;
        default = false;
        description = "Enable Telegram notifications";
      };

      botToken = mkOption {
        type = types.str;
        default = "$TELEGRAM_BOT_TOKEN";
        description = "Telegram bot token (use environment variable)";
      };

      chatId = mkOption {
        type = types.int;
        description = "Telegram chat ID";
        example = -1002642560007;
      };

      messageThreadId = mkOption {
        type = types.nullOr types.int;
        default = null;
        description = "Telegram message thread ID (for forum groups)";
      };

      template = mkOption {
        type = types.str;
        default = "telegram.message";
        description = "Template to use for Telegram messages";
      };
    };

    discord = {
      enable = mkOption {
        type = types.bool;
        default = false;
        description = "Enable Discord notifications";
      };

      webhookUrl = mkOption {
        type = types.str;
        default = "$DISCORD_WEBHOOK_URL";
        description = "Discord webhook URL (use environment variable)";
      };

      username = mkOption {
        type = types.str;
        default = "Alertmanager";
        description = "Discord bot username";
      };
    };
  };

  config = mkIf cfg.enable {
    services.prometheus.alertmanager = {
      enable = true;
      port = cfg.port;
      listenAddress = "0.0.0.0";
      openFirewall = cfg.openFirewall;
      webExternalUrl = cfg.webExternalUrl;
      dataDir = cfg.dataDir;
      environmentFile = cfg.environmentFile;
      configuration = alertmanagerConfig;
    };

    # Auto-configure Telegram and Discord receiver if enabled
    homelab.services.alertmanager.receivers = [
      (optional cfg.telegram.enable {
        name = "telegram";
        telegram_configs = [
          {
            api_url = "https://api.telegram.org";
            bot_token = cfg.telegram.botToken;
            chat_id = cfg.telegram.chatId;
            message_thread_id = cfg.telegram.messageThreadId;
            parse_mode = "HTML";
            send_resolved = true;
            message = "{{ template \"${cfg.telegram.template}\" . }}";
          }
        ];
      })
      (optional cfg.discord.enable {
        name = "discord";
        discord_configs = [
          {
            webhook_url = cfg.discord.webhookUrl;
            username = cfg.discord.username;
            send_resolved = true;
          }
        ];
      })
    ];

    # Auto-configure routes for convenience receivers
    homelab.services.alertmanager.routes =
      (optional cfg.telegram.enable {
        receiver = "telegram";
        matchers = ["severity =~ \"warning|critical\""];
        group_wait = "10s";
        continue = true;
      })
      ++ (optional cfg.discord.enable {
        receiver = "discord";
        matchers = ["severity =~ \"warning|critical\""];
        group_wait = "10s";
        continue = true;
      });

    # 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";
        };
      }
    ];

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