#!/bin/bash

ENV=$1

if [ -z "$ENV" ]; then
  echo "Usage: $0 [dev|qa|staging|prod]"
  exit 1
fi

echo "Deploying backend to $ENV"

# Define port based on environment to avoid collisions
case "$ENV" in
  dev)
    PORT=8000
    ;;
  qa)
    PORT=8001
    ;;
  staging)
    PORT=8002
    ;;
  prod|main)
    PORT=8003
    ;;
  *)
    echo "Unknown environment: $ENV"
    exit 1
    ;;
esac

if [ "$ENV" = "prod" ] || [ "$ENV" = "main" ]; then
  cd ~/public_html/insuranceborder.com/backend || exit 1
else
  cd ~/public_html/$ENV.insuranceborder.com/backend || exit 1
fi

# Setup virtual environment if it doesn't exist
if [ ! -d "venv" ]; then
  python3 -m venv venv
fi

source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

# Run database migrations
echo "Running database migrations..."
if [ -n "$DATABASE_URL" ]; then
  echo "Injecting DATABASE_URL from CI/CD environment variable..."
  echo "DATABASE_URL=$DATABASE_URL" > .env
elif [ ! -f ".env" ] && [ -f "env/$ENV.env.example" ]; then
  cp "env/$ENV.env.example" .env
fi

if [ -f ".env" ]; then
  sed -i 's/localhost/127.0.0.1/g' .env
fi

if ! alembic upgrade head > migration.log 2>&1; then
  echo "WARNING: Database migrations failed to execute automatically. Log snippet:"
  tail -n 10 migration.log
  echo "Continuing backend server deployment..."
else
  echo "Database migrations completed successfully."
fi

# Auto-generate or update .htaccess reverse proxy rules in parent public_html directory
if [ "$ENV" = "prod" ] || [ "$ENV" = "main" ]; then
  WEB_ROOT=~/public_html/insuranceborder.com
else
  WEB_ROOT=~/public_html/$ENV.insuranceborder.com
fi

mkdir -p "$WEB_ROOT"
HTACCESS_FILE="$WEB_ROOT/.htaccess"

echo "Writing unified Apache Reverse Proxy and SPA rules to $HTACCESS_FILE..."
cat <<EOT > "$HTACCESS_FILE"
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  # 1. Reverse Proxy API Requests to FastAPI Backend for $ENV (Port $PORT)
  RewriteRule ^api/(.*)$ http://127.0.0.1:$PORT/api/\$1 [P,L]
  RewriteRule ^backend/docs(.*)$ http://127.0.0.1:$PORT/docs\$1 [P,L]
  RewriteRule ^backend/openapi.json$ http://127.0.0.1:$PORT/openapi.json [P,L]

  # 2. React SPA Fallback (EXCLUDING /api requests)
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_URI} !^/api/
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
EOT

# Stop the existing server running on this port
echo "Stopping existing backend process on port $PORT..."
PID=$(lsof -t -i:$PORT)
if [ -n "$PID" ]; then
  kill -9 $PID
fi

# Launch backend in background
echo "Starting backend on port $PORT..."
nohup uvicorn main:app --host 127.0.0.1 --port $PORT > backend.log 2>&1 &

echo "Backend deployed successfully to $ENV on port $PORT"
