# Used by the git hooks so they can run checks.
# e.g.
# . "$(dirname "$0")/_resolve"
# exec "$HARNESS" preflight
#
# Loads the harness executable.
# The harness executable was created in cli.py at `def record_harness`` called with `harness install`.
#
# $HARNESS is the path recorded by `record_harness`.
#
# Then, git hook does not require `uv` or `pip` or any specific environment layout.
#
# if is-agent-in-loop, check harness executable found via harness-path
RALPH_LOOP="${RALPH_LOOP:-0}"

if [ "$RALPH_LOOP" = "0" ]; then
    exit 0
fi

recorded="$(git rev-parse --git-common-dir)/harness-path"
HARNESS=""

if [ -r "$recorded" ]; then
    HARNESS="$(cat "$recorded")"
fi

if [ ! -x "$HARNESS" ]; then
    missing_harness="$HARNESS"
    HARNESS="$(command -v harness 2>/dev/null || true)"
    if [ ! -x "$HARNESS" ]; then
        printf "\nloopgate: hooks are not installed. Run 'harness install' in this repo.\n" >&2
        exit 1
    fi

    if [ -n "$missing_harness" ]; then
        printf \
            "\nloopgate: recorded harness executable %s is unavailable.\nRecording fallback %s in '.git/harness-path'.\n\n" \
            "$missing_harness" "$HARNESS" >&2
    else
        printf \
            "\nloopgate: no recorded harness executable was found.\nRecording fallback %s in '.git/harness-path'.\n\n" \
            "$HARNESS" >&2
    fi
    printf '%s\n' "$HARNESS" > "$recorded"
fi

export PATH="$(dirname "$HARNESS")${PATH:+:$PATH}"
