#!/bin/bash
# Comprehensive Prerequisites Check Script
# Validates all prerequisites for the Proxmox workspace

set +e  # Don't exit on errors - collect all results

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && 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'

# Status tracking
PASSED=0
FAILED=0
WARNINGS=0

pass() {
    echo -e "${GREEN}✅${NC} $1"
    ((PASSED++))
}

fail() {
    echo -e "${RED}❌${NC} $1"
    ((FAILED++))
}

warn() {
    echo -e "${YELLOW}⚠️${NC} $1"
    ((WARNINGS++))
}

info() {
    echo -e "${BLUE}ℹ️${NC} $1"
}

section() {
    echo ""
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}$1${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
}

echo ""
echo -e "${BLUE}╔════════════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║${NC}              Prerequisites Check for Proxmox Workspace              ${BLUE}║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════════════════════════════════════╝${NC}"
echo ""

# ============================================================================
# SECTION 1: SYSTEM PREREQUISITES
# ============================================================================

section "1. SYSTEM PREREQUISITES"

# Check Node.js
if command -v node &> /dev/null; then
    NODE_VERSION=$(node --version | sed 's/v//')
    NODE_MAJOR=$(echo "$NODE_VERSION" | cut -d. -f1)
    if [ "$NODE_MAJOR" -ge 16 ]; then
        pass "Node.js installed: v$NODE_VERSION (requires 16+)"
    else
        fail "Node.js version too old: v$NODE_VERSION (requires 16+)"
    fi
else
    fail "Node.js not installed (requires 16+)"
fi

# Check pnpm
if command -v pnpm &> /dev/null; then
    PNPM_VERSION=$(pnpm --version)
    PNPM_MAJOR=$(echo "$PNPM_VERSION" | cut -d. -f1)
    if [ "$PNPM_MAJOR" -ge 8 ]; then
        pass "pnpm installed: $PNPM_VERSION (requires 8+)"
    else
        fail "pnpm version too old: $PNPM_VERSION (requires 8+)"
    fi
else
    fail "pnpm not installed (requires 8+)"
fi

# Check Git
if command -v git &> /dev/null; then
    GIT_VERSION=$(git --version | awk '{print $3}')
    pass "Git installed: $GIT_VERSION"
else
    fail "Git not installed"
fi

# Check required tools
REQUIRED_TOOLS=("curl" "jq" "bash")
for tool in "${REQUIRED_TOOLS[@]}"; do
    if command -v "$tool" &> /dev/null; then
        pass "$tool installed"
    else
        fail "$tool not found (required)"
    fi
done

# ============================================================================
# SECTION 2: WORKSPACE STRUCTURE
# ============================================================================

section "2. WORKSPACE STRUCTURE"

# Check project root
if [ -d "$PROJECT_ROOT" ]; then
    pass "Project root exists: $PROJECT_ROOT"
else
    fail "Project root not found: $PROJECT_ROOT"
    exit 1
fi

# Check package.json
if [ -f "$PROJECT_ROOT/package.json" ]; then
    pass "package.json exists"
else
    fail "package.json not found"
fi

# Check pnpm-workspace.yaml
if [ -f "$PROJECT_ROOT/pnpm-workspace.yaml" ]; then
    pass "pnpm-workspace.yaml exists"
else
    fail "pnpm-workspace.yaml not found"
fi

# Check submodules
if [ -d "$PROJECT_ROOT/mcp-proxmox" ]; then
    if [ -f "$PROJECT_ROOT/mcp-proxmox/index.js" ]; then
        pass "mcp-proxmox submodule exists and has index.js"
    else
        warn "mcp-proxmox submodule exists but index.js not found"
    fi
else
    fail "mcp-proxmox submodule not found"
fi

if [ -d "$PROJECT_ROOT/ProxmoxVE" ]; then
    pass "ProxmoxVE submodule exists"
else
    warn "ProxmoxVE submodule not found"
fi

