#!/bin/bash

# Portfolio Tracker Docker Services Management 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"
}

# Function to check if Docker is running
check_docker() {
    if ! docker info > /dev/null 2>&1; then
        print_error "Docker is not running. Please start Docker and try again."
        exit 1
    fi
}

# Function to check if docker-compose is available
check_docker_compose() {
    if ! command -v docker-compose > /dev/null 2>&1; then
        print_error "docker-compose is not installed. Please install it and try again."
        exit 1
    fi
}

# Function to start all services
start_services() {
    print_status "Starting all infrastructure services..."
    docker-compose up -d
    
    print_status "Waiting for services to be healthy..."
    sleep 10
    
    # Check service health
    check_service_health
    
    print_success "All services started successfully!"
    print_service_info
}

# Function to stop all services
stop_services() {
    print_status "Stopping all infrastructure services..."
    docker-compose down
    print_success "All services stopped successfully!"
}

# Function to restart all services
restart_services() {
    print_status "Restarting all infrastructure services..."
    docker-compose restart
    sleep 10
    check_service_health
    print_success "All services restarted successfully!"
}

# Function to check service health
check_service_health() {
    print_status "Checking service health..."
    
    services=("portfolio-mysql" "portfolio-mongodb" "portfolio-redis" "portfolio-kafka")
    
    for service in "${services[@]}"; do
        health=$(docker inspect --format='{{.State.Health.Status}}' "$service" 2>/dev/null || echo "no-healthcheck")
        if [ "$health" = "healthy" ]; then
            print_success "$service is healthy"
        elif [ "$health" = "no-healthcheck" ]; then
            status=$(docker inspect --format='{{.State.Status}}' "$service" 2>/dev/null || echo "not-found")
            if [ "$status" = "running" ]; then
                print_success "$service is running"
            else
                print_warning "$service status: $status"
            fi
        else
            print_warning "$service health: $health"
        fi
    done
}

# Function to show service information
print_service_info() {
    echo ""
    print_status "Service Information:"
    echo "┌─────────────────────────────────────────────────────────────┐"
    echo "│                    Infrastructure Services                  │"
    echo "├─────────────────────────────────────────────────────────────┤"
    echo "│ MySQL Database      │ localhost:3306                        │"
    echo "│ MongoDB Database    │ localhost:27017                       │"
    echo "│ Redis Cache         │ localhost:6379                        │"
    echo "│ Apache Kafka        │ localhost:9092                        │"
    echo "│ Zookeeper          │ localhost:2181                        │"
    echo "├─────────────────────────────────────────────────────────────┤"
    echo "│                    Development Tools                        │"
    echo "├─────────────────────────────────────────────────────────────┤"
    echo "│ Kafka UI           │ http://localhost:8080                 │"
    echo "│ Redis Commander    │ http://localhost:8081                 │"
    echo "│ Mongo Express      │ http://localhost:8082 (admin/admin)   │"
    echo "│ phpMyAdmin         │ http://localhost:8083 (root/root...)  │"
    echo "└─────────────────────────────────────────────────────────────┘"
    echo ""
}

# Function to show logs
show_logs() {
    if [ -n "$1" ]; then
        print_status "Showing logs for $1..."
        docker-compose logs -f "$1"
    else
        print_status "Showing logs for all services..."
        docker-compose logs -f
    fi
}

# Function to show service status
show_status() {
    print_status "Service Status:"
    docker-compose ps
}

# Function to clean up everything
cleanup() {
    print_warning "This will stop all services and remove all data volumes!"
    read -p "Are you sure? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_status "Stopping services and removing volumes..."
        docker-compose down -v
        print_status "Removing unused Docker resources..."
        docker system prune -f
        print_success "Cleanup completed!"
    else
        print_status "Cleanup cancelled."
    fi
}

# Function to backup data
backup_data() {
    backup_dir="./backups/$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$backup_dir"
    
    print_status "Creating backup in $backup_dir..."
    
    # MySQL backup
    print_status "Backing up MySQL..."
    docker exec portfolio-mysql mysqldump -u root -prootpassword portfolio_users > "$backup_dir/mysql_backup.sql"
    
    # MongoDB backup
    print_status "Backing up MongoDB..."
    docker exec portfolio-mongodb mongodump --username admin --password adminpassword --authenticationDatabase admin --db portfolio --out /tmp/backup
    docker cp portfolio-mongodb:/tmp/backup "$backup_dir/mongodb_backup"
    
    # Redis backup
    print_status "Backing up Redis..."
    docker exec portfolio-redis redis-cli BGSAVE
    docker cp portfolio-redis:/data/dump.rdb "$backup_dir/redis_backup.rdb"
    
    print_success "Backup completed in $backup_dir"
}

# Function to run database migrations
run_migrations() {
    print_status "Running database migrations..."
    
    # Wait for services to be ready
    print_status "Waiting for databases to be ready..."
    sleep 5
    
    # Run MySQL migrations (if any)
    print_status "Checking MySQL migrations..."
    # Add migration logic here when needed
    
    # Run MongoDB migrations (if any)
    print_status "Checking MongoDB migrations..."
    # Add migration logic here when needed
    
    print_success "Migrations completed!"
}

# Function to reset data
reset_data() {
    print_warning "This will reset all data to initial state!"
    read -p "Are you sure? (y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_status "Resetting data..."
        docker-compose down -v
        docker-compose up -d
        sleep 15
        run_migrations
        print_success "Data reset completed!"
    else
        print_status "Reset cancelled."
    fi
}

# Function to show help
show_help() {
    echo "Portfolio Tracker Docker Services Management"
    echo ""
    echo "Usage: $0 [COMMAND]"
    echo ""
    echo "Commands:"
    echo "  start       Start all infrastructure services"
    echo "  stop        Stop all infrastructure services"
    echo "  restart     Restart all infrastructure services"
    echo "  status      Show service status"
    echo "  logs [svc]  Show logs (optionally for specific service)"
    echo "  health      Check service health"
    echo "  info        Show service connection information"
    echo "  backup      Create backup of all data"
    echo "  cleanup     Stop services and remove all data (destructive)"
    echo "  reset       Reset all data to initial state (destructive)"
    echo "  migrate     Run database migrations"
    echo "  help        Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 start                 # Start all services"
    echo "  $0 logs mysql           # Show MySQL logs"
    echo "  $0 logs                 # Show all service logs"
    echo "  $0 backup               # Create data backup"
    echo ""
}

# Main script logic
main() {
    check_docker
    check_docker_compose
    
    case "${1:-help}" in
        start)
            start_services
            ;;
        stop)
            stop_services
            ;;
        restart)
            restart_services
            ;;
        status)
            show_status
            ;;
        logs)
            show_logs "$2"
            ;;
        health)
            check_service_health
            ;;
        info)
            print_service_info
            ;;
        backup)
            backup_data
            ;;
        cleanup)
            cleanup
            ;;
        reset)
            reset_data
            ;;
        migrate)
            run_migrations
            ;;
        help|--help|-h)
            show_help
            ;;
        *)
            print_error "Unknown command: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# Run main function with all arguments
main "$@"