#!/usr/bin/env bash
# Deploy Monitoring Stack on Proxmox VE LXC containers

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"
source "$PROJECT_ROOT/lib/proxmox-api.sh"
source "$PROJECT_ROOT/lib/container-utils.sh" 2>/dev/null || true

# Load configuration
load_config
load_config "$PROJECT_ROOT/config/network.conf" || true

VMID_MONITORING_START="${VMID_MONITORING_START:-130}"

log_info "Starting monitoring stack deployment..."

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 "${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 monitoring container
create_monitoring_container() {
    local vmid="$1"
    local hostname="$2"
    local ip_address="$3"
    
    log_info "Creating monitoring container: $hostname (VMID: $vmid, IP: $ip_address)"
    
    # Use DHCP for network configuration (matching successful containers 100-105)
    # Note: VLAN tagging removed - incompatible with unprivileged containers
    # Network isolation should be configured at bridge level or via firewall rules
    local network_config="bridge=${PROXMOX_BRIDGE:-vmbr0},name=eth0,ip=dhcp,type=veth"
    
    if pct list | grep -q "^\s*$vmid\s"; then
        log_warn "Container $vmid already exists, skipping creation"
    else
        log_info "Creating container $vmid..."
        pct create "$vmid" \
            "${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}" \
            --storage "${PROXMOX_STORAGE:-local-lvm}" \
            --hostname "$hostname" \
            --memory "${MONITORING_MEMORY:-4096}" \
            --cores "${MONITORING_CORES:-4}" \
            --rootfs "${PROXMOX_STORAGE:-local-lvm}:${MONITORING_DISK:-50}" \
            --net0 "$network_config" \
            --unprivileged "${CONTAINER_UNPRIVILEGED:-1}" \
            --swap "${CONTAINER_SWAP:-512}" \
            --onboot "${CONTAINER_ONBOOT:-1}" \
            --timezone "${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..."
    
    # Enable features
    pct set "$vmid" --features nesting=1,keyctl=1
    
    # Start container and wait for readiness (required for pct push and pct exec)
    if ! start_container_and_wait "$vmid"; then
        log_error "Failed to start container $vmid"
        return 1
    fi
    
    # Verify container is ready for file operations
    if ! verify_container_ready "$vmid"; then
        log_error "Container $vmid is not ready for file operations"
        return 1
    fi
    
    local install_script="$PROJECT_ROOT/install/monitoring-stack-install.sh"
    if [[ ! -f "$install_script" ]]; then
        log_error "Install script not found: $install_script"
        return 1
    fi
    
    # Configure locale in container to suppress warnings
    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
    
    log_info "Installing monitoring stack in container $vmid..."
    # Push install script (filter locale warnings but preserve errors)
    pct push "$vmid" "$install_script" /tmp/install.sh 2>&1 | grep -vE "(perl: warning|locale: Cannot set|Setting locale failed)" || true
    if ! pct exec "$vmid" -- test -f /tmp/install.sh 2>/dev/null; then
        log_error "Failed to push install script to container $vmid"
        return 1
    fi
    # Execute install script (filter locale warnings but preserve other output)
    local install_output
    install_output=$(pct exec "$vmid" -- bash -c "export LC_ALL=C; export LANG=C; bash /tmp/install.sh" 2>&1)
    local install_exit=$?
    echo "$install_output" | grep -vE "(perl: warning|locale: Cannot set|Setting locale failed|Falling back to the standard locale)" || true
    if [[ $install_exit -ne 0 ]]; then
        log_error "Failed to execute install script in container $vmid"
        return 1
    fi
    
    log_success "Monitoring stack $hostname (VMID: $vmid) deployed successfully"
    echo "$vmid:$hostname:$ip_address"
}

# Deploy monitoring stack
vmid=$VMID_MONITORING_START
hostname="monitoring-1"
ip_octet=130
ip_address="${MONITORING_SUBNET:-10.3.1}.${ip_octet}"

monitoring_info=$(create_monitoring_container \
    "$vmid" \
    "$hostname" \
    "$ip_address")

log_success "Monitoring stack deployment completed!"

