#!/usr/bin/env bash
# Create all missing DBIS Core containers on Proxmox host
# This script creates 6 containers: PostgreSQL (primary + replica), Redis, API (primary + secondary), Frontend

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" 2>/dev/null || {
    # Fallback if common.sh doesn't exist
    RED='\033[0;31m'
    GREEN='\033[0;32m'
    YELLOW='\033[1;33m'
    BLUE='\033[0;34m'
    NC='\033[0m'
    log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
    log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
    log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
    log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
    error_exit() { log_error "$1"; exit 1; }
    command_exists() { command -v "$1" >/dev/null 2>&1; }
}

# Load configuration
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
STORAGE="${STORAGE:-local-lvm}"
TEMPLATE="${TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}"
NETWORK="${NETWORK:-vmbr0}"
GATEWAY="${GATEWAY:-192.168.11.1}"

# DBIS Core VMIDs and IPs
declare -A DBIS_CONTAINERS=(
    [10100]="dbis-postgres-primary:192.168.11.100:8:4:200:PostgreSQL Primary Database"
    [10101]="dbis-postgres-replica-1:192.168.11.101:8:4:200:PostgreSQL Replica Database"
    [10120]="dbis-redis:192.168.11.120:4:2:50:Redis Cache Server"
    [10150]="dbis-api-primary:192.168.11.150:8:4:100:Backend API Primary Server"
    [10151]="dbis-api-secondary:192.168.11.151:8:4:100:Backend API Secondary Server"
    [10130]="dbis-frontend:192.168.11.130:4:2:50:Frontend Admin Console"
)

# Check SSH access
check_ssh_access() {
    log_info "Checking SSH access to $PROXMOX_HOST..."
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} "echo 'SSH OK'" &>/dev/null; then
        log_success "SSH access confirmed"
        return 0
    else
        log_error "Cannot access $PROXMOX_HOST via SSH"
        log_error "Please ensure:"
        log_error "  1. SSH key is set up"
        log_error "  2. Host is reachable"
        log_error "  3. Root access is available"
        return 1
    fi
}

# Check if container exists
container_exists() {
    local vmid=$1
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
        "pct list | grep -q '^$vmid ' && echo 'exists' || echo 'missing'" 2>/dev/null || echo "error"
}

# Create a container
create_container() {
    local vmid=$1
    local hostname=$2
    local ip=$3
    local memory=$4
    local cores=$5
    local disk=$6
    local description="$7"
    
    log_info "Creating container $vmid: $hostname ($ip)..."
    
    # Check if already exists
    local exists=$(container_exists "$vmid")
    if [[ "$exists" == "exists" ]]; then
        log_warn "Container $vmid already exists, skipping..."
        return 0
    fi
    
    # Create container
    log_info "  Memory: ${memory}GB, CPU: ${cores} cores, Disk: ${disk}GB"
    
    ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} <<CREATE_CONTAINER_EOF
set -e
pct create $vmid $TEMPLATE \
    --hostname $hostname \
    --memory $((memory * 1024)) \
    --cores $cores \
    --rootfs $STORAGE:${disk} \
    --net0 name=eth0,bridge=$NETWORK,ip=$ip/24,gw=$GATEWAY \
    --description "$description" \
    --start 1 \
    --onboot 1 \
    --unprivileged 1 \
    --features nesting=1,keyctl=1 \
    --swap $((memory / 4 * 1024))
CREATE_CONTAINER_EOF
    
    if [ $? -eq 0 ]; then
        log_success "Container $vmid created successfully"
        
        # Wait for container to start
        log_info "  Waiting for container to start..."
        sleep 5
        
        # Check status
        local status=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${PROXMOX_HOST} \
            "pct status $vmid 2>/dev/null | awk '{print \$2}'" || echo "unknown")
        
        if [[ "$status" == "running" ]]; then
            log_success "  Container $vmid is running"
        else
            log_warn "  Container $vmid status: $status"
        fi
        
        return 0
    else
        log_error "Failed to create container $vmid"
        return 1
    fi
}

# Main execution
main() {
    echo ""
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "DBIS Core Container Creation Script"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    log_info "Target: $PROXMOX_HOST"
    log_info "Storage: $STORAGE"
    log_info "Template: $TEMPLATE"
    echo ""
    
    # Check SSH access
    if ! check_ssh_access; then
        exit 1
    fi
    
    echo ""
    log_info "This will create 6 DBIS Core containers:"
    log_info "  • 2 PostgreSQL databases (primary + replica)"
    log_info "  • 1 Redis cache server"
    log_info "  • 2 Backend API servers (primary + secondary)"
    log_info "  • 1 Frontend admin console"
    echo ""
    
    # Check for non-interactive mode
    if [[ "${NON_INTERACTIVE:-}" == "1" ]] || [[ ! -t 0 ]]; then
        log_info "Non-interactive mode: proceeding automatically"
    else
        read -p "Continue? (y/N): " -n 1 -r
        echo ""
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            log_info "Creation cancelled"
            exit 0
        fi
    fi
    
    local success_count=0
    local fail_count=0
    local skip_count=0
    
    echo ""
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Creating DBIS Core Containers"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    
    # Create containers in deployment order
    for vmid in 10100 10101 10120 10150 10151 10130; do
        IFS=':' read -r hostname ip memory cores disk description <<< "${DBIS_CONTAINERS[$vmid]}"
        
        local exists=$(container_exists "$vmid")
        if [[ "$exists" == "exists" ]]; then
            log_warn "Container $vmid already exists, skipping..."
            skip_count=$((skip_count + 1))
        elif create_container "$vmid" "$hostname" "$ip" "$memory" "$cores" "$disk" "$description"; then
            success_count=$((success_count + 1))
        else
            fail_count=$((fail_count + 1))
        fi
        echo ""
    done
    
    # Summary
    echo ""
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Creation Summary"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    echo ""
    log_success "Successfully created: $success_count containers"
    if [ $skip_count -gt 0 ]; then
        log_warn "Skipped (already exist): $skip_count containers"
    fi
    if [ $fail_count -gt 0 ]; then
        log_error "Failed: $fail_count containers"
    fi
    echo ""
    
    if [ $success_count -gt 0 ] || [ $skip_count -gt 0 ]; then
        log_info "Next steps:"
        log_info "  1. Run: cd $PROJECT_ROOT/dbis_core && ./scripts/deployment/deploy-all.sh"
        log_info "  2. Verify: ./scripts/management/status.sh"
        log_info "  3. Configure database: ./scripts/deployment/configure-database.sh"
    fi
    echo ""
}

main "$@"

