#!/bin/bash

# Orbit App Builder Deployment Script
set -e

# 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 Docker is installed
check_docker() {
    if ! command -v docker &> /dev/null; then
        print_error "Docker is not installed. Please install Docker first."
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose is not installed. Please install Docker Compose first."
        exit 1
    fi
    
    print_success "Docker and Docker Compose are installed"
}

# Check if .env file exists
check_env() {
    if [ ! -f .env ]; then
        print_warning ".env file not found. Creating from template..."
        cp env.example .env
        print_warning "Please edit .env file with your production values before continuing."
        print_warning "Required variables:"
        print_warning "  - DATABASE_URL (MongoDB connection string)"
        print_warning "  - OPENAI_API_KEY"
        print_warning "  - SESSION_SECRET (secure random string)"
        print_warning "  - CORS_ORIGIN (your domain)"
        print_warning "  - VITE_SUPABASE_URL"
        print_warning "  - VITE_SUPABASE_ANON_KEY"
        print_warning "  - SUPABASE_SERVICE_ROLE_KEY"
        exit 1
    fi
    
    print_success ".env file found"
}

# Load environment variables
load_env() {
    print_status "Loading environment variables..."
    export $(cat .env | grep -v '^#' | xargs)
}

# Create necessary directories
create_directories() {
    print_status "Creating necessary directories..."
    mkdir -p uploads
    mkdir -p ssl
    print_success "Directories created"
}

# Build and start services
deploy() {
    print_status "Building and starting services..."
    
    # Stop existing containers
    docker-compose down --remove-orphans
    
    # Build images
    docker-compose build --no-cache
    
    # Start services
    docker-compose up -d
    
    print_success "Services started successfully"
}

# Wait for services to be ready
wait_for_services() {
    print_status "Waiting for services to be ready..."
    
        # Wait for MongoDB
    print_status "Waiting for MongoDB..."
    timeout=60
    while ! docker-compose exec -T mongodb mongosh --eval "db.adminCommand('ping')" > /dev/null 2>&1; do
      if [ $timeout -le 0 ]; then
        print_error "MongoDB failed to start within 60 seconds"
        exit 1
      fi
      sleep 1
      timeout=$((timeout - 1))
    done
    print_success "MongoDB is ready"
    
    # Wait for Redis
    print_status "Waiting for Redis..."
    timeout=30
    while ! docker-compose exec -T redis redis-cli ping > /dev/null 2>&1; do
        if [ $timeout -le 0 ]; then
            print_error "Redis failed to start within 30 seconds"
            exit 1
        fi
        sleep 1
        timeout=$((timeout - 1))
    done
    print_success "Redis is ready"
    
    # Wait for app
    print_status "Waiting for application..."
    timeout=60
    while ! curl -f http://localhost:8080/api/health > /dev/null 2>&1; do
        if [ $timeout -le 0 ]; then
            print_error "Application failed to start within 60 seconds"
            exit 1
        fi
        sleep 2
        timeout=$((timeout - 2))
    done
    print_success "Application is ready"
}

# Run database migrations
run_migrations() {
    print_status "Running database migrations..."
    
    # Wait a bit for the app to be fully ready
    sleep 5
    
    # MongoDB doesn't need migrations like PostgreSQL, but we can check connection
    print_status "Checking database connection..."
    docker-compose exec app node -e "
      const { MongoClient } = require('mongodb');
      const client = new MongoClient(process.env.DATABASE_URL);
      client.connect().then(() => {
        // Debug logging removed for production
        client.close();
        process.exit(0);
      }).catch(err => {
        // Debug logging removed for production
        process.exit(1);
      });
    "
    
    print_success "Database migrations completed"
}

# Show deployment status
show_status() {
    print_status "Deployment Status:"
    echo ""
    docker-compose ps
    echo ""
    print_success "Application is running at: http://localhost:8080"
    print_success "API health check: http://localhost:8080/api/health"
    echo ""
    print_warning "For production deployment:"
    print_warning "1. Configure SSL certificates in nginx.conf"
    print_warning "2. Set up proper domain in CORS_ORIGIN"
    print_warning "3. Use strong SESSION_SECRET"
    print_warning "4. Configure proper database credentials"
}

# Main deployment function
main() {
    print_status "Starting Orbit App Builder deployment..."
    
    check_docker
    check_env
    load_env
    create_directories
    deploy
    wait_for_services
    run_migrations
    show_status
    
    print_success "Deployment completed successfully!"
}

# Handle script arguments
case "${1:-}" in
    "stop")
        print_status "Stopping services..."
        docker-compose down
        print_success "Services stopped"
        ;;
    "restart")
        print_status "Restarting services..."
        docker-compose restart
        print_success "Services restarted"
        ;;
    "logs")
        docker-compose logs -f
        ;;
    "status")
        docker-compose ps
        ;;
    "clean")
        print_status "Cleaning up..."
        docker-compose down -v --remove-orphans
        docker system prune -f
        print_success "Cleanup completed"
        ;;
    *)
        main
        ;;
esac 