#!/bin/bash

# Redis Manager Script for Global Gala
# This script helps manage Redis container operations

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
COMPOSE_FILE="docker-compose.yml"
COMPOSE_PROD_FILE="docker-compose.prod.yml"
REDIS_CONTAINER="showprima_redis"
BACKUP_DIR="./backups/redis"

# Functions
print_help() {
    echo "Redis Manager for Global Gala"
    echo ""
    echo "Usage: $0 [command] [options]"
    echo ""
    echo "Commands:"
    echo "  start           Start Redis container"
    echo "  start-prod      Start Redis with production config"
    echo "  stop            Stop Redis container"
    echo "  restart         Restart Redis container"
    echo "  status          Show Redis status"
    echo "  logs            Show Redis logs"
    echo "  cli             Connect to Redis CLI"
    echo "  info            Show Redis info and statistics"
    echo "  backup          Create backup of Redis data"
    echo "  restore [file]  Restore from backup file"
    echo "  flush-cache     Flush cache database (DB 1)"
    echo "  flush-queue     Flush queue database (DB 2)"
    echo "  monitor         Monitor Redis commands in real-time"
    echo "  memory          Show memory usage statistics"
    echo "  test            Test Redis connection from Laravel"
    echo "  setup           Initial setup for Redis"
    echo "  help            Show this help message"
    echo ""
}

check_docker() {
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}Docker is not installed${NC}"
        exit 1
    fi
    
    if ! command -v docker-compose &> /dev/null; then
        echo -e "${RED}Docker Compose is not installed${NC}"
        exit 1
    fi
}

start_redis() {
    echo -e "${GREEN}Starting Redis container...${NC}"
    docker-compose -f $COMPOSE_FILE up -d redis
    sleep 2
    show_status
}

start_redis_prod() {
    echo -e "${GREEN}Starting Redis with production configuration...${NC}"
    
    if [ -z "$REDIS_PASSWORD" ]; then
        echo -e "${YELLOW}Warning: REDIS_PASSWORD not set in environment${NC}"
        echo "Please set REDIS_PASSWORD environment variable for production"
        exit 1
    fi
    
    docker-compose -f $COMPOSE_FILE -f $COMPOSE_PROD_FILE up -d redis
    sleep 2
    show_status
}

stop_redis() {
    echo -e "${YELLOW}Stopping Redis container...${NC}"
    docker-compose -f $COMPOSE_FILE stop redis
}

restart_redis() {
    echo -e "${YELLOW}Restarting Redis container...${NC}"
    stop_redis
    sleep 1
    start_redis
}

show_status() {
    echo -e "${GREEN}Redis Container Status:${NC}"
    docker-compose ps redis
    echo ""
    
    if docker-compose exec redis redis-cli ping &> /dev/null; then
        echo -e "${GREEN}✓ Redis is responding to ping${NC}"
        
        # Show basic stats
        echo ""
        echo "Quick Stats:"
        docker-compose exec redis redis-cli INFO server | grep -E "redis_version|uptime_in_seconds|uptime_in_days"
        docker-compose exec redis redis-cli INFO keyspace
    else
        echo -e "${RED}✗ Redis is not responding${NC}"
    fi
}

show_logs() {
    echo -e "${GREEN}Redis Logs:${NC}"
    docker-compose logs --tail=50 -f redis
}

redis_cli() {
    echo -e "${GREEN}Connecting to Redis CLI...${NC}"
    
    if [ ! -z "$REDIS_PASSWORD" ]; then
        docker-compose exec redis redis-cli -a "$REDIS_PASSWORD"
    else
        docker-compose exec redis redis-cli
    fi
}

show_info() {
    echo -e "${GREEN}Redis Information:${NC}"
    docker-compose exec redis redis-cli INFO ALL
}

backup_redis() {
    mkdir -p $BACKUP_DIR
    
    echo -e "${GREEN}Creating Redis backup...${NC}"
    
    # Trigger background save
    docker-compose exec redis redis-cli BGSAVE
    
    echo "Waiting for background save to complete..."
    sleep 5
    
    # Generate timestamp
    TIMESTAMP=$(date +%Y%m%d-%H%M%S)
    BACKUP_FILE="$BACKUP_DIR/redis-backup-$TIMESTAMP.rdb"
    
    # Copy backup file
    docker cp $REDIS_CONTAINER:/data/dump.rdb "$BACKUP_FILE"
    
    if [ -f "$BACKUP_FILE" ]; then
        echo -e "${GREEN}✓ Backup created: $BACKUP_FILE${NC}"
        ls -lh "$BACKUP_FILE"
        
        # Clean old backups (keep last 7 days)
        find $BACKUP_DIR -name "redis-backup-*.rdb" -mtime +7 -delete
        echo "Old backups cleaned (keeping last 7 days)"
    else
        echo -e "${RED}✗ Backup failed${NC}"
        exit 1
    fi
}

