{ config, containerCfg, pkgs, lib, builder, name,... }:
let 
  version = "latest";
  serverCfg = config.syscfg.server;
  settings = pkgs.writeText"settings.yml" (pkgs.lib.generators.toYAML {}{
    use_default_settings = true;
    brand = {
        issue_url = "";
        docs_url = "";
        public_instances = "";
        wiki_url = "";
        custom = {
            links = {
                "Home" = "https://${serverCfg.domain}";
                # "Status" = "https://status.${serverCfg.domain}";
            };
        };
        pwa_colors = {
            theme_color_light = "${serverCfg.colorScheme.palette.base0C}";
            background_color_light = "${serverCfg.colorScheme.palette.base07}";
            theme_color_dark = "${serverCfg.colorScheme.palette.base0C}";
            background_color_dark = "${serverCfg.colorScheme.palette.base02}";
            theme_color_black = "${serverCfg.colorScheme.palette.base0C}";
            background_color_black = "${serverCfg.colorScheme.palette.base01}";
        };
    };
    general = {
        debug = false;
        instance_name = if containerCfg.extra ? instanceName then containerCfg.extra.instanceName else "SearXNG";
        privacypolicy_url = false;
        donation_url = false;
        contact_url = false;
        enable_metrics = false;
    };
    search = {
        safe_search = 0;
        autocomplete = if containerCfg.extra ? autocomplete then containerCfg.extra.autocomplete else "";
        languages = [ "all" "en" "en-US" "ja" "de-CH" "fr-CH" "nb" ];
    };
    server = {
        # secret_key = ""; SET BY ENV VAR
    };
    ui = {
        default_locale = if containerCfg.extra ? defaultLocale then containerCfg.extra.defaultLocale else "en";
        # query_in_title = "true";
        #default_theme = "custom";
        custom_css = "footer { display: none !important; }";
    };
    # categories_as_tabs = {
    #     general = {};
    #     images ={};
    #     videos = {};
    #     news = {};
    #     files = {};
    # };
    plugins = {
        "searx.plugins.infinite_scroll.SXNGPlugin".active = true;
        "searx.plugins.tracker_url_remover.SXNGPlugin".active = true;
    };
  });
in {
  requires.secrets = [ name ];

  runtime = {
    containers = {
      server = builder.mkContainer {
        subdomain = containerCfg.subdomain;
        image = "searxng/searxng:${version}";
        port = 8080;
        secret = name;
        extraEnv = { 
          SEARXNG_BASE_URL = "https://${containerCfg.subdomain}.${serverCfg.domain}";
          SEARXNG_PORT = "8080";
          SEARXNG_BIND_ADDRESS = "[::]";
          SEARXNG_PUBLIC_INSTANCE = "false";
          SEARXNG_SETTINGS_PATH = "/etc/searxng/settings.yml";
          #SEARXNG_VALKEY_URL = "valkey://user:password@${builder.host}:6379/0}";
        };
        overrides = {
          volumes = [ 
              "${settings}:/etc/searxng/settings.yml"
          ];
         };
      };
    };
  };
}
