#!/bin/bash
# ==================================================
# DOCKER UTILS SCRIPT
# Math Platform - Docker Management Utilities
# ==================================================
# Usage: ./docker/docker-utils.sh [command]
# ==================================================

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

# Configuration
COMPOSE_FILE="docker-compose.yml"
DETAILED_COMPOSE="docker/docker-compose.yml"
PROJECT_DIR="/home/ren/Documents/math2"

# Functions
print_header() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}$1${NC}"
    echo -e "${BLUE}========================================${NC}"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

# Change to project directory
cd "$PROJECT_DIR" || exit 1

# ==================================================
# COMMANDS
# ==================================================

case "$1" in

    # --------------------------------------------------
    # START - Start all services
    # --------------------------------------------------
    start|up)
        print_header "Starting Math Platform Services"
        docker-compose up -d
        print_success "All services started"
        echo ""
        echo "Services:"
        docker-compose ps
        echo ""
        echo "URLs:"
        echo "  Frontend: http://localhost:3000"
        echo "  Backend:  http://localhost:3001"
        echo "  Nginx:    http://localhost"
        ;;

    # --------------------------------------------------
    # STOP - Stop all services
    # --------------------------------------------------
    stop|down)
        print_header "Stopping Math Platform Services"
        docker-compose down
        print_success "All services stopped"
        ;;

    # --------------------------------------------------
    # RESTART - Restart all services
    # --------------------------------------------------
    restart)
        print_header "Restarting Math Platform Services"
        docker-compose restart
        print_success "All services restarted"
        ;;

    # --------------------------------------------------
    # STATUS - Show service status
    # --------------------------------------------------
    status|ps)
        print_header "Math Platform Services Status"
        docker-compose ps
        echo ""
        echo "Health Checks:"
        docker-compose ps | grep -E "NAME|healthy"
        ;;

    # --------------------------------------------------
    # LOGS - Show service logs
    # --------------------------------------------------
    logs)
        SERVICE="${2:-}"
        if [ -z "$SERVICE" ]; then
            print_header "All Services Logs"
            docker-compose logs -f --tail=100
        else
            print_header "Logs for $SERVICE"
            docker-compose logs -f --tail=100 "$SERVICE"
        fi
        ;;

    # --------------------------------------------------
    # BUILD - Rebuild images
    # --------------------------------------------------
    build)
        print_header "Rebuilding Docker Images"
        SERVICE="${2:-}"
        if [ -z "$SERVICE" ]; then
            docker-compose build --no-cache
        else
            docker-compose build --no-cache "$SERVICE"
        fi
        print_success "Build completed"
        ;;

    # --------------------------------------------------
    # CLEAN - Remove containers, networks, volumes
    # --------------------------------------------------
    clean)
        print_header "Cleaning Docker Resources"
        read -p "This will remove all containers, networks, and volumes. Continue? (y/N) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            docker-compose down -v
            docker system prune -f
            print_success "Cleanup completed"
        else
            print_warning "Cleanup cancelled"
        fi
        ;;

    # --------------------------------------------------
    # DB BACKUP - Backup PostgreSQL database
    # --------------------------------------------------
    db-backup)
        print_header "Backing up PostgreSQL Database"
        BACKUP_DIR="$PROJECT_DIR/backups"
        mkdir -p "$BACKUP_DIR"
        BACKUP_FILE="$BACKUP_DIR/mathdb_$(date +%Y%m%d_%H%M%S).sql"
        docker-compose exec -T postgres pg_dump -U mathuser mathdb > "$BACKUP_FILE"
        print_success "Backup saved to: $BACKUP_FILE"
        ;;

    # --------------------------------------------------
    # DB RESTORE - Restore PostgreSQL database
    # --------------------------------------------------
    db-restore)
        if [ -z "$2" ]; then
            print_error "Please specify backup file: ./docker-utils.sh db-restore <backup-file>"
            exit 1
        fi
        print_header "Restoring PostgreSQL Database"
        BACKUP_FILE="$2"
        if [ ! -f "$BACKUP_FILE" ]; then
            print_error "Backup file not found: $BACKUP_FILE"
            exit 1
        fi
        docker-compose exec -T postgres psql -U mathuser mathdb < "$BACKUP_FILE"
        print_success "Database restored from: $BACKUP_FILE"
        ;;

    # --------------------------------------------------
    # DB SHELL - Access PostgreSQL shell
    # --------------------------------------------------
    db-shell)
        print_header "PostgreSQL Shell"
        docker-compose exec postgres psql -U mathuser -d mathdb
        ;;

    # --------------------------------------------------
    # REDIS SHELL - Access Redis shell
    # --------------------------------------------------
    redis-shell)
        print_header "Redis Shell"
        docker-compose exec redis redis-cli -a "${REDIS_PASSWORD:-redis_secure_password_2024}"
        ;;

    # --------------------------------------------------
    # SHELL - Access service shell
    # --------------------------------------------------
    shell)
        SERVICE="${2:-backend}"
        print_header "Shell for $SERVICE"
        docker-compose exec "$SERVICE" sh
        ;;

    # --------------------------------------------------
    # SCALE - Scale workers
    # --------------------------------------------------
    scale)
        WORKER="${2:-exercise-worker}"
        REPLICAS="${3:-2}"
        print_header "Scaling $WORKER to $REPLICAS replicas"
        docker-compose up -d --scale "$WORKER=$REPLICAS"
        print_success "Scaled $WORKER to $REPLICAS replicas"
        ;;

    # --------------------------------------------------
    # HEALTH - Check all services health
    # --------------------------------------------------
    health|check)
        print_header "Health Check"
        echo ""
        echo "PostgreSQL:"
        docker-compose exec postgres pg_isready -U mathuser -d mathdb && echo -e "  ${GREEN}Healthy${NC}" || echo -e "  ${RED}Unhealthy${NC}"
        echo ""
        echo "Redis:"
        docker-compose exec redis redis-cli -a "${REDIS_PASSWORD:-redis_secure_password_2024}" ping > /dev/null 2>&1 && echo -e "  ${GREEN}Healthy${NC}" || echo -e "  ${RED}Unhealthy${NC}"
        echo ""
        echo "Backend:"
        curl -s http://localhost:3001/health > /dev/null 2>&1 && echo -e "  ${GREEN}Healthy${NC}" || echo -e "  ${RED}Unhealthy${NC}"
        echo ""
        echo "Frontend:"
        curl -s http://localhost:3000 > /dev/null 2>&1 && echo -e "  ${GREEN}Healthy${NC}" || echo -e "  ${RED}Unhealthy${NC}"
        echo ""
        echo "Nginx:"
        curl -s http://localhost/health > /dev/null 2>&1 && echo -e "  ${GREEN}Healthy${NC}" || echo -e "  ${RED}Unhealthy${NC}"
        ;;

    # --------------------------------------------------
    # STATS - Show resource usage
    # --------------------------------------------------
    stats)
        print_header "Resource Usage"
        docker stats --no-stream
        ;;

    # --------------------------------------------------
    # PRISMA - Run Prisma commands
    # --------------------------------------------------
    prisma)
        COMMAND="${2:-}"
        case "$COMMAND" in
            migrate)
                print_header "Running Prisma Migrations"
                docker-compose exec backend npx prisma migrate deploy
                ;;
            generate)
                print_header "Generating Prisma Client"
                docker-compose exec backend npx prisma generate
                ;;
            studio)
                print_header "Starting Prisma Studio"
                docker-compose exec backend npx prisma studio
                ;;
            seed)
                print_header "Seeding Database"
                docker-compose exec backend npx prisma db seed
                ;;
            reset)
                print_header "Resetting Database"
                read -p "This will reset the database. Continue? (y/N) " -n 1 -r
                echo
                if [[ $REPLY =~ ^[Yy]$ ]]; then
                    docker-compose exec backend npx prisma migrate reset
                else
                    print_warning "Reset cancelled"
                fi
                ;;
            *)
                echo "Usage: $0 prisma [migrate|generate|studio|seed|reset]"
                exit 1
                ;;
        esac
        ;;

    # --------------------------------------------------
    # TEST - Run tests
    # --------------------------------------------------
    test)
        print_header "Running Tests"
        SERVICE="${2:-backend}"
        docker-compose exec "$SERVICE" npm test
        ;;

    # --------------------------------------------------
    # UPDATE - Update and restart services
    # --------------------------------------------------
    update)
        print_header "Updating Services"
        docker-compose pull
        docker-compose up -d --build
        print_success "Services updated"
        ;;

    # --------------------------------------------------
    # HELP - Show usage
    # --------------------------------------------------
    help|--help|-h|"")
        print_header "Docker Utils - Math Platform"
        echo ""
        echo "Usage: $0 [command] [options]"
        echo ""
        echo "Commands:"
        echo "  start, up              Start all services"
        echo "  stop, down             Stop all services"
        echo "  restart                Restart all services"
        echo "  status, ps             Show service status"
        echo "  logs [service]         Show logs (all services or specific)"
        echo "  build [service]        Rebuild images"
        echo "  clean                  Remove all containers, networks, volumes"
        echo ""
        echo "Database:"
        echo "  db-backup              Backup PostgreSQL database"
        echo "  db-restore <file>      Restore PostgreSQL database"
        echo "  db-shell               Access PostgreSQL shell"
        echo ""
        echo "Redis:"
        echo "  redis-shell            Access Redis shell"
        echo ""
        echo "Workers:"
        echo "  scale <worker> <n>     Scale worker to n replicas"
        echo "                         Workers: pdf-worker, exercise-worker, notification-worker"
        echo ""
        echo "Monitoring:"
        echo "  health, check          Check all services health"
        echo "  stats                  Show resource usage"
        echo ""
        echo "Development:"
        echo "  shell [service]        Access service shell (default: backend)"
        echo "  prisma <cmd>           Run Prisma commands:"
        echo "                         migrate, generate, studio, seed, reset"
        echo "  test [service]         Run tests"
        echo ""
        echo "Other:"
        echo "  update                 Update and restart services"
        echo "  help                   Show this help message"
        echo ""
        echo "Examples:"
        echo "  $0 start"
        echo "  $0 logs backend"
        echo "  $0 scale exercise-worker 3"
        echo "  $0 db-backup"
        echo "  $0 prisma migrate"
        echo ""
        ;;

    # --------------------------------------------------
    # UNKNOWN COMMAND
    # --------------------------------------------------
    *)
        print_error "Unknown command: $1"
        echo ""
        echo "Run '$0 help' for usage information"
        exit 1
        ;;

esac

exit 0
