#!/bin/bash

# Docker Deployment Script for Developer Portfolio Tracker
# This script manages Docker Compose deployments

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=${COMPOSE_FILE:-"docker-compose.yml"}
ENV_FILE=${ENV_FILE:-".env.docker"}
PROJECT_NAME=${PROJECT_NAME:-"portfolio-tracker"}

echo -e "${GREEN}Developer Portfolio Tracker - Docker Deployment${NC}"
echo -e "${YELLOW}Compose file: ${COMPOSE_FILE}${NC}"
echo -e "${YELLOW}Environment file: ${ENV_FILE}${NC}"
echo -e "${YELLOW}Project name: ${PROJECT_NAME}${NC}"

# Function to check if required files exist
check_requirements() {
    local missing_files=()
    
    if [ ! -f "$COMPOSE_FILE" ]; then
        missing_files+=("$COMPOSE_FILE")
    fi
    
    if [ ! -f "$ENV_FILE" ]; then
        missing_files+=("$ENV_FILE")
    fi
    
    if [ ${#missing_files[@]} -gt 0 ]; then
        echo -e "${RED}Error: Missing required files:${NC}"
        for file in "${missing_files[@]}"; do
            echo -e "${RED}  - ${file}${NC}"
        done
        return 1
    fi
    
    return 0
}

# Function to start all services
start_services() {
    echo -e "${YELLOW}Starting all services...${NC}"
    
    docker-compose \
        -f "$COMPOSE_FILE" \
        --env-file "$ENV_FILE" \
        -p "$PROJECT_NAME" \
        up -d
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ All services started successfully!${NC}"
        show_status
    else
        echo -e "${RED}✗ Failed to start services${NC}"
        return 1
    fi
}

# Function to stop all services
stop_services() {
    echo -e "${YELLOW}Stopping all services...${NC}"
    
    docker-compose \
        -f "$COMPOSE_FILE" \
        -p "$PROJECT_NAME" \
        down
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ All services stopped successfully!${NC}"
    else
        echo -e "${RED}✗ Failed to stop services${NC}"
        return 1
    fi
}

# Function to restart all services
restart_services() {
    echo -e "${YELLOW}Restarting all services...${NC}"
    stop_services
    sleep 2
    start_services
}

# Function to show service status
show_status() {
    echo -e "${BLUE}Service Status:${NC}"
    docker-compose \
        -f "$COMPOSE_FILE" \
        -p "$PROJECT_NAME" \
        ps
}

# Function to show service logs
show_logs() {
    local service=${1:-""}
    
    if [ -n "$service" ]; then
        echo -e "${YELLOW}Showing logs for ${service}...${NC}"
        docker-compose \
            -f "$COMPOSE_FILE" \
            -p "$PROJECT_NAME" \
            logs -f "$service"
    else
        echo -e "${YELLOW}Showing logs for all services...${NC}"
        docker-compose \
            -f "$COMPOSE_FILE" \
            -p "$PROJECT_NAME" \
            logs -f
    fi
}

# Function to scale a service
scale_service() {
    local service=$1
    local replicas=$2
    
    if [ -z "$service" ] || [ -z "$replicas" ]; then
        echo -e "${RED}Error: Service name and replica count required${NC}"
        echo "Usage: $0 scale <service> <replicas>"
        return 1
    fi
    
    echo -e "${YELLOW}Scaling ${service} to ${replicas} replicas...${NC}"
    
    docker-compose \
        -f "$COMPOSE_FILE" \
        -p "$PROJECT_NAME" \
        up -d --scale "$service=$replicas"
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Successfully scaled ${service} to ${replicas} replicas${NC}"
    else
        echo -e "${RED}✗ Failed to scale ${service}${NC}"
        return 1
    fi
}

# Function to run health checks
health_check() {
    echo -e "${YELLOW}Running health checks...${NC}"
    
    local services=(
        "frontend:80:/health"
        "api-gateway:3000:/health"
        "user-service:3001:/health"
        "task-service:3002:/health"
        "analytics-service:3003:/health"
        "diagram-service:3004:/health"
    )
    
    local failed_checks=()
    
    for service_info in "${services[@]}"; do
        IFS=':' read -r service port path <<< "$service_info"
        
        echo -e "${BLUE}Checking ${service}...${NC}"
        
        # Wait for service to be ready
        sleep 2
        
        if curl -f -s "http://localhost:${port}${path}" > /dev/null; then
            echo -e "${GREEN}✓ ${service} is healthy${NC}"
        else
            echo -e "${RED}✗ ${service} health check failed${NC}"
            failed_checks+=("$service")
        fi
    done
    
    if [ ${#failed_checks[@]} -eq 0 ]; then
        echo -e "${GREEN}✓ All health checks passed!${NC}"
        return 0
    else
        echo -e "${RED}✗ Health checks failed for:${NC}"
        for service in "${failed_checks[@]}"; do
            echo -e "${RED}  - ${service}${NC}"
        done
        return 1
    fi
}

# Function to clean up everything
cleanup() {
    echo -e "${YELLOW}Cleaning up Docker resources...${NC}"
    
    # Stop and remove containers
    docker-compose \
        -f "$COMPOSE_FILE" \
        -p "$PROJECT_NAME" \
        down -v --remove-orphans
    
    # Remove unused images
    docker image prune -f
    
    # Remove unused volumes
    docker volume prune -f
    
    # Remove unused networks
    docker network prune -f
    
    echo -e "${GREEN}✓ Cleanup completed${NC}"
}

# Function to backup data
backup_data() {
    local backup_dir="backups/$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$backup_dir"
    
    echo -e "${YELLOW}Creating backup in ${backup_dir}...${NC}"
    
    # Backup MySQL data
    docker-compose \
        -f "$COMPOSE_FILE" \
        -p "$PROJECT_NAME" \
        exec -T mysql \
        mysqldump -u root -p"${MYSQL_ROOT_PASSWORD}" --all-databases > "${backup_dir}/mysql_backup.sql"
    
    # Backup MongoDB data
    docker-compose \
        -f "$COMPOSE_FILE" \
        -p "$PROJECT_NAME" \
        exec -T mongodb \
        mongodump --archive > "${backup_dir}/mongodb_backup.archive"
    
    echo -e "${GREEN}✓ Backup completed in ${backup_dir}${NC}"
}

# Main execution
case "${1:-help}" in
    "start"|"up")
        check_requirements && start_services
        ;;
    "stop"|"down")
        stop_services
        ;;
    "restart")
        check_requirements && restart_services
        ;;
    "status"|"ps")
        show_status
        ;;
    "logs")
        show_logs "$2"
        ;;
    "scale")
        scale_service "$2" "$3"
        ;;
    "health")
        health_check
        ;;
    "cleanup")
        cleanup
        ;;
    "backup")
        backup_data
        ;;
    "help")
        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 service)"
        echo "  scale <service> <replicas>  Scale a service"
        echo "  health          Run health checks on all services"
        echo "  cleanup         Clean up Docker resources"
        echo "  backup          Backup database data"
        echo "  help            Show this help message"
        echo ""
        echo "Environment variables:"
        echo "  COMPOSE_FILE    Docker Compose file (default: docker-compose.yml)"
        echo "  ENV_FILE        Environment file (default: .env.docker)"
        echo "  PROJECT_NAME    Docker Compose project name (default: portfolio-tracker)"
        ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        echo "Use '$0 help' for usage information"
        exit 1
        ;;
esac