set -euo pipefail

if command -v pip &> /dev/null; then
    pip show -qq uv || pip install uv || true
fi

UV_BIN=$(python -c 'import uv; print(uv.find_uv_bin())' 2>/dev/null || which uv || echo "uv")

cat > {{ user_script_name }}.py << 'USER_SCRIPT_EOF'
{{ user_script_contents | escape_braces }}
USER_SCRIPT_EOF

cat > {{ runner_name }}.py << 'RUNNER_EOF'
{{ runner_contents | escape_braces }}
RUNNER_EOF

cat > {{ script_name }}.in << 'PAYLOAD_EOF'
{{ payload }}
PAYLOAD_EOF

# use temp directory for uv cache to avoid filesystem locking issues
# on HPC systems where home directories are on NFS/GPFS
# only set if admin hasn't already configured a better location
{% raw %}if [ -z "${{UV_CACHE_DIR:-}}" ]; then
    export UV_CACHE_DIR="${{TMPDIR:-/tmp}}/uv-cache-${{USER:-$(id -un)}}"
fi{% endraw %}
mkdir -p "$UV_CACHE_DIR"

"$UV_BIN" run --managed-python --with {{ version_spec }} \
  {{ runner_name }}.py

echo "__GROUNDHOG_RESULT__"
cat {{ script_name }}.out
