#!/usr/bin/env bash
# Fix Blockscout Explorer - Cluster-aware version
# Handles containers on different Proxmox nodes

set -euo pipefail

VMID="${1:-5000}"
IP="${2:-192.168.11.140}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"

# Function to execute command in container via API
exec_container_api() {
    local vmid="$1"
    local cmd="$2"
    
    # Try to find which node the container is on
    local node=""
    for n in ml110 pve pve2; do
        if pvesh get /nodes/$n/lxc/$vmid/status/current --output-format json >/dev/null 2>&1; then
            node="$n"
            break
        fi
    done
    
    if [ -z "$node" ]; then
        log_error "Cannot find container $vmid on any node"
        return 1
    fi
    
    # Use pct exec via SSH to the node
    ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct exec $vmid -- $cmd" 2>/dev/null
}

# Check container status via API
check_container_status() {
    local vmid="$1"
    local node=""
    
    for n in ml110 pve pve2; do
        if pvesh get /nodes/$n/lxc/$vmid/status/current --output-format json >/dev/null 2>&1; then
            node="$n"
            break
        fi
    done
    
    if [ -z "$node" ]; then
        echo "missing"
        return
    fi
    
    local status=$(pvesh get /nodes/$n/lxc/$vmid/status/current --output-format json 2>/dev/null | grep -oP '"status":\s*"\K[^"]+' | head -1 || echo "unknown")
    echo "$status"
}

log_info "Blockscout Explorer Fix (Cluster-aware)"
log_info "VMID: $VMID"
log_info "IP: $IP"

# Check container status
STATUS=$(check_container_status "$VMID")
if [ "$STATUS" = "missing" ]; then
    log_error "Container $VMID not found on any node"
    exit 1
fi

log_info "Container status: $STATUS"

if [ "$STATUS" != "running" ]; then
    log_warn "Starting container..."
    # Find node and start
    for n in ml110 pve pve2; do
        if pvesh get /nodes/$n/lxc/$VMID/status/current --output-format json >/dev/null 2>&1; then
            pvesh create /nodes/$n/lxc/$VMID/status/start 2>&1 || true
            sleep 5
            break
        fi
    done
fi

# Now run the fix script which should work via pct exec
log_info "Running fix script..."
ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "cd /home/intlc/projects/proxmox && bash scripts/fix-blockscout-explorer.sh $VMID $IP 2>&1"

