#!/bin/bash
# Comprehensive Fix Script for VMID 5000 Blockscout Explorer
# This script diagnoses and fixes Blockscout issues in VMID 5000

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID_5000="${VMID_5000:-5000}"

# 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 "VMID 5000 Blockscout Explorer 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
}

# Check Proxmox host access
log_info "Checking Proxmox host access..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "echo test" 2>/dev/null; then
    log_error "Cannot access Proxmox host: $PROXMOX_HOST"
    log_info "Please ensure SSH access is configured:"
    echo "  ssh root@$PROXMOX_HOST"
    exit 1
fi
log_success "Proxmox host is accessible"

# Check if container exists
log_info "Checking if container VMID $VMID_5000 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 need to deploy the container first"
    log_info "See: smom-dbis-138-proxmox/scripts/deployment/deploy-explorer.sh"
    exit 1
fi

log_success "Container exists"

# Check and start container if needed
log_info "Checking 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 "Starting container..."
    if ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct start $VMID_5000" 2>&1; then
        log_success "Container started"
        sleep 5
    else
        log_error "Failed to start container"
        exit 1
    fi
else
    log_success "Container is running"
fi

# Start Blockscout service
log_info "Starting Blockscout service..."
if exec_container "systemctl start blockscout" 2>/dev/null; then
    log_success "Blockscout service started"
    sleep 3
else
    log_warn "Blockscout service start command failed (may already be running)"
fi

# Check Blockscout service status
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 "Checking service logs..."
    exec_container "journalctl -u blockscout -n 20 --no-pager" 2>&1 | tail -20
fi

# Start Nginx
log_info "Starting Nginx..."
if exec_container "systemctl start nginx" 2>/dev/null; then
    log_success "Nginx started"
else
    log_warn "Nginx start command failed (may already be running)"
fi

NGINX_STATUS=$(exec_container "systemctl is-active nginx 2>/dev/null || echo inactive")
if [ "$NGINX_STATUS" = "active" ]; then
    log_success "Nginx is active"
    # Test nginx config
    if exec_container "nginx -t" 2>&1 | grep -q "successful"; then
        log_success "Nginx configuration is valid"
    else
        log_warn "Nginx configuration has issues"
        exec_container "nginx -t" 2>&1
    fi
else
    log_error "Nginx is not active"
fi

# Start Cloudflare tunnel
log_info "Starting Cloudflare tunnel..."
if exec_container "systemctl start cloudflared" 2>/dev/null; then
    log_success "Cloudflare tunnel started"
else
    log_warn "Cloudflare tunnel start command failed (may already be running)"
fi

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 "Checking tunnel logs..."
    exec_container "journalctl -u cloudflared -n 20 --no-pager" 2>&1 | tail -20
fi

# Check Docker containers
log_info "Checking Docker containers..."
DOCKER_PS=$(exec_container "docker ps -a" 2>/dev/null || echo "")
if [ -n "$DOCKER_PS" ]; then
    BLOCKSCOUT_CONTAINER=$(echo "$DOCKER_PS" | grep blockscout | grep -v postgres | awk '{print $1}' | head -1)
    if [ -n "$BLOCKSCOUT_CONTAINER" ]; then
        log_success "Blockscout container found: $BLOCKSCOUT_CONTAINER"
        CONTAINER_STATE=$(echo "$DOCKER_PS" | grep "$BLOCKSCOUT_CONTAINER" | awk '{print $7}')
        if [ "$CONTAINER_STATE" = "Up" ]; then
            log_success "Blockscout container is running"
        else
            log_warn "Blockscout container state: $CONTAINER_STATE"
            log_info "Attempting to start container..."
            exec_container "docker start $BLOCKSCOUT_CONTAINER" 2>&1 || log_warn "Failed to start container"
        fi
    else
        log_warn "No Blockscout container found"
        log_info "You may need to start Docker Compose:"
        echo "  pct exec $VMID_5000 -- docker-compose -f /opt/blockscout/docker-compose.yml up -d"
    fi
fi

# Test local API
log_info "Testing local Blockscout API..."
sleep 2
LOCAL_API=$(exec_container "curl -s http://localhost:4000/api/v2/status 2>&1 || echo 'FAILED'" 2>/dev/null)
if echo "$LOCAL_API" | grep -q "FAILED\|Connection refused"; then
    log_warn "Blockscout API not responding on port 4000"
    log_info "Container may still be starting up (can take 5-10 minutes)"
else
    log_success "Blockscout API is responding"
fi

# Summary
echo ""
log_info "=========================================="
log_info "Fix Summary"
log_info "=========================================="
log_info "Container Status: running"
log_info "Blockscout Service: $BLOCKSCOUT_STATUS"
log_info "Nginx Service: $NGINX_STATUS"
log_info "Cloudflare Tunnel: $TUNNEL_STATUS"
log_info ""
log_info "Next steps:"
log_info "  1. Wait 5-10 minutes for Blockscout to fully start"
log_info "  2. Check logs: pct exec $VMID_5000 -- docker logs blockscout"
log_info "  3. Test public URL: https://explorer.d-bis.org"
log_info ""

log_success "Fix script completed"
