#!/bin/bash
# Diagnostic Script for VMID 5000 (Blockscout Explorer)
# Checks container status, services, and provides detailed diagnostics

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 Diagnostics"
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_INFO=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct list | grep '^$VMID_5000'" 2>/dev/null || echo "")

if [ -z "$CONTAINER_INFO" ]; then
    log_error "Container VMID $VMID_5000 does not exist"
    log_info "Container may need to be deployed"
    exit 1
fi

log_success "Container exists"
echo "  Container info: $CONTAINER_INFO"

# Check container status
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_success "Container is running"
elif [ "$CONTAINER_STATUS" = "stopped" ]; then
    log_warn "Container is stopped"
    log_info "To start: ssh root@$PROXMOX_HOST 'pct start $VMID_5000'"
else
    log_error "Container status: $CONTAINER_STATUS"
fi

if [ "$CONTAINER_STATUS" != "running" ]; then
    log_info "Container is not running. Cannot check services."
    exit 0
fi

# Check system services
echo ""
log_info "=== System Services ==="

# 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: active"
    exec_container "systemctl status blockscout --no-pager -l" | head -10
else
    log_error "Blockscout service: $BLOCKSCOUT_STATUS"
fi

# Nginx service
log_info "Checking Nginx service..."
NGINX_STATUS=$(exec_container "systemctl is-active nginx 2>/dev/null || echo inactive")
if [ "$NGINX_STATUS" = "active" ]; then
    log_success "Nginx service: active"
else
    log_error "Nginx service: $NGINX_STATUS"
fi

# 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: active"
else
    log_error "Cloudflare tunnel: $TUNNEL_STATUS"
fi

# Check Docker containers
echo ""
log_info "=== Docker Containers ==="
DOCKER_PS=$(exec_container "docker ps -a" 2>/dev/null || echo "")
if [ -n "$DOCKER_PS" ]; then
    echo "$DOCKER_PS"
    
    BLOCKSCOUT_CONTAINER=$(echo "$DOCKER_PS" | grep blockscout | grep -v postgres | awk '{print $1}' | head -1)
    if [ -n "$BLOCKSCOUT_CONTAINER" ]; then
        log_info "Blockscout container: $BLOCKSCOUT_CONTAINER"
        log_info "Recent logs:"
        exec_container "docker logs --tail 20 $BLOCKSCOUT_CONTAINER 2>&1" | head -20
    else
        log_warn "No Blockscout container found"
    fi
else
    log_error "Cannot check Docker containers"
fi

# Check network connectivity
echo ""
log_info "=== Network Connectivity ==="
log_info "Checking local Blockscout API..."
LOCAL_API=$(exec_container "curl -s http://localhost:4000/api/v2/status 2>&1 || echo 'FAILED'")
if echo "$LOCAL_API" | grep -q "FAILED"; then
    log_error "Blockscout API not responding on port 4000"
else
    log_success "Blockscout API is responding"
    echo "$LOCAL_API" | head -5
fi

# Check database
echo ""
log_info "=== Database Status ==="
DB_CHECK=$(exec_container "pg_isready -h localhost -p 5432 2>&1 || echo 'FAILED'")
if echo "$DB_CHECK" | grep -q "accepting connections"; then
    log_success "PostgreSQL is accepting connections"
    
    # Try to check blockscout database
    DB_BLOCKS=$(exec_container "psql -h localhost -U postgres -d blockscout -c 'SELECT COUNT(*) FROM blocks;' 2>&1 | tail -1 || echo 'FAILED'")
    if ! echo "$DB_BLOCKS" | grep -q "FAILED"; then
        log_info "Blocks in database: $DB_BLOCKS"
    fi
else
    log_error "PostgreSQL is not accepting connections"
    echo "$DB_CHECK"
fi

# Summary
echo ""
log_info "=========================================="
log_info "Diagnostic Summary"
log_info "=========================================="
log_info "Container Status: $CONTAINER_STATUS"
log_info "Blockscout Service: $BLOCKSCOUT_STATUS"
log_info "Nginx Service: $NGINX_STATUS"
log_info "Cloudflare Tunnel: $TUNNEL_STATUS"
log_info ""
