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

with lib;

let

  cfg = config.programs.cavalier;

  iniFmt = pkgs.formats.ini { };

  jsonFmt = pkgs.formats.json { };

in {
  meta.maintainers = [ hm.maintainers.bricked ];

  options.programs.cavalier = {
    enable = mkEnableOption "Cava audio visualizer GUI";

    package = mkPackageOption pkgs "cavalier" { };

    settings = {
      general = mkOption {
        type = jsonFmt.type;
        default = { };
        example = literalExpression ''
          {
            ShowControls = true;
            ColorProfiles = [
              {
                Name = "Default";
                FgColors = [
                  "#ffed333b"
                  "#ffffa348"
                  "#fff8e45c"
                  "#ff57e389"
                  "#ff62a0ea"
                  "#ffc061cb"
                ];
                BgColors = [
                  "#ff1e1e2e"
                ];
                Theme = 1;
              }
            ];
            ActiveProfile = 0;
          }
        '';
        description = ''
          Settings to be written to the Cavalier configuration file. See
          <https://github.com/NickvisionApps/Cavalier/blob/main/NickvisionCavalier.Shared/Models/Configuration.cs>
          for all available options.
        '';
      };

      cava = mkOption {
        type = iniFmt.type;
        default = { };
        example = literalExpression ''
          {
            general.framerate = 60;
            input.method = "alsa";
            smoothing.noise_reduction = 88;
            color = {
              background = "'#000000'";
              foreground = "'#FFFFFF'";
            };
          }
        '';
        description = ''
          Settings to be written to the underlying Cava configuration file. See
          <https://github.com/karlstav/cava/blob/master/example_files/config> for
          all available options.
        '';
      };
    };
  };

  config = mkIf cfg.enable {
    assertions = [
      (lib.hm.assertions.assertPlatform "programs.cavalier" pkgs
        lib.platforms.linux)
    ];

    home.packages = [ cfg.package ];

    xdg.configFile = {
      "Nickvision Cavalier/config.json" = mkIf (cfg.settings.general != { }) {
        text = ''
          ${generators.toJSON { } cfg.settings.general}
        '';
      };

      "Nickvision Cavalier/cava_config" = mkIf (cfg.settings.cava != { }) {
        text = ''
          ; Generated by Home Manager

          ${generators.toINI { } cfg.settings.cava}
        '';
      };
    };
  };
}