#!/bin/bash
set -e

# Function to check internet connectivity
check_internet() {
    if ! curl -s --connect-timeout 5 https://registry-1.docker.io/v2/ > /dev/null; then
        echo "⚠️  No internet connection to Docker Hub - will use local images only"
        return 1
    fi
    return 0
}

# Function to pull image with retries
pull_image() {
    local image=$1
    local max_attempts=3
    local attempt=1
    local wait_time=5

    while [ $attempt -le $max_attempts ]; do
        echo "📥 Attempting to pull $image (Attempt $attempt/$max_attempts)..."
        if podman pull $image; then
            echo "✅ Successfully pulled $image"
            return 0
        fi
        echo "⚠️  Pull attempt $attempt failed. Waiting before retry..."
        sleep $wait_time
        attempt=$((attempt + 1))
        wait_time=$((wait_time * 2))
    done
    return 1
}

# Function to clean up while preserving base images
cleanup_with_preserve() {
    echo "🧹 Cleaning up while preserving base images..."
    # Save the base image IDs if they exist
    local python_image_id=$(podman images -q python:3.12-slim)
    local postgres_image_id=$(podman images -q postgres:16-alpine)
    
    # Run system prune
    podman system prune -af
    
    # If we had base images, pull them again
    if [ ! -z "$python_image_id" ]; then
        echo "🔄 Restoring Python base image..."
        pull_image python:3.12-slim
    fi
    if [ ! -z "$postgres_image_id" ]; then
        echo "🔄 Restoring PostgreSQL base image..."
        pull_image postgres:16-alpine
    fi
}

echo "🚀 Starting local deployment process..."

# Check available disk space
echo "💾 Checking disk space..."
AVAILABLE_SPACE=$(df -h . | awk 'NR==2 {print $4}' | tr -d 'G' | tr -d 'i')
if [ "$AVAILABLE_SPACE" -lt 10 ]; then
    echo "⚠️  Low disk space detected (${AVAILABLE_SPACE}G available). Cleaning up..."
    cleanup_with_preserve
    echo "✅ Cleanup complete"
fi

# Check for required base images
echo "🔍 Checking for required base images..."
for image in "python:3.12-slim" "postgres:16-alpine"; do
    if podman images | grep -q "$image"; then
        echo "✅ $image found locally"
    else
        echo "⚠️  $image not found locally"
        if ! check_internet; then
            echo "⚠️  No internet connection - attempting to build without base image"
        else
            echo "📦 Pulling $image from Docker Hub..."
            if ! pull_image "$image"; then
                echo "⚠️  Failed to pull $image - attempting to build without it"
            fi
        fi
    fi
done

# Create necessary directories and set permissions
echo "📁 Setting up directories..."
mkdir -p instance logs db_data db_backups
chmod -R 777 instance logs db_data db_backups

# Generate a secure secret key if not exists
if [ ! -f .env ]; then
    echo "🔑 Generating new secret key..."
    echo "SECRET_KEY=$(openssl rand -hex 32)" > .env
    echo "DATABASE_URL=postgresql://mold_user:mold_password@db:5432/mold_cost_calculator" >> .env
fi

# Clear template cache
echo "🧹 Clearing template cache..."
find . -type d -name "__pycache__" -exec rm -r {} +
find . -type f -name "*.pyc" -delete

# Stop and remove existing containers
echo "🧹 Cleaning up existing containers..."
podman-compose down 2>/dev/null || true

# Build the containers with retry logic
echo "📦 Building containers..."
max_build_attempts=3
build_attempt=1

while [ $build_attempt -le $max_build_attempts ]; do
    echo "🏗️  Build attempt $build_attempt/$max_build_attempts..."
    if podman-compose build; then
        echo "✅ Build successful"
        break
    fi
    if [ $build_attempt -eq $max_build_attempts ]; then
        echo "❌ Build failed after $max_build_attempts attempts"
        exit 1
    fi
    echo "⚠️  Build attempt $build_attempt failed. Waiting before retry..."
    sleep $((build_attempt * 5))
    build_attempt=$((build_attempt + 1))
done

# Start the containers
echo "🚀 Starting containers..."
podman-compose up -d

# Wait for database to be ready
echo "⏳ Waiting for database to be ready..."
max_wait=30
wait_count=0
while [ $wait_count -lt $max_wait ]; do
    if podman exec mold_cost_db pg_isready -U mold_user -d mold_cost_calculator >/dev/null 2>&1; then
        echo "✅ Database is ready"
        break
    fi
    echo "⏳ Waiting for database... ($((wait_count + 1))/$max_wait)"
    sleep 1
    wait_count=$((wait_count + 1))
done

if [ $wait_count -eq $max_wait ]; then
    echo "❌ Database failed to start within timeout"
    echo "📝 Checking container logs..."
    podman-compose logs db
    exit 1
fi

# Check if the containers are running
if podman-compose ps | grep -q "Up"; then
    echo "✅ Deployment complete!"
    echo "🌐 Application is available at: http://localhost:5003"
    echo "📝 To view logs: podman-compose logs"
    echo "📝 To view app logs: podman-compose logs web"
    echo "📝 To view db logs: podman-compose logs db"
    echo "🛑 To stop: podman-compose down"
else
    echo "❌ Containers failed to start. Check logs with: podman-compose logs"
    exit 1
fi 