# Source this file to set up the virtual environment
#
# > . .init_venv.sh
#
# To be used with our uv-based setup. Assumes python version and all dependencies are
# in pyproject.toml. Will finalize uv.sources editable libraries with uv pip compat.
#
# Once this has been done once, you can just use the normal virtual environment's
# 'activate' command to re-renter the virtual environment.
#
# You can also re-source this file to reinstall / update the project. Calls 'uv sync'
# and re-updates editable sources.

# Text output highlighting
bold=$(tput bold)
normal=$(tput sgr0)

VENV=".venv"
export PYRIGHT_PYTHON_FORCE_VERSION=latest

# Make sure we're out of any venvs
deactivate &> /dev/null

# Find if we have any editable local paths
regex="\{ *path *= *\".*\",.* *editable *= *true *\}"
MATCHES=$(grep -oP "$regex" pyproject.toml)
if [[ -n $MATCHES ]]; then
    # We have locally editable installs. Check for editable mode setting
    grep "config-settings *= *{ *editable_mode *= *\"compat\" *}" pyproject.toml > /dev/null
    if [ $? -ne 0 ]; then
        echo "${bold}ERROR: Locally editable package requested, but incorrect toml config${normal}"
        echo
        echo "Add to pyproject.toml:"
        echo
        echo "[tool.uv]"
        echo "config-settings = { editable_mode = \"compat\" }"
        echo
        return 1
    fi
fi

# Sync with uv
echo "${bold}Syncing environment${normal}"
# Check if installed
which uv &> /dev/null
if [ $? -ne 0 ]; then
    while true; do
        read -p "uv is not installed. Install it now? (y/n) " yn
        case $yn in
            [yY] )
                break
                ;;
            [nN] )
                echo "Exiting ..."
                return 1
                ;;
            * )
                echo "Invalid response. Please enter 'y' or 'n'"
                ;;
        esac
    done
    echo "Installing uv ..."
    curl -LsSf https://astral.sh/uv/install.sh | sh
    . $HOME/.local/bin/env
fi
uv sync

# activate and print version
echo "${bold}Activating environment${normal}"
. $VENV/bin/activate
$VENV/bin/python --version

# Install pre-commit scripts
echo "${bold}Installing git hooks${normal}"
pre-commit install
if [ $? -ne 0 ]; then
    return 1
fi

# print final hints
echo
echo "$VENV activated. To deactivate, use ${bold}\"deactivate\".${normal}"
