#!/usr/bin/env bash
# Complete temporary VM deployment orchestration
# This script orchestrates the entire temporary VM deployment process

set -euo pipefail

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

source "$PROJECT_ROOT/lib/common.sh"

# Load configuration
load_config "$PROJECT_ROOT/config/proxmox.conf"
load_config "$PROJECT_ROOT/config/network.conf" || {
    log_warn "network.conf not found, using defaults"
}

TEMP_VM_IP="${BESU_TEMP_IP:-192.168.11.90}"
SOURCE_PROJECT="${1:-/opt/smom-dbis-138}"

log_info "========================================="
log_info "Besu Temporary VM Deployment"
log_info "========================================="
log_info ""

# Check prerequisites
log_info "Checking prerequisites..."

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

check_root

if [[ ! -d "$SOURCE_PROJECT" ]]; then
    error_exit "Source project not found: $SOURCE_PROJECT"
fi

log_success "Prerequisites checked"
log_info ""

# Step 1: Create VM
log_info "Step 1: Creating temporary VM..."
if "$SCRIPT_DIR/deploy-besu-temp-vm.sh"; then
    log_success "VM created successfully"
else
    log_error "VM creation failed"
    exit 1
fi

log_info ""
log_info "Waiting for VM to be fully ready..."
sleep 10

# Step 2: Setup Docker
log_info ""
log_info "Step 2: Setting up Docker in VM..."
if ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 "root@$TEMP_VM_IP" \
    "cd /opt/smom-dbis-138-proxmox && ./scripts/deployment/setup-docker-besu.sh $SOURCE_PROJECT" 2>/dev/null; then
    log_success "Docker setup completed"
else
    log_warn "Docker setup may have had issues, continuing..."
fi

# Step 3: Copy configuration files
log_info ""
log_info "Step 3: Copying configuration files..."
if "$SCRIPT_DIR/copy-configs-to-vm.sh" "$SOURCE_PROJECT"; then
    log_success "Configuration files copied"
else
    log_error "Failed to copy configuration files"
    exit 1
fi

# Step 4: Setup node configs in VM
log_info ""
log_info "Step 4: Setting up node configurations in VM..."
ssh "root@$TEMP_VM_IP" << 'EOF'
cd /opt/besu

# Copy configs to validators
for i in {1..5}; do
    mkdir -p "validators/validator-$i/config"
    cp besu-configs/config-validator.toml "validators/validator-$i/config/config-validator.toml" 2>/dev/null || true
done

# Copy configs to sentries
for i in {1..4}; do
    mkdir -p "sentries/sentry-$i/config"
    cp besu-configs/config-sentry.toml "sentries/sentry-$i/config/config-sentry.toml" 2>/dev/null || true
done

# Copy configs to RPC nodes
for i in {1..3}; do
    mkdir -p "rpc/rpc-$i/config"
    cp besu-configs/config-rpc.toml "rpc/rpc-$i/config/config-rpc.toml" 2>/dev/null || true
done

echo "Configuration files set up"
EOF

if [[ $? -eq 0 ]]; then
    log_success "Node configurations set up"
else
    log_warn "Some configuration setup may have failed"
fi

# Step 5: Start containers
log_info ""
log_info "Step 5: Starting Besu containers..."
log_info "This may take a few minutes..."
if ssh "root@$TEMP_VM_IP" "cd /opt/besu && docker compose up -d" 2>/dev/null; then
    log_success "Containers started"
else
    log_error "Failed to start containers"
    exit 1
fi

# Wait for containers to initialize
log_info ""
log_info "Waiting for containers to initialize..."
sleep 30

# Step 6: Validate deployment
log_info ""
log_info "Step 6: Validating deployment..."
if "$PROJECT_ROOT/scripts/validation/validate-besu-temp-vm.sh"; then
    log_success "Deployment validated successfully"
else
    log_warn "Validation found some issues, but deployment may still be functional"
fi

log_info ""
log_success "========================================="
log_success "Temporary VM Deployment Complete!"
log_success "========================================="
log_info ""
log_info "VM Details:"
log_info "  IP Address: $TEMP_VM_IP"
log_info "  VMID: ${BESU_TEMP_VMID:-9000}"
log_info ""
log_info "RPC Endpoints:"
log_info "  RPC-1: http://$TEMP_VM_IP:8545"
log_info "  RPC-2: http://$TEMP_VM_IP:8547"
log_info "  RPC-3: http://$TEMP_VM_IP:8549"
log_info ""
log_info "Next steps:"
log_info "1. Monitor containers: ssh root@$TEMP_VM_IP 'docker compose logs -f'"
log_info "2. Validate network: ./scripts/validation/validate-besu-temp-vm.sh"
log_info "3. When ready, migrate to LXC: ./scripts/migration/migrate-vm-to-lxc.sh $SOURCE_PROJECT"
log_info ""

