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

with lib;

let cfg = config.sydnix.mpd;
in {
  options = {
    sydnix.mpd = {
      enable = mkEnableOption "Music Player Daemon";

      musicDirectory = mkOption {
        default = "${config.home.homeDirectory}/Music";
        type = types.path;
      };

      scrobbling = {
        enable = mkEnableOption "Enable scrobbling for MPD via mpdscribble.";

        endpoints = mkOption {
          type = types.attrsOf (types.submodule ({ ... }: {
            options = {
              passwordFile = mkOption {
                type = types.path;
              };
              username = mkOption {
                type = types.str;
              };
            };
          }));
        };
      };

      discord = {
        enable =
          mkEnableOption "Discord integration for MPD via mpd-discord-rpc";
      };
    };
  };

  config = mkIf cfg.enable {
    sydnix.impermanence.directories =
      let xdg-state-dir = 
        config.home.statehome
              or "${config.home.homeDirectory}/.local/state";
      in [
        (lib.removePrefix
          config.home.homeDirectory
          "${xdg-state-dir}/mpd")
      ];
    services.mpd = {
      enable = true;
      musicDirectory = cfg.musicDirectory;
      extraConfig = ''
        audio_output {
            type "pipewire"
            name "My PipeWire Output"
        }
      '';
      # if you want to allow non-localhost connections
      network.listenAddress = "any";
    };

    services.mpd-discord-rpc = mkIf cfg.discord.enable {
      enable = true;
    };

    services.mpdscribble = mkIf cfg.scrobbling.enable {
      enable = true;
      endpoints = cfg.scrobbling.endpoints;
    };
  };
}
