venv_dir=".venv"
currentvenv=""
get_project_root() {
    local current_dir="$PWD"
    while [[ "$current_dir" != "" && ! -d "$current_dir/$venv_dir" ]]; do
        current_dir=${current_dir%/*}
    done
    echo "$current_dir"
}

root_dir=$(get_project_root)

if [[ -z "$root_dir" || ! -d "$root_dir/$venv_dir" ]]; then
    echo "Unable to find the virtual environment folder."
    return
fi

if [[ $VIRTUAL_ENV != "" ]]; then
    currentvenv="${VIRTUAL_ENV##*/}"
fi

if [[ "$currentvenv" != "$venv_dir" ]]; then
    python_version=$(python3 --version 2>&1)
    echo "Switching to environment: $venv_dir | $python_version"
    source "$root_dir/$venv_dir/bin/activate"
fi

pip freeze > requirements.txt
sed -i "" -e "s/==/>=/" requirements.txt
pip install --upgrade pip
pip -q install -r requirements.txt
echo "Updated pip packages."

