#!/usr/bin/env zsh
# ===============================================================
# zshrc — Dynamic Modular Config Loader with JSON Logging
# ===============================================================

# Profiling
[[ "$ZPROFRC" -ne 1 ]] || zmodload zsh/zprof
alias zprofrc="ZPROFRC=1 zsh"
typeset -g POWERLEVEL9K_INSTANT_PROMPT=false

# Ensure globals
typeset -g DOTFILES="${DOTFILES:-$HOME/.dotfiles}"
typeset -g outfile="${outfile:-$HOME/zshrc-log.json}"
: > "$outfile"  # clear old log

setopt EXTENDED_GLOB

if [[ ! `typeset -f call_file` ]]; then
  source "$DOTFILES/bin/call_file"
fi

POWERLEVEL9K_INSTANT_PROMPT=true
#if [[ -e "${HOME}/zsh-defer/zsh-defer.plugin.zsh" ]]; then
#    call_file ${HOME}/zsh-defer/zsh-defer.plugin.zsh
#fi



   # Use extended globbing syntax.

# load envrc from $HOME
if [[ -a $HOME/.envrc ]];then
	call_file $HOME/.envrc "env"
fi
# load localrc from $HOME
if [[ -a $HOME/.localrc ]];then
	call_file $HOME/.localrc "local"
fi

if $POWERLEVEL9K_INSTANT_PROMPT; then
    if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then
        call_file "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" "instant"
    fi
fi


unsetopt complete_aliases nobgnice
typeset -U config_files
config_files=($DOTFILES/**/*.zsh)

# --- PATH phase -------------------------------------------------
for file in ${(M)config_files:#*/path.zsh}; do
  call_file "$file" "path"
  typeset -gU path
done
export -U PATH

# --- CONFIG phase ------------------------------------------------
# exclude path.zsh, any *completion*.zsh, and the compinit driver itself
for file in ${${${config_files:#*/path.zsh}:#*/*completion*.zsh}:#*/zsh/compinit.zsh}; do
  call_file "$file"     # label auto-derives (dir for config.zsh, stem otherwise)
done

# --- COMPLETION (cache-aware) -----------------------------------
call_file "$DOTFILES/zsh/compinit.zsh" "compinit"

unset config_files

# Finish profiling by calling zprof.
[[ "$ZPROFRC" -eq 1 ]] && zprof
[[ -v ZPROFRC ]] && unset ZPROFRC

# Always return success
true
