#!/usr/bin/env bash
# Resolve the correct Racket for beagle's compiled bytecode.
# Source this from bin/* scripts: source "$(dirname "$0")/_beagle-racket"
# Then use $RACKET instead of "racket" and $RACO instead of "raco".
#
# Also PREPENDS the pinned racket onto PATH (exported), so child scripts with a
# bare `#!/usr/bin/env racket` shebang (beagle-syntax, -fix, -lsp, -repl, ...)
# inherit it instead of an ambient racket. Without this, invoking beagle outside
# its direnv shell (dispatched agent / CI / cron / a non-direnv subshell) picks
# the system racket, where beagle-lib is unlinked -> "collection not found:
# beagle/private/*" -> the syntax + recompile gate fails SILENTLY. The resolved
# path is cached in _BEAGLE_RACKET so nested sources skip the costly direnv call.

BEAGLE_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

RACKET="racket"
RACO="raco"

if [[ -z "${_BEAGLE_RACKET:-}" ]]; then
    # 1. This checkout's own direnv (the normal case).
    if [[ -d "$BEAGLE_ROOT/.direnv" ]]; then
        _direnv_racket="$(cd "$BEAGLE_ROOT" && direnv exec . which racket 2>/dev/null || true)"
    fi
    # 2. WORKTREE / un-allowed direnv: a `git worktree` has flake.nix but no
    #    allowed .direnv, so bare racket would be the SYSTEM version — which
    #    mismatches the flake-pinned bytecode and dies with "body of raco.rkt".
    #    Fall back to the canonical checkout's resolved racket (same flake.lock
    #    => same racket); internally consistent even for a worktree.
    if [[ -z "${_direnv_racket:-}" && -d "$HOME/code/beagle/.direnv" && "$BEAGLE_ROOT" != "$HOME/code/beagle" ]]; then
        _direnv_racket="$(cd "$HOME/code/beagle" && direnv exec . which racket 2>/dev/null || true)"
    fi
    # 3. Last resort: evaluate this flake directly (slow, but always correct).
    if [[ -z "${_direnv_racket:-}" && -f "$BEAGLE_ROOT/flake.nix" ]] && command -v nix >/dev/null 2>&1; then
        _direnv_racket="$(cd "$BEAGLE_ROOT" && nix develop --command which racket 2>/dev/null || true)"
    fi
    [[ -n "${_direnv_racket:-}" ]] && export _BEAGLE_RACKET="$_direnv_racket"
fi

if [[ -n "${_BEAGLE_RACKET:-}" ]]; then
    RACKET="$_BEAGLE_RACKET"
    RACO="$(dirname "$_BEAGLE_RACKET")/raco"
    case ":$PATH:" in
        *":$(dirname "$_BEAGLE_RACKET"):"*) ;;          # pinned racket already on PATH
        *) export PATH="$(dirname "$_BEAGLE_RACKET"):$PATH" ;;
    esac
fi
