#!/usr/bin/env bash
# Common functions and utilities for DBIS Core deployment scripts

# Don't use set -euo pipefail here as this is a library file
set +euo pipefail

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1" >&2
}

log_success() {
    echo -e "${GREEN}[✓]${NC} $1" >&2
}

log_warn() {
    echo -e "${YELLOW}[WARNING]${NC} $1" >&2
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

log_debug() {
    if [[ "${DEBUG:-}" == "1" ]] || [[ "${DBIS_DEBUG:-}" == "1" ]]; then
        echo -e "${BLUE}[DEBUG]${NC} $1" >&2
    fi
}

# Error handling
error_exit() {
    log_error "$1"
    exit 1
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check if running as root (for Proxmox host operations)
check_root() {
    if [[ $EUID -ne 0 ]]; then
        error_exit "This script must be run as root for Proxmox host operations"
    fi
}

# Get script directory
get_script_dir() {
    local depth=1
    local script_dir
    
    while [[ $depth -lt 10 ]]; do
        if [[ -n "${BASH_SOURCE[$depth]:-}" ]]; then
            script_dir="$(cd "$(dirname "${BASH_SOURCE[$depth]}")" && pwd)"
            if [[ "$(basename "$script_dir")" != "lib" ]] && [[ "$(basename "$script_dir")" != "utils" ]]; then
                echo "$script_dir"
                return 0
            fi
        fi
        depth=$((depth + 1))
    done
    
    cd "$(dirname "${BASH_SOURCE[0]}")" && pwd
}

# Get project root
get_project_root() {
    local script_dir
    script_dir="$(get_script_dir)"
    
    # Navigate to proxmox project root
    if [[ "$script_dir" == */dbis_core/scripts/* ]]; then
        echo "$(cd "$script_dir/../../.." && pwd)"
    elif [[ "$script_dir" == */dbis_core/* ]]; then
        echo "$(cd "$script_dir/../.." && pwd)"
    else
        echo "$(cd "$script_dir/.." && pwd)"
    fi
}

# Load configuration
load_config() {
    local project_root
    project_root="$(get_project_root)"
    
    # Load main Proxmox config
    if [[ -f "${project_root}/smom-dbis-138-proxmox/config/proxmox.conf" ]]; then
        source "${project_root}/smom-dbis-138-proxmox/config/proxmox.conf" 2>/dev/null || true
    fi
    
    # Load DBIS Core config
    if [[ -f "${project_root}/dbis_core/config/dbis-core-proxmox.conf" ]]; then
        source "${project_root}/dbis_core/config/dbis-core-proxmox.conf" 2>/dev/null || true
    fi
    
    # Load .env file if exists
    if [[ -f "${HOME}/.env" ]]; then
        set -a
        source <(grep -E "^PROXMOX_" "${HOME}/.env" 2>/dev/null | sed 's/^/export /' || true)
        set +a
    fi
}

# Wait for container to be ready
wait_for_container() {
    local vmid="$1"
    local max_wait=60
    local waited=0
    
    while ! pct exec "$vmid" -- true 2>/dev/null && [[ $waited -lt $max_wait ]]; do
        sleep 2
        waited=$((waited + 2))
    done
    
    if ! pct exec "$vmid" -- true 2>/dev/null; then
        log_error "Container $vmid not ready after ${max_wait}s"
        return 1
    fi
    return 0
}

# Start container and wait
start_container_and_wait() {
    local vmid="$1"
    
    if ! pct start "$vmid" 2>/dev/null; then
        log_warn "Container $vmid may already be running"
    fi
    
    wait_for_container "$vmid"
}

# Verify container is ready for file operations
verify_container_ready() {
    local vmid="$1"
    local max_attempts=10
    local attempt=0
    
    while [[ $attempt -lt $max_attempts ]]; do
        if pct exec "$vmid" -- test -d /root 2>/dev/null; then
            return 0
        fi
        sleep 1
        attempt=$((attempt + 1))
    done
    
    return 1
}

# Check if container exists
container_exists() {
    local vmid="$1"
    pct list | grep -q "^\s*$vmid\s"
}

# Get container IP address
get_container_ip() {
    local vmid="$1"
    pct config "$vmid" | grep -E "^net0:" | sed -E 's/.*ip=([^,]+).*/\1/' | head -1
}

# Set container static IP
set_container_ip() {
    local vmid="$1"
    local ip_address="$2"
    local gateway="${3:-192.168.11.1}"
    
    pct set "$vmid" --net0 "bridge=${PROXMOX_BRIDGE:-vmbr0},name=eth0,ip=${ip_address}/24,gw=${gateway},type=veth" 2>/dev/null || {
        log_warn "Failed to set static IP for container $vmid"
        return 1
    }
    return 0
}

# Ensure OS template exists
ensure_os_template() {
    local template="${1:-${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}}"
    
    if pvesm list local | grep -q "$(basename "$template")"; then
        return 0
    fi
    
    log_warn "OS template not found: $template"
    return 1
}

