#!/bin/bash
# Complete Setup Script for Proxmox Workspace
# This script ensures all prerequisites are met and completes all setup steps

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "🚀 Proxmox Workspace Complete Setup"
echo "===================================="
echo ""

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

# Check functions
check_pass() {
    echo -e "${GREEN}✅${NC} $1"
}

check_warn() {
    echo -e "${YELLOW}⚠️${NC} $1"
}

check_fail() {
    echo -e "${RED}❌${NC} $1"
    exit 1
}

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

# Step 1: Verify Prerequisites
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 1: Verifying Prerequisites"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Check Node.js
if command -v node &> /dev/null; then
    NODE_VERSION=$(node --version)
    NODE_MAJOR=$(echo "$NODE_VERSION" | cut -d'.' -f1 | sed 's/v//')
    if [ "$NODE_MAJOR" -ge 16 ]; then
        check_pass "Node.js $NODE_VERSION installed (requires 16+)"
    else
        check_fail "Node.js version $NODE_VERSION is too old (requires 16+)"
    fi
else
    check_fail "Node.js is not installed"
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
        check_pass "pnpm $PNPM_VERSION installed (requires 8+)"
    else
        check_fail "pnpm version $PNPM_VERSION is too old (requires 8+)"
    fi
else
    check_fail "pnpm is not installed. Install with: npm install -g pnpm"
fi

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

echo ""

# Step 2: Initialize Submodules
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 2: Initializing Git Submodules"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

if [ -f ".gitmodules" ] || [ -d ".git" ]; then
    check_info "Initializing and updating submodules..."
    git submodule update --init --recursive 2>&1 | grep -E "Submodule|Cloning|fatal" || true
    check_pass "Submodules initialized"
else
    check_warn "Not a git repository, skipping submodule initialization"
fi

echo ""

# Step 3: Install Dependencies
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 3: Installing Workspace Dependencies"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

check_info "Installing dependencies for all workspace packages..."
if pnpm install; then
    check_pass "All dependencies installed"
else
    check_fail "Failed to install dependencies"
fi

echo ""

# Step 4: Verify Workspace Structure
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 4: Verifying Workspace Structure"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Check workspace config
if [ -f "pnpm-workspace.yaml" ]; then
    check_pass "pnpm-workspace.yaml exists"
else
    check_fail "pnpm-workspace.yaml not found"
fi

# Check root package.json
if [ -f "package.json" ]; then
    check_pass "Root package.json exists"
    if grep -q "mcp:start" package.json; then
        check_pass "Workspace scripts configured"
    fi
else
    check_fail "package.json not found"
fi

# Check submodules
if [ -d "mcp-proxmox" ] && [ -f "mcp-proxmox/index.js" ]; then
    check_pass "mcp-proxmox submodule present"
else
    check_warn "mcp-proxmox submodule may be missing"
fi

if [ -d "ProxmoxVE/frontend" ] && [ -f "ProxmoxVE/frontend/package.json" ]; then
    check_pass "ProxmoxVE/frontend submodule present"
else
    check_warn "ProxmoxVE/frontend submodule may be missing"
fi

echo ""

# Step 5: Configuration Files
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 5: Setting Up Configuration Files"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

ENV_FILE="$HOME/.env"
if [ ! -f "$ENV_FILE" ]; then
    check_info "Creating .env file..."
    cat > "$ENV_FILE" << 'EOF'
# Proxmox MCP Server Configuration
# Fill in your actual values below

# Proxmox Configuration (REQUIRED)
PROXMOX_HOST=your-proxmox-ip-or-hostname
PROXMOX_USER=root@pam
PROXMOX_TOKEN_NAME=your-token-name
PROXMOX_TOKEN_VALUE=your-token-secret

# Security Settings (REQUIRED)
# ⚠️  WARNING: Setting PROXMOX_ALLOW_ELEVATED=true enables DESTRUCTIVE operations
PROXMOX_ALLOW_ELEVATED=false

# Optional Settings
# PROXMOX_PORT=8006  # Defaults to 8006 if not specified
EOF
    check_pass ".env file created at $ENV_FILE"
    check_warn "Please edit $ENV_FILE and add your Proxmox credentials"
else
    check_pass ".env file exists at $ENV_FILE"
    # Check if configured
    if grep -q "your-proxmox-ip" "$ENV_FILE" 2>/dev/null || ! grep -q "^PROXMOX_HOST=" "$ENV_FILE" 2>/dev/null; then
        check_warn ".env file needs Proxmox credentials configured"
    else
        check_pass ".env file appears configured"
    fi
fi

# Claude Desktop config
CLAUDE_CONFIG_DIR="$HOME/.config/Claude"
CLAUDE_CONFIG="$CLAUDE_CONFIG_DIR/claude_desktop_config.json"
if [ ! -d "$CLAUDE_CONFIG_DIR" ]; then
    mkdir -p "$CLAUDE_CONFIG_DIR"
    check_pass "Claude config directory created"
fi

if [ ! -f "$CLAUDE_CONFIG" ]; then
    check_info "Creating Claude Desktop config..."
    cat > "$CLAUDE_CONFIG" << EOF
{
  "mcpServers": {
    "proxmox": {
      "command": "node",
      "args": [
        "$SCRIPT_DIR/mcp-proxmox/index.js"
      ]
    }
  }
}
EOF
    check_pass "Claude Desktop config created"
else
    check_pass "Claude Desktop config exists"
fi

echo ""

# Step 6: Verify Dependencies
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 6: Verifying Package Dependencies"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Check MCP server dependencies
if [ -d "mcp-proxmox/node_modules" ]; then
    if [ -d "mcp-proxmox/node_modules/@modelcontextprotocol" ]; then
        check_pass "MCP server dependencies installed"
    else
        check_warn "MCP server dependencies may be incomplete"
    fi
else
    check_warn "MCP server node_modules not found (may need: cd mcp-proxmox && pnpm install)"
fi

# Check frontend dependencies
if [ -d "ProxmoxVE/frontend/node_modules" ]; then
    check_pass "Frontend dependencies installed"
else
    check_warn "Frontend dependencies not found (may need: cd ProxmoxVE/frontend && pnpm install)"
fi

echo ""

# Step 7: Final Verification
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "Step 7: Final Verification"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Run the verification script if it exists
if [ -f "verify-setup.sh" ]; then
    check_info "Running verification script..."
    echo ""
    bash verify-setup.sh || check_warn "Some verification checks failed (see above)"
else
    check_warn "verify-setup.sh not found"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ Setup Complete!"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "Next steps:"
echo "1. Edit $ENV_FILE with your Proxmox credentials"
echo "2. (Optional) Create Proxmox API token: ./create-proxmox-token.sh"
echo "3. Restart Claude Desktop to load MCP server"
echo "4. Test MCP server: pnpm test:basic"
echo "5. Start MCP server: pnpm mcp:start"
echo ""
echo "Available commands:"
echo "  • pnpm mcp:start       - Start MCP server"
echo "  • pnpm mcp:dev         - Start MCP server in watch mode"
echo "  • pnpm frontend:dev    - Start frontend dev server"
echo "  • ./verify-setup.sh    - Verify setup"
echo ""

