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

let
  configDir = ./config;

  # Explicit list of config items to manage
  # This replaces dynamic builtins.readDir for clarity and faster evaluation
  configItems = {
    # Directories
    "environment.d" = "directory";
    fastfetch = "directory";
    fcitx5 = "directory";
    fontconfig = "directory";
    git = "directory";
    imv = "directory";
    "nautilus-python" = "directory";
    nomarchy = "directory";
    "nomarchy-skill" = "directory";
    Typora = "directory";
    uwsm = "directory";
    wiremix = "directory";
    xournalpp = "directory";

    # Files
    "brave-flags.conf" = "regular";
    "chromium-flags.conf" = "regular";
    "starship.toml" = "regular";
    "xdg-terminals.list" = "regular";
  };

  # Files/directories handled elsewhere or not intended for ~/.config/
  # - nomarchy.ttf: font file, not a config
  # - waybar: handled in waybar.nix
  # - walker: handled in walker.nix
  # - alacritty: handled in alacritty.nix
  # - swayosd: handled in swayosd.nix

  # Check for user overrides
  userConfigDir = config.nomarchy.configOverrides;
  hasUserOverrides = userConfigDir != null && builtins.pathExists userConfigDir;

  # Generate the xdg.configFile attribute set
  makeMapping = name: type:
    let
      hasUserOverride = hasUserOverrides && builtins.pathExists "${userConfigDir}/${name}";
      source = if hasUserOverride then "${userConfigDir}/${name}" else "${configDir}/${name}";
    in {
      inherit name;
      value = lib.mkDefault {
        inherit source;
        recursive = type == "directory";
      };
    };

  configMappings = lib.mapAttrs' (name: type: makeMapping name type) configItems;

in
{
  xdg.configFile = configMappings;
}
