#!/usr/bin/env bash

# Resolve helper binaries with deterministic precedence:
# 1) explicit env override (e.g. HPPR_BIN)
# 2) sibling binary next to calling script
# 3) configured exec dir via HPPR_EXEC_DIR
# 4) PATH fallback
hppr_resolve_tool() {
    local env_var="$1"
    local tool_name="$2"
    local script_dir="$3"

    local override="${!env_var-}"
    if [[ -n "$override" ]]; then
        echo "$override"
        return 0
    fi

    local sibling="$script_dir/$tool_name"
    if [[ -x "$sibling" ]]; then
        echo "$sibling"
        return 0
    fi

    local exec_dir="${HPPR_EXEC_DIR:-}"
    if [[ -n "$exec_dir" ]] && [[ -x "$exec_dir/$tool_name" ]]; then
        echo "$exec_dir/$tool_name"
        return 0
    fi

    if command -v "$tool_name" >/dev/null 2>&1; then
        command -v "$tool_name"
        return 0
    fi

    echo "ERROR: Cannot resolve '$tool_name' (set $env_var, set HPPR_EXEC_DIR, or add '$tool_name' to PATH)" >&2
    return 1
}
