#!/usr/bin/env bash
# Verify Network Configuration
# Checks network connectivity and bandwidth to Proxmox host

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh" 2>/dev/null || {
    log_info() { echo "[INFO] $1"; }
    log_success() { echo "[✓] $1"; }
    log_error() { echo "[ERROR] $1"; }
    log_warn() { echo "[WARN] $1"; }
}

# Load configuration
load_config "$PROJECT_ROOT/config/proxmox.conf" 2>/dev/null || true

log_info "========================================="
log_info "Network Configuration Verification"
log_info "========================================="
log_info ""

# Check network connectivity
log_info "=== Network Connectivity ==="

# Get Proxmox host IP/name (if configured)
PROXMOX_HOST="${PROXMOX_HOST:-localhost}"
log_info "Proxmox host: $PROXMOX_HOST"

# Check if we can resolve the host
if command_exists ping; then
    if ping -c 1 -W 2 "$PROXMOX_HOST" &>/dev/null; then
        log_success "Proxmox host is reachable"
        
        # Get average latency
        LATENCY=$(ping -c 3 -W 2 "$PROXMOX_HOST" 2>/dev/null | grep "avg" | awk -F'/' '{print $5}' || echo "N/A")
        if [[ "$LATENCY" != "N/A" ]]; then
            log_info "  Average latency: ${LATENCY}ms"
            if (( $(echo "$LATENCY > 100" | bc -l 2>/dev/null || echo 0) )); then
                log_warn "  High latency detected (>100ms). May impact deployment performance."
            fi
        fi
    else
        log_warn "Cannot ping Proxmox host (may be normal if running locally)"
    fi
fi

# Check network interfaces
log_info ""
log_info "=== Network Interfaces ==="

if [[ -f /proc/net/dev ]]; then
    # List active network interfaces
    INTERFACES=$(ip -o link show 2>/dev/null | awk -F': ' '{print $2}' | grep -v "lo" || true)
    if [[ -n "$INTERFACES" ]]; then
        for iface in $INTERFACES; do
            if ip link show "$iface" 2>/dev/null | grep -q "state UP"; then
                log_info "  $iface: UP"
                
                # Get link speed if available
                if [[ -f "/sys/class/net/$iface/speed" ]]; then
                    SPEED=$(cat "/sys/class/net/$iface/speed" 2>/dev/null || echo "unknown")
                    if [[ "$SPEED" != "-1" ]] && [[ "$SPEED" != "unknown" ]]; then
                        if [[ $SPEED -ge 1000 ]]; then
                            log_success "    Speed: ${SPEED}Mbps (Gigabit or better - recommended)"
                        elif [[ $SPEED -ge 100 ]]; then
                            log_warn "    Speed: ${SPEED}Mbps (Fast Ethernet - may limit performance)"
                        else
                            log_warn "    Speed: ${SPEED}Mbps (Slow - may significantly impact deployment)"
                        fi
                    fi
                fi
            else
                log_info "  $iface: DOWN"
            fi
        done
    fi
else
    log_warn "Cannot check network interfaces (/proc/net/dev not available)"
fi

# Check Proxmox bridge configuration (if on Proxmox host)
log_info ""
log_info "=== Proxmox Bridge Configuration ==="

CONFIGURED_BRIDGE="${PROXMOX_BRIDGE:-vmbr0}"
log_info "Configured bridge: $CONFIGURED_BRIDGE"

if command_exists ip; then
    if ip link show "$CONFIGURED_BRIDGE" &>/dev/null; then
        log_success "Bridge '$CONFIGURED_BRIDGE' exists"
        
        BRIDGE_STATUS=$(ip link show "$CONFIGURED_BRIDGE" 2>/dev/null | grep -o "state [A-Z]*" | awk '{print $2}')
        log_info "  Status: $BRIDGE_STATUS"
        
        if [[ "$BRIDGE_STATUS" == "UP" ]]; then
            log_success "  Bridge is UP"
        else
            log_warn "  Bridge is DOWN - containers may not have network access"
        fi
    else
        log_error "Bridge '$CONFIGURED_BRIDGE' not found"
        log_info "  Available bridges:"
        ip link show type bridge 2>/dev/null | grep "^[0-9]" | awk -F': ' '{print "    - " $2}' || log_info "    (none found)"
    fi
fi

# Check DNS resolution (important for package downloads)
log_info ""
log_info "=== DNS Configuration ==="

if command_exists nslookup || command_exists host; then
    TEST_DOMAIN="github.com"
    if nslookup "$TEST_DOMAIN" &>/dev/null || host "$TEST_DOMAIN" &>/dev/null; then
        log_success "DNS resolution working ($TEST_DOMAIN)"
    else
        log_error "DNS resolution failed - package downloads may fail"
    fi
else
    log_warn "Cannot test DNS (nslookup/host not available)"
fi

# Check internet connectivity (for package downloads)
log_info ""
log_info "=== Internet Connectivity ==="

if command_exists curl; then
    if curl -s --max-time 5 https://github.com &>/dev/null; then
        log_success "Internet connectivity working (GitHub reachable)"
        
        # Test download speed (rough estimate)
        log_info "  Testing download speed..."
        SPEED_TEST=$(curl -s -o /dev/null -w "%{speed_download}" --max-time 10 https://github.com 2>/dev/null || echo "0")
        if [[ -n "$SPEED_TEST" ]] && [[ "$SPEED_TEST" != "0" ]]; then
            # Convert bytes/s to Mbps
            SPEED_MBPS=$(echo "scale=2; $SPEED_TEST * 8 / 1024 / 1024" | bc 2>/dev/null || echo "N/A")
            if [[ "$SPEED_MBPS" != "N/A" ]]; then
                log_info "  Approximate download speed: ${SPEED_MBPS} Mbps"
                if (( $(echo "$SPEED_MBPS > 100" | bc -l 2>/dev/null || echo 0) )); then
                    log_success "    Speed is good for deployment (recommended: >100 Mbps)"
                elif (( $(echo "$SPEED_MBPS > 10" | bc -l 2>/dev/null || echo 0) )); then
                    log_warn "    Speed is acceptable but may slow deployment (recommended: >100 Mbps)"
                else
                    log_warn "    Speed is slow - deployment may be significantly slower"
                    log_info "      Consider:"
                    log_info "        • Using local package mirrors"
                    log_info "        • Pre-caching packages"
                    log_info "        • Upgrading network connection"
                fi
            fi
        fi
    else
        log_warn "Internet connectivity test failed (may be normal in isolated networks)"
    fi
else
    log_warn "Cannot test internet connectivity (curl not available)"
fi

# Network optimization recommendations
log_info ""
log_info "=== Network Optimization Recommendations ==="
log_info ""
log_info "For optimal deployment performance:"
log_info "  ✓ Use Gigabit Ethernet (1 Gbps) or faster"
log_info "  ✓ Ensure low latency (<50ms) to Proxmox host"
log_info "  ✓ Use wired connection instead of wireless"
log_info "  ✓ Consider local package mirrors for apt"
log_info "  ✓ Pre-cache OS templates (saves 5-10 minutes)"
log_info "  ✓ Monitor network usage during deployment"
log_info ""
log_info "Expected network usage:"
log_info "  • OS template download: ~200-500 MB (one-time)"
log_info "  • Package downloads: ~500 MB - 2 GB per container"
log_info "  • Configuration file transfers: Minimal"
log_info "  • Total for 67 containers: ~35-135 GB"
log_info ""

log_success "Network configuration verification complete"

