#!/usr/bin/env bash
# Canonical agent-facing Python entry point for the staged task-local runtime.
#
# Usage:
#     ./python.sh your_script.py
#     ./python.sh -c "import numpy; print(numpy.__version__)"
#
# Resolves the pinned NumPy/SciPy runtime declared in the nearby runtime_env
# directory (pyproject.toml + uv.lock). If `uv` is available the locked
# environment is used verbatim (--frozen: the lockfile is never re-resolved or
# updated). If it is not, we fall back to the ambient interpreter and say so on
# stderr, so a version mismatch is visible rather than silent.
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Resolve the pinned runtime wherever this wrapper has been staged. In the
# submission tree it sits at input/software/, next to input/runtime_env/; the
# task prompt places it at base/software/, with the runtime at
# base/input/runtime_env/. Both are checked so the wrapper works either way
# rather than depending on one staging convention.
RUNTIME_ENV=""
for _cand in "${HERE}/../runtime_env" "${HERE}/../input/runtime_env" \
             "${HERE}/runtime_env" "${HERE}/../../input/runtime_env"; do
    if [ -f "${_cand}/pyproject.toml" ]; then
        RUNTIME_ENV="$(cd "${_cand}" && pwd)"
        break
    fi
done
if [ -z "${RUNTIME_ENV}" ]; then
    echo "python.sh: could not locate runtime_env (pyproject.toml) near ${HERE}" >&2
    echo "python.sh: falling back to the ambient python3." >&2
    exec python3 "$@"
fi

# Materialise the virtualenv OUTSIDE the task directory, so the staged inputs
# stay pristine (and work when mounted read-only). This temporary environment
# is expected and permitted -- it is not a modification of task files.
# Override the location with UV_PROJECT_ENVIRONMENT.
: "${UV_PROJECT_ENVIRONMENT:=${TMPDIR:-/tmp}/fem-benchmark-venv}"
export UV_PROJECT_ENVIRONMENT

if command -v uv >/dev/null 2>&1; then
    exec uv run --project "${RUNTIME_ENV}" --frozen python "$@"
fi

echo "python.sh: warning - 'uv' not found; falling back to the ambient python3." >&2
echo "python.sh: the pinned runtime in ${RUNTIME_ENV} is NOT guaranteed." >&2
exec python3 "$@"