if [ -d "$PROJECT_ROOT/smom-dbis-138-proxmox" ]; then
    pass "smom-dbis-138-proxmox submodule exists"
else
    warn "smom-dbis-138-proxmox submodule not found"
fi

# Check directory structure
[ -d "$PROJECT_ROOT/scripts" ] && pass "scripts/ directory exists" || fail "scripts/ directory not found"
[ -d "$PROJECT_ROOT/docs" ] && pass "docs/ directory exists" || fail "docs/ directory not found"

# ============================================================================
# SECTION 3: DEPENDENCIES
# ============================================================================

section "3. DEPENDENCIES"

# Check if node_modules exists
if [ -d "$PROJECT_ROOT/node_modules" ]; then
    pass "node_modules exists (dependencies installed)"
    
    # Check MCP server dependencies
    if [ -d "$PROJECT_ROOT/mcp-proxmox/node_modules" ]; then
        pass "MCP server dependencies installed"
    else
        warn "MCP server dependencies not installed (run: pnpm install)"
    fi
    
    # Check frontend dependencies
    if [ -d "$PROJECT_ROOT/ProxmoxVE/frontend/node_modules" ]; then
        pass "Frontend dependencies installed"
    else
        warn "Frontend dependencies not installed (run: pnpm install)"
    fi
else
    fail "node_modules not found (run: pnpm install)"
fi

# ============================================================================
# SECTION 4: CONFIGURATION FILES
# ============================================================================

section "4. CONFIGURATION FILES"

# Check .env file
ENV_FILE="$HOME/.env"
if [ -f "$ENV_FILE" ]; then
    pass ".env file exists: $ENV_FILE"
    
    # Check for required variables
    source scripts/load-env.sh 2>/dev/null || true
    load_env_file 2>/dev/null || true
    
    [ -n "${PROXMOX_HOST:-}" ] && [ "${PROXMOX_HOST}" != "your-proxmox-ip-or-hostname" ] && \
        pass "PROXMOX_HOST configured: $PROXMOX_HOST" || \
        warn "PROXMOX_HOST not configured or using placeholder"
    
    [ -n "${PROXMOX_USER:-}" ] && [ "${PROXMOX_USER}" != "your-username" ] && \
        pass "PROXMOX_USER configured: $PROXMOX_USER" || \
        warn "PROXMOX_USER not configured or using placeholder"
    
    [ -n "${PROXMOX_TOKEN_NAME:-}" ] && [ "${PROXMOX_TOKEN_NAME}" != "your-token-name" ] && \
        pass "PROXMOX_TOKEN_NAME configured: $PROXMOX_TOKEN_NAME" || \
        warn "PROXMOX_TOKEN_NAME not configured or using placeholder"
    
    if [ -n "${PROXMOX_TOKEN_VALUE:-}" ] && [ "${PROXMOX_TOKEN_VALUE}" != "your-token-secret-here" ] && [ "${PROXMOX_TOKEN_VALUE}" != "your-token-secret" ]; then
        pass "PROXMOX_TOKEN_VALUE configured (secret present)"
    else
        fail "PROXMOX_TOKEN_VALUE not configured or using placeholder"
    fi
else
    fail ".env file not found: $ENV_FILE"
    info "Create it with: ./scripts/setup.sh"
fi

# Check Claude Desktop config
CLAUDE_CONFIG="$HOME/.config/Claude/claude_desktop_config.json"
if [ -f "$CLAUDE_CONFIG" ]; then
    pass "Claude Desktop config exists: $CLAUDE_CONFIG"
    
    # Check if MCP server is configured
    if grep -q "proxmox" "$CLAUDE_CONFIG" 2>/dev/null; then
        pass "MCP server configured in Claude Desktop"
    else
        warn "MCP server not found in Claude Desktop config"
    fi
else
    warn "Claude Desktop config not found: $CLAUDE_CONFIG"
    info "Create it with: ./scripts/setup.sh"
fi

