#!/usr/bin/env bash
set -euo pipefail

# --- Logging setup ---
LOGFILE="${LOGFILE:-$HOME/sde_setup.log}"
exec > >(tee -a "$LOGFILE") 2>&1
echo "=== $(date -Is) starting setup ==="

# --- Clean environment variables ---
unset PYTHONPATH LD_LIBRARY_PATH || true

# --- Locate Nix-provided libs (gcc & zlib) ---
GCC_LIB="$(ls -d /nix/store/*-gcc-*-lib/lib 2>/dev/null | head -n1 || true)"
ZLIB_SO="$(find /nix/store -maxdepth 3 -type f -name 'libz.so.1' 2>/dev/null | head -n1 || true)"

ZLIB_LIB=""
if [ -n "${ZLIB_SO:-}" ]; then
  ZLIB_LIB="$(dirname "$ZLIB_SO")"
elif [ -e /lib/x86_64-linux-gnu/libz.so.1 ]; then
  mkdir -p "$HOME/shimlibs"
  cp -f /lib/x86_64-linux-gnu/libz.so.1 "$HOME/shimlibs/"
  ZLIB_LIB="$HOME/shimlibs"
fi

# --- Construct LD_LIBRARY_PATH ---
if [ -n "${GCC_LIB:-}" ]; then
  export LD_LIBRARY_PATH="$GCC_LIB"
fi
if [ -n "${ZLIB_LIB:-}" ]; then
  export LD_LIBRARY_PATH="$ZLIB_LIB:${LD_LIBRARY_PATH:-}"
fi

# --- Python virtual environment (idempotent) ---
VENV="${VENV:-$HOME/sde_venv}"
if [ ! -d "$VENV" ]; then
  python3 -m venv "$VENV"
fi
# shellcheck disable=SC1090
source "$VENV/bin/activate"

# --- Pip install (quiet and cached) ---
export PIP_DISABLE_PIP_VERSION_CHECK=1 PIP_PROGRESS_BAR=off
python -m pip install --upgrade --quiet pip || true

if [ -n "${REQS:-}" ] && [ -f "$REQS" ]; then
  python -m pip install --quiet -r "$REQS"
else
  python -m pip install --quiet numpy pandas grpcio joblib scikit-learn tensorflow h5py
fi

# --- Summary ---
echo "VENV: $VENV"
echo "Python: $(python --version)"
echo "LD_LIBRARY_PATH: ${LD_LIBRARY_PATH:-<empty>}"
echo "Environment ready."
