# shellcheck shell=bash
# Intel oneAPI toolkit — lazy-loaded to avoid ~1.5s startup penalty.
# The full environment is sourced on first use of any Intel compiler/tool.
# To load manually: _load_oneapi

ONEAPI_SETVARS="/opt/intel/oneapi/setvars.sh"

if [[ -f "$ONEAPI_SETVARS" ]]; then
    _load_oneapi() {
        # Guard against double-loading
        if [[ "${_ONEAPI_LOADED:-0}" -eq 1 ]]; then
            return
        fi
        _ONEAPI_LOADED=1

        # Remove the lazy-load wrappers before sourcing
        local _cmd
        for _cmd in icc icpc icx icpx ifort ifx dpcpp; do
            unset -f "$_cmd" 2>/dev/null
        done

        # shellcheck disable=SC1090
        . "$ONEAPI_SETVARS" --force > /dev/null

        if [[ -n "$ONEAPI_ROOT" ]]; then
            case ":${LD_LIBRARY_PATH}:" in
                *":${ONEAPI_ROOT}/lib:"*) ;;
                *) export LD_LIBRARY_PATH="${ONEAPI_ROOT}/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" ;;
            esac
        fi
    }

    # Create wrapper functions for common Intel tools that trigger lazy-load
    _oneapi_lazy_wrap() {
        local cmd="$1"
        # shellcheck disable=SC2139
        eval "${cmd}() { _load_oneapi; command ${cmd} \"\$@\"; }"
    }

    for _oneapi_cmd in icc icpc icx icpx ifort ifx dpcpp; do
        _oneapi_lazy_wrap "$_oneapi_cmd"
    done
    unset -f _oneapi_lazy_wrap
    unset _oneapi_cmd
fi
