# Stole ollies idea of putting _part_ in a separate file and part inline :3
export EDITOR=nvim
# Function: zap
_zap() {
    if [[ -d .jj || -d .git ]]; then
        clear -x
        local repo_type=""

        if [[ -d .git && -d .jj ]]; then
            repo_type="JJ (git-colocated)"
        elif [[ -d .jj ]]; then
            repo_type="Jujutsu"
        else
            repo_type="Git"
        fi

        echo "📂 Opened $repo_type repository: $(pwd)"

        if [[ -d .git ]]; then
            git fetch
        else
            jj git fetch
        fi

        # Show repository line counts (assuming 'kc' is another alias/function)
        kc

        if [[ -d .jj ]]; then
            jj log -Tbuiltin_log_compact_full_description -r'ancestors(bookmarks() & @-, 5) & ~@' --reversed --no-pager --limit 5
            jj show --summary
        else
            git status
        fi

        # Dynamically tell user of flakes.
        if [[ -f flake.nix ]] && command -v nix >/dev/null 2>&1 && [[ -z "$IN_NIX_SHELL" ]] && [[ ! -f .envrc ]]; then
            echo -e "\n\n❄️\tFound flake.nix, run 'create-envrc' to create a .envrc file here to load this flake automatically."
        fi
    else
        eza -a --icons
    fi
}

_zap_on_cd() {
    # Check if we are in an interactive shell to avoid
    # cluttering automated scripts
    [[ -t 1 ]] && _zap
}

autoload -Uz add-zsh-hook
add-zsh-hook chpwd _zap_on_cd

# Function: create-envrc
function create-envrc() {
    if [ -e .envrc ]
    then
        echo "⚠️  .envrc already here, can't safely insert."
        direnv reload
        return 0
    fi

    if ! command -v nix > /dev/null 2>&1
    then
        echo "󱄅  Nix is not installed!"
        return 1
    fi

    if ! command -v direnv > /dev/null 2>&1
    then
        echo "󱄅  Direnv is not installed!"
        return 1
    fi

    if ! [ -e flake.nix ]
    then
        echo "❌ No flake.nix file in this directory"
        return 1
    fi


    if ! [ -e .gitignore ] || ! grep -q "^\.direnv/" .gitignore
    then
        echo "💨 Adding direnv cache to gitignore"
        echo -e "\n# Ignore direnv cache\n.direnv/" >> .gitignore
    fi

    echo "if nix flake show &> /dev/null; then
      use flake
fi" >./.envrc

    direnv allow
}


rb() {
      jj --repository "$HOME/.dotfiles" file track "$HOME/.dotfiles/."

      if [ -f /etc/NIXOS ]; then
	echo "-> nixos rebuild switch --flake \"$HOME/.dotfiles#$(hostname)\""
        doas nixos-rebuild switch --flake "$HOME/.dotfiles#$(hostname)"
      else
	echo "-> home-manager switch --flake \"$HOME/.dotfiles#$(hostname)\""
        nix run home-manager -- switch --flake "$HOME/.dotfiles#$(hostname)"
      fi
}

