# Home Manager wiring for DMS (imported by default.nix; lives under _private/ for import-tree).
{
  inputs,
  config,
  pkgs,
  lib,
  osConfig ? { },
  ...
}:
let
  home = config.home.homeDirectory;
  dmsEnabled = lib.attrByPath [ "chiasson" "desktop" "shell" ] null osConfig == "dms";
  dmsOs = lib.attrByPath [ "chiasson" "desktop" "shells" "dms" ] { } osConfig;
  hostName = lib.attrByPath [ "networking" "hostName" ] "nixos" osConfig;
  rebuildCommand =
    if (dmsOs.rebuildCommand or null) != null then
      dmsOs.rebuildCommand
    else
      [ "sudo" "nixos-rebuild" "switch" "--flake" ".#${hostName}" ];
  gpuTempEnabled = dmsOs.enableGpuTemp or true;
  hyprlandEnabled = lib.attrByPath [ "chiasson" "desktop" "hyprland" "enable" ] false osConfig;
  discordEnabled = lib.attrByPath [ "chiasson" "home" "apps" "discord" "enable" ] false config;
  ohMyPoshEnabled = config.programs.oh-my-posh.enable or false;
  obsidianSnippetDirs = map (v: v + "/snippets") (dmsOs.obsidianVaults or [ ]);
  matugenOutputDirs =
    lib.optionals hyprlandEnabled [ "${home}/.config/hypr" ]
    ++ lib.optionals ohMyPoshEnabled [ "${home}/.config/oh-my-posh" ]
    ++ lib.optionals discordEnabled [ "${home}/.config/vesktop/themes" ]
    ++ [
      "${home}/.config/qt6ct/colors"
      "${home}/.config/qt5ct/colors"
    ];
  ensureMatugenBody =
    lib.concatStringsSep "\n" (map (dir: "mkdir -p ${lib.escapeShellArg dir}") matugenOutputDirs)
    + lib.concatStringsSep "\n" (map (dir: ''
      snippetDir=${lib.escapeShellArg dir}
      parentDir="$(dirname "$snippetDir")"
      if [ -d "$snippetDir" ]; then
        :
      elif [ ! -d "$parentDir" ] || [ ! -w "$parentDir" ]; then
        echo "dms: skipping Obsidian snippet dir '$snippetDir' (parent missing or not writable)" >&2
      else
        mkdir -p "$snippetDir"
      fi
    '') obsidianSnippetDirs)
    + lib.optionalString ohMyPoshEnabled ''
      dest="$HOME/.config/oh-my-posh/theme.omp.json"
      template="$HOME/.config/matugen/templates/ohmyposh-theme.omp.json"
      if [ -L "$dest" ] || { [ -e "$dest" ] && ! [ -f "$dest" ]; }; then
        rm -f "$dest"
      fi
      if [ ! -f "$dest" ]; then
        cp -L "$template" "$dest"
      fi
    '';
  ensureMatugenOutputDirsScript = pkgs.writeShellScript "dms-ensure-matugen-output-dirs" ''
    set -euo pipefail
    ${ensureMatugenBody}
  '';

  dmsRestartOnceScript = pkgs.writeShellScript "dms-plugin-restart-once" (
    builtins.replaceStrings
      [ "@FLOCK@" "@SYSTEMCTL@" ]
      [
        "${pkgs.util-linux}/bin/flock"
        "${pkgs.systemd}/bin/systemctl"
      ]
      (builtins.readFile ../scripts/dms-restart-once.sh)
  );

  jsonFormat = pkgs.formats.json { };
  dmsConfigDir = "${config.xdg.configHome}/DankMaterialShell";
  defaultSeedDir = dmsOs.defaultSeedDir or null;

  dmsSeedSources =
    if defaultSeedDir != null then
      {
        "settings.json" = defaultSeedDir + "/settings.json";
      }
      // lib.optionalAttrs (builtins.pathExists (defaultSeedDir + "/plugin_settings.json")) {
        "plugin_settings.json" = defaultSeedDir + "/plugin_settings.json";
      }
    else
      {
        "settings.json" = jsonFormat.generate "dms-settings-seed.json" (
          import ./default-settings.nix {
            inherit lib gpuTempEnabled;
            extraRightBarWidgets = dmsOs.extraRightBarWidgets or [ ];
          }
        );
      };

  dmsSeedBody = lib.concatMapStringsSep "\n" (
    fileName:
    let
      dest = "${dmsConfigDir}/${fileName}";
      src = dmsSeedSources.${fileName};
    in
    ''
      dest=${lib.escapeShellArg dest}
      mkdir -p "$(dirname "$dest")"
      if [ -L "$dest" ]; then
        ${pkgs.coreutils}/bin/cp --remove-destination -L "$dest" "$dest"
      fi
      if [ ! -e "$dest" ]; then
        ${pkgs.coreutils}/bin/cp ${lib.escapeShellArg src} "$dest"
        chmod u+w "$dest"
      fi
    ''
  ) (lib.attrNames dmsSeedSources);
  dmsSeedConfigScript = pkgs.writeShellScript "dms-seed-config" ''
    set -euo pipefail
    ${dmsSeedBody}
  '';

  matugenConfigText = import ./matugen-config.nix {
    inherit
      lib
      home
      hyprlandEnabled
      ohMyPoshEnabled
      discordEnabled
      obsidianSnippetDirs
      ;
  };

  thirdPartyPlugins = {
    dankVault = inputs.dms-plugin-dank-vault;
    calculator = inputs.dms-plugin-calculator;
    homeAssistantMonitor = inputs.dms-plugin-home-assistant;
    dropdownMenu = inputs.dms-plugin-dropdown-menu;
    ocrScanner = inputs.dms-plugin-ocr-scanner;
    unifiedTaskbar = inputs.dms-plugin-unified-taskbar;
    widgetGroup = inputs.dms-plugin-widget-group;
    nixPackageRunner = inputs.dms-plugin-nix-package-runner;
    ambientSound = inputs.dms-plugin-ambient-sound;
    cavaVisualizer = inputs.dms-plugin-cava-visualizer;
    emojiLauncher = inputs.dms-plugin-emoji-launcher;
    dankDesktopWeather = inputs.dms-plugin-official + "/DankDesktopWeather";
    webSearch = inputs.dms-plugin-web-search;
    wallpaperCarousel = inputs.dms-plugin-wallpaper-carousel;
    ephemera = inputs.dms-plugin-ephemera;
    appShortcut = inputs.dms-plugin-app-shortcut;
    wvkbdToggle = inputs.dms-plugin-wvkbd-toggle;
    rbwLockToggle = inputs.dms-plugin-rbw-lock-toggle;
  };

  shipPlugin =
    _id: src:
    {
      source = src;
      onChange = "${dmsRestartOnceScript}";
    };
