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

let
  # Core dependencies needed by most scripts (minimal set)
  coreDeps = with pkgs; [
    coreutils
    gnused
    gnugrep
    findutils
    gawk
    jq
  ];

  # Category-specific dependencies
  categoryDeps = with pkgs; {
    appearance = [
      swww
      libnotify
    ];

    apps = [
      hyprland
      libnotify
    ];

    hardware = [
      brightnessctl
      playerctl
      pamixer
      pciutils
      libnotify
    ];

    system = [
      gum
      libnotify
      curl
      wget
      pkgs.home-manager
      nixos-rebuild
    ];

    utils = [
      gum
      hyprland
      libnotify
      wl-clipboard
      grim
      slurp
      xmlstarlet
      curl
      wget
    ];

    wm = [
      hyprland
      swayosd
      libnotify
      procps
    ];
  };

  # All dependencies combined (for scripts that might call others)
  allDeps = coreDeps ++ (lib.unique (lib.flatten (builtins.attrValues categoryDeps)));

  # Environment variables to inject
  envVars = {
    NOMARCHY_TOGGLE_SUSPEND = if config.nomarchy.toggles.suspend then "true" else "false";
    NOMARCHY_TOGGLE_SCREENSAVER = if config.nomarchy.toggles.screensaver then "true" else "false";
    NOMARCHY_TOGGLE_IDLE = if config.nomarchy.toggles.idle then "true" else "false";
    NOMARCHY_TOGGLE_NIGHTLIGHT = if config.nomarchy.toggles.nightlight then "true" else "false";
    NOMARCHY_TOGGLE_WAYBAR = if config.nomarchy.toggles.waybar then "true" else "false";
    NOMARCHY_TOGGLE_SKIP_VSCODE_THEME = if config.nomarchy.toggles.skipVsCodeTheme then "true" else "false";
    NOMARCHY_MONOSPACE_FONT = config.nomarchy.fonts.monospace;
  };

  # Build wrapper arguments for environment variables
  envWrapperArgs = lib.concatStringsSep " " (
    lib.mapAttrsToList (name: value: "--set ${name} \"${value}\"") envVars
  );

  nomarchy-scripts = pkgs.stdenv.mkDerivation {
    pname = "nomarchy-scripts";
    version = "1.0.0";
    src = ./utils;

    nativeBuildInputs = [ pkgs.makeWrapper ];

    installPhase = ''
      mkdir -p $out/bin
      cp * $out/bin/

      chmod +x $out/bin/*
      patchShebangs $out/bin
    '';

    postFixup = ''
      # Wrap all scripts with all dependencies for robustness
      deps="${lib.makeBinPath allDeps}"
      for file in $out/bin/*; do
        if [ -f "$file" ]; then
          wrapProgram "$file" \
            --prefix PATH : "$deps" \
            ${envWrapperArgs}
        fi
      done
    '';
  };
in
{
  home.packages = [ nomarchy-scripts ];
}
