#!/bin/bash
# Wrapper that ensures venv is active before running hogli.
# Needed for git hooks / lint-staged which may run outside an activated shell.

set -euo pipefail

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

if [ -z "${VIRTUAL_ENV:-}" ]; then
    # Only local venvs are considered here. Standalone hogli must never adopt
    # the main clone's venv: commands like `uv sync --active` would rewrite it
    # against this worktree. Hooks that need borrowing export VIRTUAL_ENV via
    # bin/helpers/worktree-borrow.sh before hogli runs.
    FOUND_VENV=""
    if [ -f "$REPO_ROOT/bin/helpers/worktree-borrow.sh" ]; then
        source "$REPO_ROOT/bin/helpers/worktree-borrow.sh"
        FOUND_VENV="$(posthog_find_venv "$REPO_ROOT")"
    fi

    if [ -n "$FOUND_VENV" ]; then
        source "$FOUND_VENV/bin/activate"
        PYTHON_CMD="$FOUND_VENV/bin/python"
    fi
else
    PYTHON_CMD="$VIRTUAL_ENV/bin/python"
fi

# Migration aid: after the common/hogli/ -> tools/hogli/ + tools/hogli-commands/
# restructure, users with stale venvs see `ModuleNotFoundError: hogli`. Catch it
# early and point at `uv sync`. Safe to delete once everyone has re-activated.
HOGLI_IMPORT_ERR="$("$PYTHON_CMD" -c "import hogli" 2>&1)" || true
if [[ -n "$HOGLI_IMPORT_ERR" && "$HOGLI_IMPORT_ERR" == *"No module named 'hogli'"* ]]; then
    cat >&2 <<'EOF'
error: the `hogli` package is not importable from your active venv.

It recently moved to tools/hogli/ (framework) + tools/hogli-commands/ (commands).
Your venv has stale paths — re-sync it:

    flox activate            # recommended (flox auto-runs uv sync)
    uv sync --active         # or sync directly

Then rerun your hogli command.
EOF
    exit 127
fi

exec "$PYTHON_CMD" -m hogli "$@"
