#!/usr/bin/env bash
# Shared .env loader for CHNB shell scripts.
#
# Caller should set PROJECT_ROOT before sourcing this file. The load order is
# user config -> project .env -> CHNB_ENV_FILE so the explicit file has highest
# priority, matching util.config/load_public_env.

if [ -z "${CHNB_SHELL_ENV_LOADED:-}" ]; then
    export CHNB_SHELL_ENV_LOADED=1

    _chnb_source_env_file() {
        local path="$1"
        if [ -n "$path" ] && [ -f "$path" ]; then
            set -a
            # shellcheck disable=SC1090
            . "$path"
            set +a
        fi
    }

    if [ "${CHNB_ENV_OVERRIDE:-1}" != "0" ] && \
       [ "${CHNB_ENV_OVERRIDE:-1}" != "false" ] && \
       [ "${CHNB_ENV_OVERRIDE:-1}" != "no" ]; then
        _chnb_source_env_file "$HOME/.config/chnb/.env"
        if [ -n "${PROJECT_ROOT:-}" ]; then
            _chnb_source_env_file "$PROJECT_ROOT/.env"
        fi
        _chnb_source_env_file "${CHNB_ENV_FILE:-}"
    fi

    unset -f _chnb_source_env_file
fi
