#!/bin/bash

# Enhanced Start Script for Employee Workstation Activity Tracking System

# Function to display error and exit
error_exit() {
    echo "ERROR: $1" >&2
    exit 1
}

# Check if run.py exists
if [ ! -f "run.py" ]; then
    error_exit "run.py not found in the current directory. Please ensure you are in the project root."
fi

# Check for virtual environment and activate
if [ -d "venv" ]; then
    echo "Activating virtual environment..."
    source venv/bin/activate
else
    echo "WARNING: Virtual environment 'venv' not found. Attempting to run without it."
    echo "It is highly recommended to create and use a virtual environment."
    echo "You can create one with: python -m venv venv"
fi

# Determine mode (development or production)
MODE=${1:-dev} # Default to 'dev' if no argument is provided

if [[ "$MODE" == "dev" || "$MODE" == "development" ]]; then
    echo "Starting application in DEVELOPMENT mode..."

    echo "--- Python Diagnostics ---"
    echo "Which python: $(which python)"
    echo "Which python3: $(which python3)"
    echo "PYTHONPATH: $PYTHONPATH"
    ACTIVE_PYTHON_VERSION=$(python --version 2>&1 || python3 --version 2>&1)
    echo "Active Python version: $ACTIVE_PYTHON_VERSION"
    echo "Attempting to import dotenv directly via command line..."
    python -c "import dotenv; print('dotenv imported successfully. Path:', dotenv.__file__)" || python3 -c "import dotenv; print('dotenv imported successfully. Path:', dotenv.__file__)"
    echo "--- End Python Diagnostics ---"

    if command -v python &> /dev/null; then
        python run.py
    elif command -v python3 &> /dev/null; then
        python3 run.py
    else
        error_exit "Python interpreter (python or python3) not found. Please ensure Python is installed and in your PATH."
    fi
elif [[ "$MODE" == "prod" || "$MODE" == "production" ]]; then
    echo "Starting application in PRODUCTION mode using Gunicorn on port 5050..."
    if command -v gunicorn &> /dev/null; then
        # Check if Gunicorn is installed in the venv or globally
        gunicorn -w 4 -b 0.0.0.0:5050 "app:create_app()"
    else
        error_exit "Gunicorn not found. Please install it: pip install gunicorn"
    fi
else
    echo "Invalid mode specified: $MODE"
    echo "Usage: $0 [dev|development|prod|production]"
    error_exit "Please specify a valid mode."
fi 