restore_redis() {
    if [ -z "$1" ]; then
        echo -e "${RED}Please specify backup file to restore${NC}"
        echo "Usage: $0 restore [backup-file]"
        echo ""
        echo "Available backups:"
        ls -lh $BACKUP_DIR/*.rdb 2>/dev/null || echo "No backups found"
        exit 1
    fi
    
    if [ ! -f "$1" ]; then
        echo -e "${RED}Backup file not found: $1${NC}"
        exit 1
    fi
    
    echo -e "${YELLOW}Warning: This will replace all current Redis data!${NC}"
    read -p "Are you sure you want to restore from $1? (y/N) " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        echo -e "${GREEN}Restoring Redis from backup...${NC}"
        
        # Stop Redis
        stop_redis
        
        # Copy backup file
        docker cp "$1" $REDIS_CONTAINER:/data/dump.rdb
        
        # Start Redis
        start_redis
        
        echo -e "${GREEN}✓ Redis restored from backup${NC}"
    else
        echo "Restore cancelled"
    fi
}

flush_cache() {
    echo -e "${YELLOW}This will flush all cache data (Database 1)${NC}"
    read -p "Are you sure? (y/N) " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker-compose exec redis redis-cli -n 1 FLUSHDB
        echo -e "${GREEN}✓ Cache database flushed${NC}"
    else
        echo "Operation cancelled"
    fi
}

flush_queue() {
    echo -e "${YELLOW}This will flush all queue data (Database 2)${NC}"
    read -p "Are you sure? (y/N) " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        docker-compose exec redis redis-cli -n 2 FLUSHDB
        echo -e "${GREEN}✓ Queue database flushed${NC}"
    else
        echo "Operation cancelled"
    fi
}

monitor_redis() {
    echo -e "${GREEN}Monitoring Redis commands (Ctrl+C to stop)...${NC}"
    docker-compose exec redis redis-cli MONITOR
}

show_memory() {
    echo -e "${GREEN}Redis Memory Usage:${NC}"
    docker-compose exec redis redis-cli INFO memory
    echo ""
    echo -e "${GREEN}Memory Doctor:${NC}"
    docker-compose exec redis redis-cli MEMORY DOCTOR
    echo ""
    echo -e "${GREEN}Memory Stats:${NC}"
    docker-compose exec redis redis-cli MEMORY STATS
}

test_connection() {
    echo -e "${GREEN}Testing Redis connection from Laravel...${NC}"
    
    # Check if Laravel is configured for Redis
    if ! grep -q "CACHE_DRIVER=redis" .env 2>/dev/null && \
       ! grep -q "QUEUE_CONNECTION=redis" .env 2>/dev/null && \
       ! grep -q "SESSION_DRIVER=redis" .env 2>/dev/null; then
        echo -e "${YELLOW}Warning: Redis not configured in .env file${NC}"
        echo "Add Redis configuration from .env.redis.example to your .env file"
    fi
    
    # Test connection using Laravel tinker
    php artisan tinker --execute="
        try {
            \$ping = Redis::ping();
            echo \"✓ Redis connection successful: \" . \$ping . PHP_EOL;
            
            // Test cache
            Cache::put('test:connection', 'success', 60);
            \$value = Cache::get('test:connection');
            echo \"✓ Cache test successful: \" . \$value . PHP_EOL;
            
            // Show database sizes
            for (\$i = 0; \$i < 6; \$i++) {
                Redis::select(\$i);
                \$size = Redis::dbSize();
                echo \"Database \$i: \$size keys\" . PHP_EOL;
            }
        } catch (Exception \$e) {
            echo \"✗ Redis connection failed: \" . \$e->getMessage() . PHP_EOL;
            exit(1);
        }
    "
}

setup_redis() {
    echo -e "${GREEN}Setting up Redis for Global Gala...${NC}"
    
    # Check Docker
    check_docker
    
    # Create necessary directories
    mkdir -p docker/redis
    mkdir -p $BACKUP_DIR
    
    # Check if .env exists
    if [ ! -f .env ]; then
        echo -e "${YELLOW}Creating .env file...${NC}"
        cp .env.example .env
    fi
    
    # Add Redis configuration to .env if not present
    if ! grep -q "CACHE_DRIVER=redis" .env; then
        echo -e "${YELLOW}Adding Redis configuration to .env...${NC}"
        cat .env.redis.example >> .env
        echo -e "${GREEN}✓ Redis configuration added to .env${NC}"
    else
        echo -e "${GREEN}✓ Redis already configured in .env${NC}"
    fi
    
    # Start Redis
    start_redis
    
    # Test connection
    sleep 2
    test_connection
    
    echo ""
    echo -e "${GREEN}✓ Redis setup complete!${NC}"
    echo ""
    echo "Next steps:"
    echo "1. Update your application code to use Redis for caching and queues"
    echo "2. Run 'php artisan queue:work redis' to process queued jobs"
    echo "3. Monitor Redis with: $0 monitor"
    echo "4. View Redis Commander UI at http://localhost:8081 (if enabled)"
}

# Main script logic
check_docker

case "$1" in
    start)
        start_redis
        ;;
    start-prod)
        start_redis_prod
        ;;
    stop)
        stop_redis
        ;;
    restart)
        restart_redis
        ;;
    status)
        show_status
        ;;
    logs)
        show_logs
        ;;
    cli)
        redis_cli
        ;;
    info)
        show_info
        ;;
    backup)
        backup_redis
        ;;
    restore)
        restore_redis "$2"
        ;;
    flush-cache)
        flush_cache
        ;;
    flush-queue)
        flush_queue
        ;;
    monitor)
        monitor_redis
        ;;
    memory)
        show_memory
        ;;
    test)
        test_connection
        ;;
    setup)
        setup_redis
        ;;
    help|"")
        print_help
        ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        print_help
        exit 1
        ;;
esac