{ inputs, ... }: {
  flake.homeManagerModules.wisdomAppsSpotify =
    { config, lib, pkgs, ... }:
    let
      root = config.chiasson.home;
      cfg = config.chiasson.home.apps.spotify;
      spicePkgs = inputs.spicetify-nix.legacyPackages.${pkgs.stdenv.hostPlatform.system};
    in
    {
      imports = [ inputs.spicetify-nix.homeManagerModules.default ];

      options.chiasson.home.apps.spotify.enable = lib.mkEnableOption ''
        x86_64: spicetify + Spotify; others: `spotify-player`; aarch64 also gets `ncspot`.
      '';

      options.chiasson.home.apps.spotify.openDiscoveryFirewall = lib.mkEnableOption ''
        Punch TCP 57621 / UDP 5353 on the host firewall for LAN discovery (needs Spotify enabled here).
      '';

      config = lib.mkIf (root.enable && cfg.enable) {
        programs.spicetify = lib.mkIf pkgs.stdenv.isx86_64 {
          enable = true;
          enabledCustomApps = [
            spicePkgs.apps.ncsVisualizer
            spicePkgs.apps.lyricsPlus
          ];
          enabledExtensions = [ spicePkgs.extensions.fullScreen ];
        };

        home.packages =
          with pkgs;
          [ spotify-player ]
          ++ lib.optionals pkgs.stdenv.hostPlatform.isAarch64 [ ncspot ];
      };
    };

  # Opens Spotify LAN ports when any wired HM user sets `chiasson.home.apps.spotify.*` (requires HM+NixOS).
  flake.nixosModules.systemSpotify =
    { config, lib, ... }:
    let
      users = config.home-manager.users or { };
      userOpensDiscovery =
        name:
        let
          u = users.${name};
        in
        (lib.attrByPath [ "chiasson" "home" "enable" ] false u)
        && (lib.attrByPath [ "chiasson" "home" "apps" "spotify" "enable" ] false u)
        && (lib.attrByPath [ "chiasson" "home" "apps" "spotify" "openDiscoveryFirewall" ] false u);
      anyDiscovery = lib.any userOpensDiscovery (lib.attrNames users);
    in
    {
      config = lib.mkIf anyDiscovery {
        networking.firewall.allowedTCPPorts = [ 57621 ];
        networking.firewall.allowedUDPPorts = [ 5353 ];
      };
    };
}
