################################################################################
# Use direnv to automatically load/unload the flox environment on directory change.
# Requires having the flox-direnv.sh function installed.
#
# curl -o "${HOME}/.config/direnv/lib/flox-direnv.sh" "https://raw.githubusercontent.com/flox/flox-direnv/v1.1.0/direnv.rc"                                                                                                                                                                                                                              │
# Which we have sourced directly into this file to not require external setup.
#
# Usage: use_flox [...]
#
# Loads the environment variables from a Flox envrionment
# By default, uses the ".flox" directory to load the envrionment from
# You can also specify a remote envrionment as follows
# 
# ```
# use_flox --remote=<owner>/<name>
# ```
# or
# ```
# use_flox --trust --remote=<owner>/<name>
# ```
#
# Where <owner>/<name> is the name of the remote environment on FloxHub
#
# You can also specify another directory to load the environment from
#
# ```
# use_flox --dir=<path>
# ```
#
# Where <path> is the path to a directory containing a ".flox" directory
#
# Custom commands aren't supported, since we use the `flox activate` command to dump and load the environment
#
function use_flox() {
    if [[ ! -d ".flox" ]]; then
        printf "direnv(use_flox): \`.flox\` directory not found\n" >&2
        printf "direnv(use_flox): Did you run \`flox init\` in this directory?\n" >&2
        return 1
    fi

    direnv_load flox activate "$@" -- "$direnv" dump

    if [[ $# == 0 ]]; then
        watch_dir ".flox/env/"
        watch_file ".flox/env.json"
        watch_file ".flox/env.lock"
    fi
}

# Load personal environment variables if they exist
dotenv_if_exists .env.local

# Only use flox when the installed CLI matches the repository pin. Checking
# before activation prevents a different CLI schema from rewriting tracked
# environment files.
if has flox && [ -f .flox/env/manifest.toml ]; then
  required_flox_version="$(<.flox-cli-version)"
  installed_flox_version="$(flox --version 2>/dev/null)"

  if [[ "${installed_flox_version}" == "${required_flox_version}" ]]; then
    use flox
  else
    log_error "nke requires Flox ${required_flox_version}; found ${installed_flox_version}."
    log_error "Flox activation was skipped to avoid modifying tracked environment files."
  fi
fi
