#!/usr/bin/env bash
# Deploy Redis Cache Container for DBIS Core Banking System

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

# Source utilities
source "$PROJECT_ROOT/dbis_core/scripts/utils/common.sh"
source "$PROJECT_ROOT/dbis_core/scripts/utils/dbis-core-utils.sh" 2>/dev/null || true
source "$PROJECT_ROOT/smom-dbis-138-proxmox/lib/container-utils.sh" 2>/dev/null || true

# Load configuration
load_config

log_info "========================================="
log_info "DBIS Core - Redis Deployment"
log_info "========================================="
log_info ""

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

# Ensure OS template exists
ensure_os_template "${DBIS_CONTAINER_OS_TEMPLATE:-${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}}" || {
    error_exit "OS template not available. Please download it first."
}

# Function to create Redis container
create_redis_container() {
    local vmid="$1"
    local hostname="$2"
    local ip_address="$3"
    
    log_info "Creating Redis container: $hostname (VMID: $vmid, IP: $ip_address)"
    
    if container_exists "$vmid"; then
        log_warn "Container $vmid already exists, skipping creation"
    else
        log_info "Creating container $vmid..."
        pct create "$vmid" \
            "${DBIS_CONTAINER_OS_TEMPLATE:-${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}}" \
            --storage "${PROXMOX_STORAGE:-local-lvm}" \
            --hostname "$hostname" \
            --memory "${DBIS_REDIS_MEMORY:-4096}" \
            --cores "${DBIS_REDIS_CORES:-2}" \
            --rootfs "${PROXMOX_STORAGE:-local-lvm}:${DBIS_REDIS_DISK:-50}" \
            --net0 "bridge=${DBIS_NETWORK_BRIDGE:-vmbr0},name=eth0,ip=${ip_address}/24,gw=192.168.11.1,type=veth" \
            --unprivileged "${DBIS_CONTAINER_UNPRIVILEGED:-1}" \
            --swap "${DBIS_REDIS_SWAP:-512}" \
            --onboot "${DBIS_CONTAINER_ONBOOT:-1}" \
            --timezone "${DBIS_CONTAINER_TIMEZONE:-America/Los_Angeles}" \
            --features nesting=1,keyctl=1
        
        log_success "Container $vmid created"
    fi
    
    wait_for_container "$vmid"
    
    # Configure container
    log_info "Configuring container $vmid..."
    pct set "$vmid" --features nesting=1,keyctl=1
    
    # Start container and wait for readiness
    if ! start_container_and_wait "$vmid"; then
        log_error "Failed to start container $vmid"
        return 1
    fi
    
    # Verify container is ready
    if ! verify_container_ready "$vmid"; then
        log_error "Container $vmid is not ready for file operations"
        return 1
    fi
    
    # Configure locale
    pct exec "$vmid" -- bash -c "export LC_ALL=C; export LANG=C; echo 'export LC_ALL=C' >> /root/.bashrc; echo 'export LANG=C' >> /root/.bashrc; echo 'export LC_ALL=C' >> /etc/environment; echo 'export LANG=C' >> /etc/environment" 2>/dev/null || true
    
    # Update system
    log_info "Updating system packages..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get upgrade -y -qq" 2>&1 | grep -vE "(perl: warning|locale:)" || true
    
    # Install Redis
    log_info "Installing Redis ${DBIS_REDIS_VERSION:-7}..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get install -y -qq redis-server" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to install Redis"
        return 1
    }
    
    # Configure Redis
    log_info "Configuring Redis..."
    
    # Enable Redis to listen on all interfaces
    pct exec "$vmid" -- bash -c "sed -i 's/bind 127.0.0.1 ::1/bind 0.0.0.0/' /etc/redis/redis.conf" 2>/dev/null || true
    
    # Enable persistence
    pct exec "$vmid" -- bash -c "sed -i 's/# save 900 1/save 900 1/' /etc/redis/redis.conf" 2>/dev/null || true
    pct exec "$vmid" -- bash -c "sed -i 's/# save 300 10/save 300 10/' /etc/redis/redis.conf" 2>/dev/null || true
    pct exec "$vmid" -- bash -c "sed -i 's/# save 60 10000/save 60 10000/' /etc/redis/redis.conf" 2>/dev/null || true
    
    # Set maxmemory policy
    pct exec "$vmid" -- bash -c "echo 'maxmemory-policy allkeys-lru' >> /etc/redis/redis.conf" 2>/dev/null || true
    
    # Restart Redis
    log_info "Starting Redis service..."
    pct exec "$vmid" -- systemctl restart redis-server 2>/dev/null || true
    pct exec "$vmid" -- systemctl enable redis-server 2>/dev/null || true
    
    # Wait for Redis to be ready
    log_info "Waiting for Redis to be ready..."
    sleep 3
    
    # Test Redis connection
    if test_redis_connection "$vmid" "$ip_address"; then
        log_success "Redis is responding"
    else
        log_warn "Redis connection test inconclusive (redis-cli may not be installed)"
    fi
    
    # Configure firewall (if ufw is available)
    if pct exec "$vmid" -- command -v ufw >/dev/null 2>&1; then
        log_info "Configuring firewall..."
        pct exec "$vmid" -- bash -c "ufw allow 6379/tcp comment 'Redis'" 2>/dev/null || true
    fi
    
    log_success "Redis container $hostname (VMID: $vmid) deployed successfully"
    return 0
}

# Deploy Redis
log_info "Deploying Redis Cache..."
create_redis_container \
    "${VMID_DBIS_REDIS:-10120}" \
    "dbis-redis" \
    "${DBIS_REDIS_IP:-192.168.11.120}"

log_success "Redis deployment completed!"
log_info ""
log_info "Next steps:"
log_info "1. Deploy API: ./scripts/deployment/deploy-api.sh"
log_info "2. Deploy Frontend: ./scripts/deployment/deploy-frontend.sh"

