#!/usr/bin/env bash
# Migrate container to another Proxmox node

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

# Function to migrate container
migrate_container() {
    local vmid="$1"
    local target_node="$2"
    local storage="${3:-}"
    local migrate_storage="${4:-false}"
    
    log_info "Migrating container $vmid to node $target_node..."
    
    # Check if container exists
    if ! pct list | grep -q "^\s*$vmid\s"; then
        error_exit "Container $vmid does not exist"
    fi
    
    # Get current node
    local current_node
    current_node=$(proxmox_get_container_node "$vmid")
    
    if [[ "$current_node" == "$target_node" ]]; then
        log_warn "Container $vmid is already on node $target_node"
        return 0
    fi
    
    log_info "Current node: $current_node"
    log_info "Target node: $target_node"
    
    # Check if target node exists
    local nodes
    nodes=$(proxmox_list_nodes | jq -r '.data[].node' 2>/dev/null || echo "$target_node")
    if ! echo "$nodes" | grep -q "^${target_node}$"; then
        error_exit "Target node $target_node not found in cluster"
    fi
    
    # Check container status
    local container_status
    container_status=$(pct status "$vmid" | awk '{print $2}' || echo "unknown")
    log_info "Container status: $container_status"
    
    # Perform migration
    if proxmox_migrate_container "$vmid" "$target_node" "$storage" "$migrate_storage"; then
        log_success "Successfully migrated container $vmid to node $target_node"
        
        # Verify migration
        local new_node
        new_node=$(proxmox_get_container_node "$vmid")
        if [[ "$new_node" == "$target_node" ]]; then
            log_success "Migration verified: container is now on node $new_node"
        else
            log_warn "Migration verification failed: container on node $new_node (expected $target_node)"
        fi
    else
        error_exit "Migration failed"
    fi
}

# Function to list available nodes
list_nodes() {
    log_info "Available nodes in cluster:"
    local nodes_output
    nodes_output=$(proxmox_list_nodes 2>/dev/null)
    if command_exists jq && [[ -n "$nodes_output" ]]; then
        echo "$nodes_output" | jq -r '.data[] | "  - \(.node): \(.status)"' 2>/dev/null || {
            log_info "  - ${PROXMOX_NODE} (single node cluster)"
        }
    else
        # Fallback: use configured nodes
        if [[ -n "${PROXMOX_NODES:-}" ]]; then
            echo "$PROXMOX_NODES" | tr ',' '\n' | while read -r node; do
                log_info "  - $node"
            done
        else
            log_info "  - ${PROXMOX_NODE} (default node)"
        fi
    fi
}

# Main
if [[ $# -lt 2 ]]; then
    echo "Usage: $0 <VMID> <target_node> [storage_pool] [migrate_storage]"
    echo ""
    echo "Options:"
    echo "  VMID            - Container ID to migrate"
    echo "  target_node     - Target Proxmox node"
    echo "  storage_pool    - (Optional) Target storage pool"
    echo "  migrate_storage - (Optional) true/false to migrate storage (default: false)"
    echo ""
    echo "Examples:"
    echo "  $0 1000 pve2                    # Migrate container 1000 (validator) to pve2"
    echo "  $0 2500 pve3 local-lvm true     # Migrate container 2500 (RPC core) to pve3 with storage migration"
    echo ""
    list_nodes
    exit 1
fi

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

VMID="$1"
TARGET_NODE="$2"
STORAGE="${3:-}"
MIGRATE_STORAGE="${4:-false}"

migrate_container "$VMID" "$TARGET_NODE" "$STORAGE" "$MIGRATE_STORAGE"

log_success "Migration completed!"

