#!/usr/bin/env bash

CONFIG_PATH=$HOME/.config/machineconfig/default_ve

# check below if VIRTUAL_ENV is set
if [ -z "$VIRTUAL_ENV" ]; then  # no active ve ==> activate one.
  if [ -z "$1" ]; then  # nothing passed, activate default

    if [ -f ./.ve_path ]; then  # check if there is a .ve_path file in the current directory
      name=$(cat ./.ve_path)  # if yes, use it
      # replace ~ with $HOME
      name="${name/#\~/$HOME}"
      source "$name/bin/activate"
    elif [ -f $CONFIG_PATH ]; then  # check if there is a default ve stored in ~/.machineconfog/default_ve
      name=$(cat $CONFIG_PATH)  # if yes, use it
      source "$name/bin/activate"
    else  # no default ve found, using ve and setting it as default
      name="ve"
      source ~/venvs/$name/bin/activate
      mkdir ~/.config/machineconfig -p || true
      if [ -n "$VIRTUAL_ENV" ]; then
        echo $VIRTUAL_ENV > $CONFIG_PATH
     else
        echo "❌ No virtual environment active, cant echo it to $CONFIG_PATH"
      fi
    fi

  else
    name=$1
    source ~/venvs/$name/bin/activate
  fi

  if [ $? -eq 0 ]; then
    echo "✅ Activated Virtual Environment $VIRTUAL_ENV "
  fi

else  # there is an active_ve already.
  if [ -n "$1" ] && [ "$HOME/venvs/$1" != "$VIRTUAL_ENV" ]; then  # check if $1 is passed, if yes, activate it
    echo "🔻 Deactivating virtual environment $VIRTUAL_ENV "

    # if command -v deactivate >/dev/null 2>&1; then
    #     deactivate
      # fi
    if command -v deactivate >/dev/null 2>&1; then
        DEACTIVATE_PATH=$(command -v deactivate)
        if [[ $DEACTIVATE_PATH != *"ms-python"* ]]; then
            deactivate
        fi
    fi

    name=$1
    source ~/venvs/$name/bin/activate

    if [ $? -eq 0 ]; then
      echo "✅ Activated virtual environment $VIRTUAL_ENV "
    fi

  else  # user didn't pass anything.

    if [ -f ./.ve_path ]; then  # check if there is a .ve_path file in the current directory
      name=$(cat ./.ve_path)  # if yes, use it
      name="${name/#\~/$HOME}"  # replace ~ with $HOME

      if [ "$name" = "$VIRTUAL_ENV" ]; then
          echo "⚠️ Virtual environment $VIRTUAL_ENV already active"
      else
        echo "🔻 Deactivating virtual environment $VIRTUAL_ENV "
        source "$name/bin/activate"
        echo "✅ Activated Virtual Environment $VIRTUAL_ENV "
      fi

    else
      echo "⚠️ Virtual environment $VIRTUAL_ENV already active"
    fi

  fi

  # check if default is not defined, if so, define it as $VIRTUAL_ENV
  if [ ! -f $CONFIG_PATH ]; then
    mkdir ~/.config/machineconfig -p || true
    if [ -n "$VIRTUAL_ENV" ]; then
      echo $VIRTUAL_ENV > $CONFIG_PATH
    else
      echo "❌ No virtual environment active, cannot echo it to $CONFIG_PATH"
    fi
  fi
fi
