{
  config,
  lib,
  ...
}:
with lib; let
  serviceInterface = import ../../lib/service-interface.nix {inherit lib;};

  cfg = config.homelab.services.gatus;
  homelabCfg = config.homelab;

  # Service-specific options beyond the standard interface
  gatusServiceOptions = {
    ui = {
      title = mkOption {
        type = types.str;
        default = "Homelab Status";
        description = "Title for the Gatus web interface";
      };

      header = mkOption {
        type = types.str;
        default = "Homelab Services Status";
        description = "Header text for the Gatus interface";
      };

      link = mkOption {
        type = types.str;
        default = "https://status.${homelabCfg.externalDomain}";
        description = "Link in the Gatus header";
      };

      buttons = mkOption {
        type = types.listOf (types.submodule {
          options = {
            name = mkOption {type = types.str;};
            link = mkOption {type = types.str;};
          };
        });
        default = [
          {
            name = "Grafana";
            link = "https://grafana.${homelabCfg.externalDomain}";
          }
          {
            name = "Prometheus";
            link = "https://prometheus.${homelabCfg.externalDomain}";
          }
        ];
        description = "Navigation buttons in the Gatus interface";
      };
    };

    alerting = mkOption {
      type = types.attrs;
      default = {};
      description = "Gatus alerting configuration";
      example = literalExpression ''
        {
          discord = {
            webhook-url = "https://discord.com/api/webhooks/...";
            default-alert = {
              enabled = true;
              description = "Health check failed";
              failure-threshold = 3;
              success-threshold = 2;
            };
          };
        }
      '';
    };

    storage = mkOption {
      type = types.attrs;
      default = {
        type = "memory";
      };
      description = "Gatus storage configuration";
      example = literalExpression ''
        {
          type = "postgres";
          path = "postgres://user:password@localhost/gatus?sslmode=disable";
        }
      '';
    };

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

    web = {
      address = mkOption {
        type = types.str;
        default = "0.0.0.0";
        description = "Web interface bind address";
      };
    };
  };

  # Convert our health check format to Gatus format
  formatHealthCheck = check: let
    # Build the URL based on the health check configuration
    url = check._url;

    # Convert conditions to Gatus format (they should already be compatible)
    conditions = check.conditions or ["[STATUS] == 200"];

    # Convert alerts to Gatus format
    alerts = map (alert: {
      inherit (alert) type enabled;
      failure-threshold = alert.failure-threshold or 3;
      success-threshold = alert.success-threshold or 2;
      description = "Health check alert for ${check.name}";
    }) (check.alerts or []);
  in {
    name = check.name;
    group = check.group or "default";
    url = url;
    interval = check.interval or "30s";

    # Add method and headers for HTTP/HTTPS checks
    method =
      if (check.protocol == "http" || check.protocol == "https")
      then check.method or "GET"
      else null;

    conditions = conditions;

    # Add timeout
    client = {
      timeout = check.timeout or "10s";
    };

    # Add alerts if configured
    alerts =
      if alerts != []
      then alerts
      else [];

    # Add labels for UI organization
    ui = {
      hide-hostname = false;
      hide-url = false;
      description = "Health check for ${check.name} on ${check.host}";
    };
  };

  # Generate Gatus configuration
  gatusConfig =
    recursiveUpdate {
      # Global Gatus settings
      alerting = mkIf (cfg.alerting != {}) cfg.alerting;

      web = {
        address = cfg.web.address;
        port = cfg.port;
      };

      # Enable metrics
      metrics = cfg.monitoring.enable;

      ui = {
        title = cfg.ui.title;
        header = cfg.ui.header;
        link = cfg.ui.link;
        buttons = cfg.ui.buttons;
      };

      storage = cfg.storage;

      # Convert all enabled health checks to Gatus endpoints
      endpoints = let
        # Get all health checks from global config
        allHealthChecks = homelabCfg.global.monitoring.allHealthChecks or [];

        # Filter only enabled health checks
        enabledHealthChecks = filter (check: check.enabled or true) allHealthChecks;

        # Convert to Gatus format
        gatusEndpoints = map formatHealthCheck enabledHealthChecks;
      in
        gatusEndpoints;
    }
    cfg.extraConfig;
in {
  options.homelab.services.gatus = serviceInterface.mkServiceInterface {
    serviceName = "gatus";
    defaultPort = 8080;
    defaultSubdomain = "status";
    monitoringPath = "/metrics";
    healthCheckPath = "/health";
    healthCheckConditions = [
      "[STATUS] == 200"
      "[BODY].status == UP"
      "[RESPONSE_TIME] < 1000"
    ];
    serviceOptions = gatusServiceOptions;
  };

  config = serviceInterface.mkServiceConfig {
    inherit config cfg homelabCfg;
    serviceName = "gatus";

    extraMonitoringLabels = {
      component = "status-monitoring";
    };

    serviceConfig = {
      services.gatus = {
        enable = true;
        settings = gatusConfig;
      };
    };
  };
}
