#!/usr/bin/env bash
# Verify prerequisites before deployment

set -euo pipefail

# 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"; }

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID="${VMID:-102}"

# Check if running on Proxmox host
if command -v pct &> /dev/null; then
    RUN_LOCAL=true
else
    RUN_LOCAL=false
fi

exec_in_container() {
    local cmd="$1"
    if [ "$RUN_LOCAL" = true ]; then
        pct exec "$VMID" -- bash -c "$cmd" 2>/dev/null || return 1
    else
        ssh "root@${PROXMOX_HOST}" "pct exec $VMID -- bash -c '$cmd'" 2>/dev/null || return 1
    fi
}

echo ""
echo "=========================================="
echo "  Prerequisites Verification"
echo "=========================================="
echo ""

all_checks_passed=true

# Check 1: VMID 102 exists
log_info "Checking VMID $VMID exists..."
if exec_in_container "true"; then
    log_success "VMID $VMID is accessible"
else
    log_error "VMID $VMID is not accessible"
    all_checks_passed=false
fi

# Check 2: VMID 102 is running
log_info "Checking VMID $VMID is running..."
if exec_in_container "systemctl is-system-running > /dev/null 2>&1"; then
    log_success "VMID $VMID is running"
else
    log_error "VMID $VMID is not running"
    all_checks_passed=false
fi

# Check 3: Network connectivity to Proxmox hosts
log_info "Checking network connectivity to Proxmox hosts..."
for ip in 192.168.11.10 192.168.11.11 192.168.11.12; do
    if exec_in_container "timeout 3 bash -c 'echo > /dev/tcp/${ip}/8006' 2>/dev/null"; then
        log_success "Can reach ${ip}:8006"
    else
        log_warn "Cannot reach ${ip}:8006 (may need to test manually)"
    fi
done

# Check 4: cloudflared installation
log_info "Checking cloudflared installation..."
if exec_in_container "command -v cloudflared &> /dev/null"; then
    version=$(exec_in_container "cloudflared --version 2>/dev/null | head -1" || echo "unknown")
    log_success "cloudflared is installed: $version"
else
    log_warn "cloudflared is not installed (will be installed by setup script)"
fi

# Check 5: Configuration files exist
log_info "Checking configuration files..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TUNNELS_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

for tunnel in ml110 r630-01 r630-02; do
    if [ -f "$TUNNELS_DIR/configs/tunnel-${tunnel}.yml" ]; then
        log_success "Config file exists: tunnel-${tunnel}.yml"
    else
        log_error "Config file missing: tunnel-${tunnel}.yml"
        all_checks_passed=false
    fi
done

# Check 6: Systemd service files exist
log_info "Checking systemd service files..."
for tunnel in ml110 r630-01 r630-02; do
    if [ -f "$TUNNELS_DIR/systemd/cloudflared-${tunnel}.service" ]; then
        log_success "Service file exists: cloudflared-${tunnel}.service"
    else
        log_error "Service file missing: cloudflared-${tunnel}.service"
        all_checks_passed=false
    fi
done

# Check 7: Scripts are executable
log_info "Checking scripts are executable..."
for script in setup-multi-tunnel.sh install-tunnel.sh monitor-tunnels.sh check-tunnel-health.sh alert-tunnel-failure.sh restart-tunnel.sh; do
    if [ -x "$SCRIPT_DIR/$script" ]; then
        log_success "Script is executable: $script"
    else
        log_warn "Script not executable: $script (will fix)"
        chmod +x "$SCRIPT_DIR/$script" 2>/dev/null || true
    fi
done

# Check 8: Directories exist
log_info "Checking directory structure..."
for dir in configs systemd scripts monitoring docs; do
    if [ -d "$TUNNELS_DIR/$dir" ]; then
        log_success "Directory exists: $dir"
    else
        log_error "Directory missing: $dir"
        all_checks_passed=false
    fi
done

echo ""
echo "=========================================="
echo "  Manual Prerequisites"
echo "=========================================="
echo ""
log_warn "The following must be done manually:"
echo ""
echo "1. Cloudflare Account:"
echo "   - [ ] Cloudflare account with Zero Trust enabled"
echo "   - [ ] Domain d-bis.org managed by Cloudflare"
echo ""
echo "2. Create Tunnels in Cloudflare Dashboard:"
echo "   - [ ] Go to: https://one.dash.cloudflare.com"
echo "   - [ ] Zero Trust → Networks → Tunnels"
echo "   - [ ] Create: tunnel-ml110"
echo "   - [ ] Create: tunnel-r630-01"
echo "   - [ ] Create: tunnel-r630-02"
echo "   - [ ] Copy tunnel tokens/credentials"
echo ""
echo "3. DNS Records (after tunnels created):"
echo "   - [ ] Create CNAME: ml110-01 → <tunnel-id>.cfargotunnel.com (Proxied)"
echo "   - [ ] Create CNAME: r630-01 → <tunnel-id>.cfargotunnel.com (Proxied)"
echo "   - [ ] Create CNAME: r630-02 → <tunnel-id>.cfargotunnel.com (Proxied)"
echo ""

echo "=========================================="
if [ "$all_checks_passed" = true ]; then
    log_success "All automated checks passed!"
    echo ""
    log_info "You can proceed with:"
    echo "  ./scripts/setup-multi-tunnel.sh"
    exit 0
else
    log_error "Some checks failed. Please fix issues before proceeding."
    exit 1
fi

