#!/usr/bin/env zsh
# Set up XDG directories
export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}"
export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}"
export XDG_STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}"

# Set up zsh directories
export ZDOTDIR="$XDG_CONFIG_HOME/zsh"
export ZSH_CACHE="$XDG_CACHE_HOME/zsh"

# Set up Homebrew environment (needed for all shells, including doom env)
# Cache brew shellenv output (~80ms savings) since it's stable
_brew_cache="$XDG_CACHE_HOME/zsh/brew_shellenv.zsh"
if [[ -x /opt/homebrew/bin/brew ]]; then
  if [[ ! -f "$_brew_cache" ]]; then
    mkdir -p "${_brew_cache:h}"
    /opt/homebrew/bin/brew shellenv > "$_brew_cache" 2>/dev/null
  fi
  source "$_brew_cache"
fi
unset _brew_cache

# Set up terminfo early (before nix-darwin extra.zshenv is sourced).
# Prefer ~/.terminfo because this repo provides compatibility symlinks using
# the canonical first-letter layout expected by tools like `codex doctor`.
_terminfo_candidates=(
  "$HOME/.terminfo"
  "$HOME/.nix-profile/share/terminfo"
  "/etc/profiles/per-user/$USER/share/terminfo"
  "/run/current-system/sw/share/terminfo"
  "/nix/var/nix/profiles/default/share/terminfo"
  "/usr/share/terminfo"
  ${(s.:.)TERMINFO_DIRS}
)
_terminfo_dirs=()
for _terminfo_dir in $_terminfo_candidates; do
  [[ -r "$_terminfo_dir" ]] && _terminfo_dirs+=("$_terminfo_dir")
done
typeset -U _terminfo_dirs
export TERMINFO_DIRS="${(j.:.)_terminfo_dirs}"
unset _terminfo_candidates _terminfo_dirs _terminfo_dir
# Set default TERM if empty (prevents TUI crashes in non-interactive SSH)
[[ -z "$TERM" ]] && export TERM=xterm-256color

# Source nix-darwin generated environment (envFiles from modules).
[[ -f "$ZDOTDIR/extra.zshenv" ]] && source "$ZDOTDIR/extra.zshenv"

# Canonical PATH order: managed Nix profiles first, then user/tool bins.
# This prevents stale self-installed tools in ~/.local/bin, ~/.bun/bin, etc.
# from shadowing declarative packages such as Herdr.
typeset -U path PATH
path=(
  /etc/profiles/per-user/$USER/bin
  /run/wrappers/bin
  /run/current-system/sw/bin
  $HOME/.nix-profile/bin
  $XDG_CONFIG_HOME/dotfiles/bin
  $HOME/.pi/agent/bin
  ${BUN_INSTALL:-$HOME/.bun}/bin
  $HOME/.local/bin
  $HOME/.pixi/bin
  $HOME/.cargo/bin
  $path
)
