# Enables running the script from any directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VENV_DIR="$SCRIPT_DIR/.venv"
ENV_FILE="$SCRIPT_DIR/.env"

Green='\033[0;32m'
BGreen='\033[1;32m' # Bold Green
Cyan='\033[0;36m'
Color_Off='\033[0m'
Yellow='\033[0;33m'
BYellow='\033[1;33m'
BCyan='\033[1;36m'

# Check if the virtual environment directory exists
if [ -d "$VENV_DIR" ]; then

    # check if venv is activated
    if [ "$(which python)" == "$VENV_DIR/bin/python" ]; then
        echo "${Cyan}dev:${Color_Off}      ${Green}Virtual environment is activated.${Color_Off}"
    else
        echo "${Cyan}dev:${Color_Off}      ${BYellow}Your virtual environment is not activated.${Color_Off}"
        echo "${Cyan}dev:${Color_Off}      ${BYellow}Remember to activate your venv before installing new packages:${Color_Off}"
        echo "${Cyan}dev:${Color_Off}      ${BCyan}source .venv/bin/activate${Color_Off}"
    fi


    # Check if uvicorn is installed in venv
    if [ -f "$VENV_DIR/bin/uvicorn" ]; then

        # Check if .env file exists
        if [ -f "$ENV_FILE" ]; then
        
            #check if .env is in valid format
            if ! grep -q -E '^((export )?[A-Z_]+)=' "$ENV_FILE"; then
                echo "${Cyan}dev:${Color_Off}      ${BYellow}.env file is not in valid format.${Color_Off}"
                echo "${Cyan}dev:${Color_Off}      ${BYellow}Please check the .env.example file for the correct format.${Color_Off}"
                exit 1
            fi

            set -a
            if ! source .env; then
                echo "${Cyan}dev:${Color_Off}      ${BYellow}Error loading .env file. Format might be invalid.${Color_Off}"
                echo "${Cyan}dev:${Color_Off}      ${BYellow}Please check the .env.example file for the correct format.${Color_Off}"
                exit 1
            fi            
            # source .env
            set +a

            echo "${Cyan}dev:${Color_Off}      ${BGreen}.env file loaded.${Color_Off}"
        else
            echo "${Cyan}dev:${Color_Off}      No .env file found."
        fi
        echo "${Cyan}dev:${Color_Off}      ${BGreen}Starting uvicorn...${Color_Off}"
        # starting uvicorn from venv
        "$VENV_DIR/bin/uvicorn" app.main:app --reload --port=4000 --app-dir="$SCRIPT_DIR"
    else
        echo "${Cyan}dev:${Color_Off}      Uvicorn not found in virtual environment."
        echo "${Cyan}dev:${Color_Off}      lease install requirements.txt in virtual environment."
        echo "${Cyan}dev:${Color_Off}      source .venv/bin/activate"
        echo "${Cyan}dev:${Color_Off}      pip install -r requirements.txt"
    fi

else
    echo "${Cyan}dev:${Color_Off}      Virtual environment directory not found."
fi