in
{
  imports = [
    inputs.dms.homeModules.dank-material-shell
    inputs.nix-monitor.homeManagerModules.default
  ];

  config = lib.mkIf dmsEnabled (lib.mkMerge [
    (lib.mkIf (dmsOs.bundleThirdPartyPlugins or true) {
      xdg.configFile = lib.mapAttrs (_id: src: shipPlugin _id src) thirdPartyPlugins;
    })
    {
      programs.nix-monitor = {
        enable = true;
        inherit rebuildCommand;
        generationsCommand = [
          "bash"
          "-c"
          "readlink /nix/var/nix/profiles/system | cut -d- -f2"
        ];
      };

      home.packages = with pkgs; [
        kdePackages.qtdeclarative
        kdePackages.kirigami.unwrapped
        kdePackages.qtmultimedia
        kdePackages.sonnet
        tesseract
        mpv
        socat
        wl-clipboard
        jq
        cava
        curl
        libsecret
      ];

      programs.dank-material-shell = {
        enable = true;
        package = inputs.dms.packages.${pkgs.stdenv.hostPlatform.system}.dms-shell.override {
          extraQtPackages = with pkgs.kdePackages; [ qtwebsockets ];
        };
        systemd = {
          enable = true;
          restartIfChanged = true;
        };
        enableSystemMonitoring = true;
        dgop.package = inputs.dgop.packages.${pkgs.stdenv.hostPlatform.system}.default;
        enableVPN = true;
        enableDynamicTheming = true;
        enableAudioWavelength = true;
        enableCalendarEvents = false;
        settings = { };
        session = { };
      };

      home.activation.dmsSeedConfig = lib.hm.dag.entryAfter [ "writeBoundary" ] "${dmsSeedConfigScript}";

      systemd.user.services.dms.serviceConfig.ExecStartPre =
        lib.mkOrder 100 "${ensureMatugenOutputDirsScript}";

      xdg.configFile."matugen/config.toml".text = matugenConfigText;
      xdg.configFile."matugen/templates/dank-discord.css".source = ../templates/dank-discord.css;
      xdg.configFile."matugen/templates/hyprland-colors.conf".source = ../templates/hyprland-colors.conf;
      xdg.configFile."matugen/templates/ohmyposh-theme.omp.json".source = ../templates/ohmyposh-theme.omp.json;
      xdg.configFile."matugen/templates/obsidian-minimal-matugen-colors.css".source =
        ../templates/obsidian-minimal-matugen-colors.css;
    }
    (lib.mkIf ohMyPoshEnabled {
      programs.oh-my-posh = {
        useTheme = lib.mkForce null;
        configFile = lib.mkForce "${config.xdg.configHome}/oh-my-posh/theme.omp.json";
      };
    })
  ]);
}
