{
  config,
  lib,
  pkgs,
  ...
}:

let
  cfg = config.services.open-webui-oci;

  image = pkgs.dockerTools.pullImage {
    imageName = "ghcr.io/open-webui/open-webui";
    imageDigest = "sha256:a7e4796ae894d1e2a0c1824860ade472f35c507608a01c3581377b5c19b0ed49";
    hash = "sha256-uhPlVXSxY6rGbYGvlPVV3zurmbI96mAHEuKKy9FFaD4=";
    finalImageName = "ghcr.io/open-webui/open-webui";
    finalImageTag = "0.9.2";
  };

  defaultEnv = {
    ANONYMIZED_TELEMETRY = "False";
    BYPASS_MODEL_ACCESS_CONTROL = "True";
    DEFAULT_LOCALE = "en";
    DEFAULT_USER_ROLE = "user";
    DO_NOT_TRACK = "True";
    ENABLE_DIRECT_CONNECTIONS = "True";
    ENABLE_IMAGE_GENERATION = "True";
    ENABLE_PERSISTENT_CONFIG = "False";
    ENABLE_SIGNUP = "False";
    ENABLE_SIGNUP_PASSWORD_CONFIRMATION = "True";
    ENABLE_USER_WEBHOOKS = "True";
    ENABLE_WEBSEARCH = "True";
    ENV = "prod";
    SCARF_NO_ANALYTICS = "True";
    USER_AGENT = "OpenWebUI";
    USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS = "True";
    WEB_SEARCH_ENGINE = "DuckDuckGo";
  };

  inherit (lib)
    concatStringsSep
    literalExpression
    mkEnableOption
    mkIf
    mkOption
    mkOverride
    optional
    types
    ;
in
{
  options.services.open-webui-oci = {
    enable = mkEnableOption "Open WebUI container with Podman.";
    image = mkOption {
      type = types.package;
      default = image;
      description = "The Docker image to use (`pkgs.dockerTools.pullImage`).";
    };
    externalUrl = mkOption {
      type = types.nullOr types.str;
      default = null;
      example = literalExpression "http://${config.networking.domain}";
      description = "Public URL to add to CORS.";
    };
    port = mkOption {
      type = types.port;
      default = 3000;
      description = "Which port the Open-WebUI server listens to.";
    };
    environment = mkOption {
      default = { };
      type = types.attrsOf types.str;
      description = ''
        Extra environment variables for Open-WebUI.
        For more details see <https://docs.openwebui.com/getting-started/advanced-topics/env-configuration/>
      '';
    };
    environmentFile = mkOption {
      description = "Environment file to be passed to the Open WebUI container.";
      type = types.nullOr types.path;
      default = null;
      example = "config.sops.templates.open-webui-env.path";
    };
  };

  config = mkIf cfg.enable {
    virtualisation.podman = {
      enable = true;
      autoPrune.enable = true;
      dockerCompat = true;
    };

    networking.firewall.interfaces =
      let
        matchAll = if !config.networking.nftables.enable then "podman+" else "podman*";
      in
      {
        "${matchAll}".allowedUDPPorts = [ 53 ];
      };

    virtualisation.oci-containers.backend = "podman";

    virtualisation.oci-containers.containers."open-webui" = {
      image = with cfg.image; imageName + ":" + imageTag;
      imageFile = cfg.image;
      environment =
        defaultEnv
        // cfg.environment
        // {
          PORT = "${toString cfg.port}";
          CORS_ALLOW_ORIGIN = concatStringsSep ";" (
            [
              "http://localhost:${toString cfg.port}"
              "http://127.0.0.1:${toString cfg.port}"
              "http://0.0.0.0:${toString cfg.port}"
            ]
            ++ optional (cfg.externalUrl != null) cfg.externalUrl
          );
        };
      environmentFiles = optional (cfg.environmentFile != null) cfg.environmentFile;
      volumes = [
        "open-webui_open-webui:/app/backend/data:rw"
      ];
      log-driver = "journald";
      extraOptions = [
        "--network=host"
      ];
    };
    systemd.services."podman-open-webui" = {
      serviceConfig = {
        Restart = mkOverride 90 "always";
      };
      after = [
        "podman-volume-open-webui_open-webui.service"
      ];
      requires = [
        "podman-volume-open-webui_open-webui.service"
      ];
      partOf = [
        "podman-compose-open-webui-root.target"
      ];
      wantedBy = [
        "podman-compose-open-webui-root.target"
      ];
    };

    systemd.services."podman-volume-open-webui_open-webui" = {
      path = [ pkgs.podman ];
      serviceConfig = {
        Type = "oneshot";
        RemainAfterExit = true;
      };
      script = ''
        podman volume inspect open-webui_open-webui || podman volume create open-webui_open-webui
      '';
      partOf = [ "podman-compose-open-webui-root.target" ];
      wantedBy = [ "podman-compose-open-webui-root.target" ];
    };

    systemd.targets."podman-compose-open-webui-root" = {
      unitConfig = {
        Description = "Root target generated by compose2nix.";
      };
      wantedBy = [ "multi-user.target" ];
    };
  };
}
