# Tool versions pinned for reproducibility.
PYTHON_VERSION=3.10.20
UV_VERSION=0.11.7

# Temporarily export variables from .env files so they become environment variables.
if [ -f .env ]; then
  set -o allexport
  source .env
  set +o allexport
fi
if [ -f .env.local ]; then
  set -o allexport
  source .env.local
  set +o allexport
fi

# Install or update uv if missing or version mismatch.
UV_BIN="$PWD/.local/bin/uv"
if [ ! -x "$UV_BIN" ] || ! "$UV_BIN" --version | grep -q "$UV_VERSION"; then
  curl --proto '=https' --tlsv1.2 -LsSf \
    https://github.com/astral-sh/uv/releases/download/$UV_VERSION/uv-installer.sh \
    | UV_UNMANAGED_INSTALL="$PWD/.local/bin" sh
fi
export PATH="$PWD/.local/bin:$PATH"

# Ensure lockfile exists before syncing dependencies.
if [ ! -f uv.lock ]; then
  uv lock
fi

# Recreate virtual environment if missing or Python version mismatches.
VENV_PYTHON=""
if [ -x ".venv/bin/python" ]; then
  VENV_PYTHON=$(.venv/bin/python -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}')")
fi
if [ ! -d .venv ] || [ "$VENV_PYTHON" != "$PYTHON_VERSION" ]; then
  uv venv --python "$PYTHON_VERSION"
fi

# Activate virtual environment (export variables into current shell context).
if [ -f .venv/bin/activate ]; then
  set -o allexport
  source .venv/bin/activate
  set +o allexport
  unset PS1
fi

uv sync --frozen
