#!/bin/bash

# Production Automated Deployment Script for Insurance Border API
set -e

ENV=${1:-production}
DEPLOY_DIR=${2:-/var/www/insurance_border_backend}

echo "========================================="
echo " Starting deployment for environment: $ENV"
echo " Target Directory: $DEPLOY_DIR"
echo "========================================="

if [ -d "$DEPLOY_DIR" ]; then
    cd "$DEPLOY_DIR"
else
    echo "Error: Directory $DEPLOY_DIR does not exist."
    exit 1
fi

# 1. Pull latest changes from remote git repository
echo "[1/5] Fetching latest code from Git..."
git fetch --all
git checkout main || git checkout $ENV
git pull origin $(git rev-parse --abbrev-ref HEAD)

# 2. Virtual Environment Setup & Dependencies
echo "[2/5] Installing/updating Python dependencies..."
if [ ! -d "venv" ]; then
    python3 -m venv venv
fi

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

# 3. Database Migrations
echo "[3/5] Executing database migrations (Alembic)..."
if command -v alembic &> /dev/null; then
    alembic upgrade head
else
    echo "Warning: Alembic not found in PATH or venv. Skipping database migrations."
fi

# 4. Verify Static Directories
echo "[4/5] Ensuring uploads and static directories exist..."
mkdir -p uploads static

# 5. Service Reload / Restart
echo "[5/5] Reloading production service..."
if command -v systemctl &> /dev/null && systemctl is-active --quiet backend; then
    sudo systemctl reload backend || sudo systemctl restart backend
    echo "Systemd service 'backend' reloaded successfully."
elif command -v docker &> /dev/null && docker compose ps | grep -q insurance_border_backend; then
    docker compose up -d --build
    echo "Docker containers updated and reloaded successfully."
else
    echo "Notice: Neither Systemd 'backend' service nor Docker compose container was actively running."
    echo "Restarting Gunicorn backend manually..."
    pkill -f gunicorn || true
    nohup venv/bin/gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 127.0.0.1:8000 > backend.log 2>&1 &
fi

echo "========================================="
echo " Deployment to $ENV completed successfully!"
echo "========================================="
