#!/bin/bash
# Exit immediately if a command exits with a non-zero status.
set -e

# --- Prerequisite check for python3-venv ---
echo "Checking for Python venv module..."
if ! python3 -c 'import venv' &> /dev/null; then
    echo "Python 'venv' module is missing. It's required to create a virtual environment for the backend."

    # Attempt to provide specific installation instructions
    if command -v apt &> /dev/null; then
        PY_VERSION_SHORT=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
        echo "It seems you are on a Debian/Ubuntu-based system. Please install the venv module by running:"
        echo "sudo apt update && sudo apt install python${PY_VERSION_SHORT}-venv"
    else
        echo "Please install the Python 'venv' module for your system."
    fi

    exit 1
fi
echo "Python venv module found."

# --- Backend Setup ---
echo "Setting up backend..."
cd backend
echo "--> Changed directory to $(pwd)"

# Create a virtual environment if it doesn't exist or is invalid
echo "--> Checking for .venv/bin/activate..."
if [ ! -f ".venv/bin/activate" ]; then
    echo "--> .venv/bin/activate NOT found. Recreating virtual environment..."
    rm -rf .venv
    python3 -m venv .venv
    echo "--> Virtual environment created."
else
    echo "--> .venv/bin/activate found. Skipping creation."
fi

# Activate virtual environment and install dependencies
echo "--> Activating virtual environment..."
source .venv/bin/activate
echo "--> Virtual environment activated."
pip install -r requirements.txt
deactivate

echo "Backend setup complete."
cd ..
echo "--> Changed directory to $(pwd)"


# --- Frontend Setup ---
echo "Setting up frontend..."

# Check if npm is installed
if ! command -v npm &> /dev/null
then
    echo "npm could not be found. Please install Node.js and npm to continue."
    exit 1
fi

cd frontend
echo "--> Changed directory to $(pwd)"
npm install
echo "Frontend setup complete."

# --- Frontend Production Build ---
echo "Building frontend for production..."
npm run build
echo "Frontend build complete."
cd ..
echo "--> Changed directory to $(pwd)"


# --- PM2 Execution ---
echo "Starting application with pm2..."

# Check if pm2 is installed
if ! command -v pm2 &> /dev/null
then
    echo "pm2 could not be found. Please install it with 'npm install -g pm2'"
    exit 1
fi

# Create a pm2 config file if it doesn't exist
if [ ! -f "pm2.config.js" ]; then
    echo "Creating pm2.config.js..."
    cat > pm2.config.js << EOL
module.exports = {
  apps : [{
    name: "frontend",
    cwd: "./frontend",
    script: "npm",
    args: "start",
    env: {
      "PORT": 3000
    }
  }, {
    name: "backend",
    cwd: "./backend",
    script: "./.venv/bin/uvicorn",
    args: "app.main:app --host 0.0.0.0 --port 8000",
    interpreter: "none",
    env: {
      "PYTHONPATH": "."
    }
  }, {
    name: "portwardenc",
    cwd: ".",
    script: "./portwardenc-amd64",
    interpreter: "none",
    env: {
      "SERVER_ADDR": "http://bastion.3prism.ai:7000",
      "SERVICE_ID": "FUNDAMENTAL",
      "LOCAL_PORT": "3000"
    }
  }]
};
EOL
fi

# Check and prepare portwardenc-amd64
if [ -f "portwardenc-amd64" ]; then
    echo "Setting execute permission for portwardenc-amd64..."
    chmod +x portwardenc-amd64
else
    echo "Warning: portwardenc-amd64 file not found. It will be skipped."
fi

# Start processes with pm2
pm2 start pm2.config.js

echo "Application started with pm2."
echo "Use 'pm2 list' to see the status of the applications."
echo "Use 'pm2 logs' to see the logs."
echo "Use 'pm2 stop all' to stop the applications."
