#!/bin/bash

# Source setenv.sh if not already loaded
if [ -z "$PROJECT" ]; then
    SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
    source "$SCRIPT_DIR/setenv.sh"
fi

activate() {
    # Choose Python interpreter
    if [ -n "$NETWORK_PYTHON" ]; then
        PYTHON_EXE="$NETWORK_PYTHON/bin/python"
    else
        PYTHON_EXE="python3"
    fi

    # Ensure venv exists
    if [ ! -d "$PROJECT/.venv" ]; then
        echo "Creating virtual environment..."
        "$PYTHON_EXE" -m venv "$PROJECT/.venv"
        if [ $? -ne 0 ]; then
            echo "ERROR: Failed to create virtual environment"
            return 1
        fi
    fi

    # Activate venv
    if [ -f "$PROJECT/.venv/bin/activate" ]; then
        source "$PROJECT/.venv/bin/activate"
        # Pin the interpreter
        export VIRTUAL_ENV_PYTHON="$PYTHON_EXE"
    else
        echo "ERROR: Virtual environment activation script not found"
        return 1
    fi
}

deactivate() {
    if [ -n "$VIRTUAL_ENV" ]; then
        deactivate 2>/dev/null || true
        unset VIRTUAL_ENV_PYTHON
    fi
}

# Call function based on argument
case "$1" in
    activate|activate_interpreter)
        activate
        ;;
    deactivate|deactivate_interpreter)
        deactivate
        ;;
    *)
        echo "Usage: $0 {activate|deactivate|activate_interpreter|deactivate_interpreter}"
        exit 1
        ;;
esac