# Check deployment configs
if [ -d "$PROJECT_ROOT/smom-dbis-138-proxmox/config" ]; then
    if [ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/config/proxmox.conf" ]; then
        pass "Deployment proxmox.conf exists"
    else
        warn "Deployment proxmox.conf not found (example exists)"
    fi
    
    if [ -f "$PROJECT_ROOT/smom-dbis-138-proxmox/config/network.conf" ]; then
        pass "Deployment network.conf exists"
    else
        warn "Deployment network.conf not found (example exists)"
    fi
fi

# ============================================================================
# SECTION 5: SCRIPTS
# ============================================================================

section "5. SCRIPTS"

REQUIRED_SCRIPTS=(
    "setup.sh"
    "complete-setup.sh"
    "verify-setup.sh"
    "load-env.sh"
    "test-connection.sh"
    "validate-ml110-deployment.sh"
)

for script in "${REQUIRED_SCRIPTS[@]}"; do
    SCRIPT_PATH="$PROJECT_ROOT/scripts/$script"
    if [ -f "$SCRIPT_PATH" ]; then
        if [ -x "$SCRIPT_PATH" ]; then
            pass "$script exists and is executable"
        else
            warn "$script exists but is not executable"
        fi
    else
        fail "$script not found"
    fi
done

# ============================================================================
# SECTION 6: PROXMOX CONNECTION (if configured)
# ============================================================================

section "6. PROXMOX CONNECTION"

if [ -f "$ENV_FILE" ]; then
    source scripts/load-env.sh 2>/dev/null || true
    load_env_file 2>/dev/null || true
    
    if [ -n "${PROXMOX_HOST:-}" ] && [ -n "${PROXMOX_TOKEN_VALUE:-}" ] && \
       [ "${PROXMOX_TOKEN_VALUE}" != "your-token-secret-here" ] && \
       [ "${PROXMOX_TOKEN_VALUE}" != "your-token-secret" ]; then
        info "Testing connection to ${PROXMOX_HOST}..."
        
        API_RESPONSE=$(curl -k -s -w "\n%{http_code}" -m 10 \
            -H "Authorization: PVEAPIToken=${PROXMOX_USER}!${PROXMOX_TOKEN_NAME}=${PROXMOX_TOKEN_VALUE}" \
            "https://${PROXMOX_HOST}:${PROXMOX_PORT:-8006}/api2/json/version" 2>&1)
        
        HTTP_CODE=$(echo "$API_RESPONSE" | tail -1)
        
        if [ "$HTTP_CODE" = "200" ]; then
            VERSION=$(echo "$API_RESPONSE" | sed '$d' | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['version'])" 2>/dev/null || echo "unknown")
            pass "Proxmox API connection successful (version: $VERSION)"
        else
            fail "Proxmox API connection failed (HTTP $HTTP_CODE)"
        fi
    else
        warn "Cannot test Proxmox connection - credentials not fully configured"
    fi
else
    warn "Cannot test Proxmox connection - .env file not found"
fi

# ============================================================================
# SUMMARY
# ============================================================================

section "PREREQUISITES SUMMARY"

echo -e "${CYAN}Results:${NC}"
echo -e "  ${GREEN}Passed:${NC}  $PASSED"
echo -e "  ${RED}Failed:${NC}  $FAILED"
echo -e "  ${YELLOW}Warnings:${NC} $WARNINGS"
echo ""

if [ $FAILED -eq 0 ]; then
    echo -e "${GREEN}✅ All prerequisites met!${NC}"
    echo ""
    echo "Next steps:"
    echo "  1. Run deployment validation: ./scripts/validate-ml110-deployment.sh"
    echo "  2. Start MCP server: pnpm mcp:start"
    exit 0
else
    echo -e "${RED}❌ Some prerequisites are missing${NC}"
    echo ""
    echo "Please fix the failures above before proceeding."
    echo ""
    echo "Quick fixes:"
    [ $FAILED -gt 0 ] && echo "  - Run: ./scripts/complete-setup.sh"
    exit 1
fi

