#!/bin/bash
# Comprehensive Fix Script for All Explorer Issues
# Fixes both Blockscout (VMID 5000) and explorer-monorepo issues

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID_5000="${VMID_5000:-5000}"
EXPLORER_MONOREPO_DIR="${EXPLORER_MONOREPO_DIR:-/home/intlc/projects/proxmox/explorer-monorepo}"

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

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

echo "=========================================="
echo "Comprehensive Explorer Issues Fix Script"
echo "=========================================="
echo ""

# Function to execute command in container
exec_container() {
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 root@"$PROXMOX_HOST" "pct exec $VMID_5000 -- bash -c '$1'" 2>&1
}

# Step 1: Fix explorer-monorepo Backend API Server
log_info "Step 1: Fixing explorer-monorepo Backend API Server"
cd "$EXPLORER_MONOREPO_DIR" || {
    log_error "Cannot access explorer-monorepo directory: $EXPLORER_MONOREPO_DIR"
    exit 1
}

# Check if backend server is running
if lsof -Pi :8080 -sTCP:LISTEN -t >/dev/null 2>&1; then
    log_warn "Backend server is already running on port 8080"
    OLD_PID=$(lsof -t -i:8080)
    log_info "Stopping existing server (PID: $OLD_PID)"
    kill "$OLD_PID" 2>/dev/null || true
    sleep 2
fi

# Set environment variables
export CHAIN_ID="${CHAIN_ID:-138}"
export PORT="${PORT:-8080}"
export DB_HOST="${DB_HOST:-localhost}"
export DB_PORT="${DB_PORT:-5432}"
export DB_USER="${DB_USER:-explorer}"
export DB_PASSWORD="${DB_PASSWORD:-changeme}"
export DB_NAME="${DB_NAME:-explorer}"
export DB_SSLMODE="${DB_SSLMODE:-disable}"

log_info "Starting backend server with configuration:"
log_info "  Chain ID: $CHAIN_ID"
log_info "  Port: $PORT"
log_info "  Database: $DB_USER@$DB_HOST:$DB_PORT/$DB_NAME"

# Start backend server using the service script
if [ -f "$EXPLORER_MONOREPO_DIR/scripts/start-backend-service.sh" ]; then
    log_info "Using start-backend-service.sh script"
    cd "$EXPLORER_MONOREPO_DIR"
    bash scripts/start-backend-service.sh || {
        log_warn "Service script failed, trying direct start"
        cd backend/api/rest/cmd
        nohup go run main.go > /tmp/explorer_backend.log 2>&1 &
        sleep 3
    }
else
    log_info "Starting backend server directly"
    cd "$EXPLORER_MONOREPO_DIR/backend/api/rest/cmd"
    nohup go run main.go > /tmp/explorer_backend.log 2>&1 &
    sleep 3
fi

# Verify backend is running
sleep 2
if curl -s "http://localhost:8080/health" >/dev/null 2>&1; then
    log_success "Backend API server is running"
else
    log_warn "Backend server may not be fully started yet"
    log_info "Check logs: tail -f /tmp/explorer_backend.log"
fi

# Step 2: Check VMID 5000 Container Status
log_info ""
log_info "Step 2: Checking VMID 5000 Container Status"
log_info "Note: This requires SSH access to Proxmox host: $PROXMOX_HOST"

if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "echo test" 2>/dev/null; then
    log_success "Proxmox host is accessible"
    
    # Check if container exists
    CONTAINER_EXISTS=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct list | grep -c '^$VMID_5000' || echo 0" 2>/dev/null)
    
    if [ "$CONTAINER_EXISTS" -eq 0 ]; then
        log_error "Container VMID $VMID_5000 does not exist"
        log_info "You may need to deploy the container first"
    else
        log_success "Container VMID $VMID_5000 exists"
        
        # Check container status
        CONTAINER_STATUS=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct status $VMID_5000 2>/dev/null | awk '{print \$2}'" || echo "unknown")
        
        if [ "$CONTAINER_STATUS" != "running" ]; then
            log_warn "Container is not running (status: $CONTAINER_STATUS)"
            log_info "Attempting to start container..."
            ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct start $VMID_5000" 2>&1 || log_error "Failed to start container"
            sleep 5
        else
            log_success "Container is running"
        fi
        
        # Check Blockscout service
        log_info "Checking Blockscout service..."
        BLOCKSCOUT_STATUS=$(exec_container "systemctl is-active blockscout 2>/dev/null || echo inactive")
        if [ "$BLOCKSCOUT_STATUS" = "active" ]; then
            log_success "Blockscout service is active"
        else
            log_warn "Blockscout service is not active"
            log_info "Attempting to start Blockscout service..."
            exec_container "systemctl start blockscout" || log_warn "Failed to start Blockscout service"
        fi
        
        # Check Docker containers
        log_info "Checking Docker containers..."
        DOCKER_CONTAINERS=$(exec_container "docker ps -a | grep blockscout | wc -l" || echo "0")
        if [ "$DOCKER_CONTAINERS" -gt "0" ]; then
            log_success "Found Blockscout Docker containers"
        else
            log_warn "No Blockscout Docker containers found"
        fi
        
        # Check Nginx
        log_info "Checking Nginx..."
        NGINX_STATUS=$(exec_container "systemctl is-active nginx 2>/dev/null || echo inactive")
        if [ "$NGINX_STATUS" = "active" ]; then
            log_success "Nginx is active"
        else
            log_warn "Nginx is not active"
            log_info "Attempting to start Nginx..."
            exec_container "systemctl start nginx" || log_warn "Failed to start Nginx"
        fi
        
        # Check Cloudflare tunnel
        log_info "Checking Cloudflare tunnel..."
        TUNNEL_STATUS=$(exec_container "systemctl is-active cloudflared 2>/dev/null || echo inactive")
        if [ "$TUNNEL_STATUS" = "active" ]; then
            log_success "Cloudflare tunnel is active"
        else
            log_warn "Cloudflare tunnel is not active"
            log_info "Attempting to start Cloudflare tunnel..."
            exec_container "systemctl start cloudflared" || log_warn "Failed to start Cloudflare tunnel"
        fi
    fi
else
    log_warn "Cannot access Proxmox host: $PROXMOX_HOST"
    log_info "Skipping VMID 5000 checks (requires SSH access)"
fi

# Step 3: Summary
log_info ""
log_info "=========================================="
log_info "Fix Summary"
log_info "=========================================="
log_info ""
log_info "Completed:"
log_info "  ✓ Attempted to start explorer-monorepo backend server"
log_info ""
log_info "Manual steps required:"
log_info "  1. Verify backend server: curl http://localhost:8080/health"
log_info "  2. Check backend logs: tail -f /tmp/explorer_backend.log"
log_info "  3. For VMID 5000: SSH to Proxmox host and run diagnostics"
log_info "  4. Review comprehensive issues document: EXPLORER_VMID5000_COMPREHENSIVE_ISSUES_REVIEW.md"
log_info ""
log_info "Next steps:"
log_info "  - Run diagnostic script: scripts/diagnose-vmid5000-status.sh"
log_info "  - Check database configuration for explorer-monorepo"
log_info "  - Verify Cloudflare tunnel configuration for VMID 5000"
log_info ""

log_success "Fix script completed"
