#!/usr/bin/env bash
# Remote Deployment Script for SMOM-DBIS-138
# Uses Proxmox API instead of pct command (for remote deployment)

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"

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

log_info "========================================="
log_info "SMOM-DBIS-138 Remote Deployment (API)"
log_info "========================================="
log_info ""

# Initialize Proxmox API
init_proxmox_api

# Get target node
TARGET_NODE="${PROXMOX_NODE:-}"
if [[ -z "$TARGET_NODE" ]]; then
    log_info "Detecting target node..."
    NODES_RESPONSE=$(proxmox_list_nodes)
    TARGET_NODE=$(echo "$NODES_RESPONSE" | jq -r '.data[0].node' 2>/dev/null || echo "pve")
    log_info "Using node: $TARGET_NODE"
fi

# Function to create container via API
create_container_api() {
    local vmid="$1"
    local hostname="$2"
    local ip_address="$3"
    local memory="${4:-2048}"
    local cores="${5:-2}"
    local disk="${6:-20}"
    local network_config="${7:-}"
    local storage="${8:-${PROXMOX_STORAGE}}"
    local template="${9:-${CONTAINER_OS_TEMPLATE}}"
    
    log_info "Creating container $vmid ($hostname) via API..."
    
    # Check if container already exists
    CONTAINERS_RESPONSE=$(proxmox_list_containers "$TARGET_NODE")
    if echo "$CONTAINERS_RESPONSE" | jq -e ".data[] | select(.vmid==$vmid)" &>/dev/null; then
        log_warn "Container $vmid already exists, skipping creation"
        return 0
    fi
    
    # Prepare container creation data
    local create_data="{
        \"vmid\": $vmid,
        \"ostemplate\": \"$template\",
        \"storage\": \"$storage\",
        \"hostname\": \"$hostname\",
        \"memory\": $memory,
        \"cores\": $cores,
        \"rootfs\": \"$storage:$disk\",
        \"net0\": \"$network_config\",
        \"unprivileged\": 0,
        \"features\": \"nesting=1,keyctl=1,firewall=1\"
    }"
    
    # Create container via API
    CREATE_RESPONSE=$(proxmox_api_call "POST" "/nodes/${TARGET_NODE}/lxc" "$create_data" "$TARGET_NODE")
    
    if echo "$CREATE_RESPONSE" | jq -e '.data' &>/dev/null || echo "$CREATE_RESPONSE" | grep -q "UPID"; then
        log_success "Container $vmid creation initiated"
        
        # Wait for container to be created
        log_info "Waiting for container $vmid to be ready..."
        local max_wait=60
        local waited=0
        while [ $waited -lt $max_wait ]; do
            CONTAINERS_RESPONSE=$(proxmox_list_containers "$TARGET_NODE")
            if echo "$CONTAINERS_RESPONSE" | jq -e ".data[] | select(.vmid==$vmid)" &>/dev/null; then
                log_success "Container $vmid is ready"
                return 0
            fi
            sleep 2
            waited=$((waited + 2))
        done
        
        log_warn "Container $vmid creation may still be in progress"
    else
        log_error "Failed to create container $vmid"
        log_debug "Response: $CREATE_RESPONSE"
        return 1
    fi
}

# Function to wait for container
wait_for_container() {
    local vmid="$1"
    local max_wait=120
    local waited=0
    
    log_info "Waiting for container $vmid to be ready..."
    while [ $waited -lt $max_wait ]; do
        STATUS=$(proxmox_get_container_status "$vmid" "$TARGET_NODE" 2>/dev/null || echo "")
        if [[ -n "$STATUS" ]]; then
            local status=$(echo "$STATUS" | jq -r '.data.status' 2>/dev/null || echo "")
            if [[ "$status" == "running" ]] || [[ -n "$status" ]]; then
                log_success "Container $vmid is ready"
                return 0
            fi
        fi
        sleep 2
        waited=$((waited + 2))
    done
    
    log_warn "Container $vmid may not be fully ready"
    return 1
}

# Function to upload file to container (via API - requires alternative method)
# Note: pct push requires local access, so we'll need to use alternative methods
upload_file_to_container() {
    local vmid="$1"
    local local_file="$2"
    local remote_path="$3"
    
    log_warn "File upload via API not directly supported"
    log_info "File: $local_file -> Container $vmid:$remote_path"
    log_info "You may need to:"
    log_info "  1. Copy file to Proxmox host first"
    log_info "  2. Use pct push from Proxmox host"
    log_info "  3. Or use alternative method (scp, etc.)"
}

# Function to execute command in container (via API)
execute_in_container() {
    local vmid="$1"
    local command="$2"
    
    log_info "Executing command in container $vmid: $command"
    
    # Use API to execute command
    local exec_data="{\"command\": [\"bash\", \"-c\", \"$command\"]}"
    EXEC_RESPONSE=$(proxmox_api_call "POST" "/nodes/${TARGET_NODE}/lxc/$vmid/exec" "$exec_data" "$TARGET_NODE")
    
    if echo "$EXEC_RESPONSE" | jq -e '.data' &>/dev/null; then
        log_success "Command executed in container $vmid"
        return 0
    else
        log_error "Failed to execute command in container $vmid"
        return 1
    fi
}

log_info "Remote deployment via API initialized"
log_info "Target node: $TARGET_NODE"
log_info ""
log_info "Note: Remote deployment has limitations:"
log_info "  - Container creation: ✅ Supported via API"
log_info "  - File upload (pct push): ⚠️  Requires local access"
log_info "  - Command execution: ✅ Supported via API"
log_info ""
log_info "For full functionality, consider:"
log_info "  1. Copying deployment package to Proxmox host"
log_info "  2. Running deployment scripts on Proxmox host"
log_info "  3. Or using hybrid approach (create via API, configure via SSH)"
log_info ""

# Parse command line arguments
DEPLOY_BESU="${DEPLOY_BESU:-true}"
DEPLOY_SERVICES="${DEPLOY_SERVICES:-true}"
DEPLOY_HYPERLEDGER="${DEPLOY_HYPERLEDGER:-true}"
DEPLOY_MONITORING="${DEPLOY_MONITORING:-true}"
DEPLOY_EXPLORER="${DEPLOY_EXPLORER:-true}"

while [[ $# -gt 0 ]]; do
    case $1 in
        --skip-besu)
            DEPLOY_BESU=false
            shift
            ;;
        --skip-services)
            DEPLOY_SERVICES=false
            shift
            ;;
        --skip-hyperledger)
            DEPLOY_HYPERLEDGER=false
            shift
            ;;
        --skip-monitoring)
            DEPLOY_MONITORING=false
            shift
            ;;
        --skip-explorer)
            DEPLOY_EXPLORER=false
            shift
            ;;
        *)
            log_error "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Example: Deploy a test container
log_info ""
log_info "=== Remote Deployment Example ==="
log_info ""
log_info "This script demonstrates remote deployment via API."
log_info "For full deployment, containers can be created via API,"
log_info "but file upload and installation may require local access."
log_info ""
log_info "Recommended approach:"
log_info "  1. Create containers via API (this script)"
log_info "  2. Copy files to Proxmox host"
log_info "  3. Run installation scripts on Proxmox host"
log_info ""

log_success "Remote deployment script ready"
log_info ""
log_info "To deploy containers, use the create_container_api function"
log_info "or modify this script to call deployment functions."

