#!/bin/bash

# Deploy script for Biblical Guide production server
# Fetches latest code from production branch and deploys

set -e

echo "🚀 Starting deployment..."

# Configuration
REPO_URL="https://git.noru1.ro/andrei/ghidul-biblic.git"
BRANCH="production"
APP_NAME="ghidul-biblic"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if .env file exists
if [ ! -f .env ]; then
    print_error ".env file not found. Please create it with required environment variables."
    exit 1
fi

# Validate required environment variables
print_status "Validating environment variables..."
required_vars=("DATABASE_URL" "JWT_SECRET" "AZURE_OPENAI_KEY" "AZURE_OPENAI_ENDPOINT")
missing_vars=()

for var in "${required_vars[@]}"; do
    if ! grep -q "^${var}=" .env; then
        missing_vars+=("$var")
    fi
done

if [ ${#missing_vars[@]} -ne 0 ]; then
    print_error "Missing required environment variables: ${missing_vars[*]}"
    exit 1
fi

print_success "Environment variables validated"

# Stop existing containers
print_status "Stopping existing containers..."
docker compose down || true

# Fetch latest code from production branch
print_status "Fetching latest code from $BRANCH branch..."
git fetch origin $BRANCH
git reset --hard origin/$BRANCH

print_success "Code updated to latest $BRANCH branch"

# Show current commit
CURRENT_COMMIT=$(git rev-parse --short HEAD)
COMMIT_MSG=$(git log -1 --pretty=format:"%s")
print_status "Current commit: $CURRENT_COMMIT - $COMMIT_MSG"

# Build and start the application
print_status "Building and starting application..."
docker compose up --build -d

# Wait for application to be ready
print_status "Waiting for application to start..."
sleep 10

# Health check
print_status "Performing health check..."
for i in {1..30}; do
    if curl -f http://localhost:3010/api/health >/dev/null 2>&1; then
        print_success "Application is healthy and running on port 3010"
        break
    fi

    if [ $i -eq 30 ]; then
        print_error "Health check failed after 30 attempts"
        print_status "Showing container logs:"
        docker compose logs --tail=50
        exit 1
    fi

    sleep 2
done

# Show running containers
print_status "Running containers:"
docker compose ps

# Cleanup old images (keep last 3)
print_status "Cleaning up old Docker images..."
docker image prune -f >/dev/null 2>&1 || true

print_success "🎉 Deployment completed successfully!"
print_status "Application is now running at: http://localhost:3010"
print_status "API health endpoint: http://localhost:3010/api/health"