#!/bin/bash

# ============================================
# UX Prototypes - One-Click Mac Setup
# ============================================
# Just double-click this file to get started!
# ============================================

clear

echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║                                                            ║"
echo "║         🎨 UX Prototypes - One-Click Setup                 ║"
echo "║                                                            ║"
echo "║         Setting up your design prototyping environment     ║"
echo "║                                                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""

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

# Progress indicator
step=0
total_steps=7

progress() {
    step=$((step + 1))
    echo ""
    echo -e "${BLUE}[$step/$total_steps]${NC} $1"
    echo "────────────────────────────────────────"
}

success() {
    echo -e "${GREEN}✓${NC} $1"
}

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

error() {
    echo -e "${RED}✗${NC} $1"
}

# ============================================
# Step 1: Check for Xcode Command Line Tools (includes Git)
# ============================================
progress "Checking for developer tools..."

if ! xcode-select -p &> /dev/null; then
    warn "Xcode Command Line Tools not found. Installing..."
    echo "A popup may appear - click 'Install' and wait for it to complete."
    xcode-select --install
    
    # Wait for installation
    echo ""
    echo "Waiting for Xcode Command Line Tools installation..."
    echo "(This may take 5-10 minutes)"
    echo ""
    
    until xcode-select -p &> /dev/null; do
        sleep 5
    done
    success "Xcode Command Line Tools installed!"
else
    success "Xcode Command Line Tools already installed"
fi

# Verify Git
if command -v git &> /dev/null; then
    success "Git is available ($(git --version))"
else
    error "Git not found. Please restart this script after Xcode tools finish installing."
    exit 1
fi

# ============================================
# Step 2: Check for Homebrew & Node.js
# ============================================
progress "Checking for Node.js..."

if command -v node &> /dev/null; then
    success "Node.js already installed ($(node --version))"
else
    warn "Node.js not found. Installing via Homebrew..."
    
    # Install Homebrew if needed
    if ! command -v brew &> /dev/null; then
        echo "Installing Homebrew first..."
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        
        # Add Homebrew to path for Apple Silicon Macs
        if [[ -f /opt/homebrew/bin/brew ]]; then
            eval "$(/opt/homebrew/bin/brew shellenv)"
            echo 'eval "$(/opt/homebrew/bin/brew shellenv)"' >> ~/.zprofile
        fi
    fi
    
    # Install Node.js
    brew install node
    success "Node.js installed ($(node --version))"
fi

# ============================================
# Step 3: Configure Git user (if not set)
# ============================================
progress "Configuring Git..."

git_name=$(git config --global user.name)
git_email=$(git config --global user.email)

if [ -z "$git_name" ]; then
    echo ""
    echo "Please enter your full name (for Git commits):"
    read -r user_name
    git config --global user.name "$user_name"
    success "Git name set to: $user_name"
else
    success "Git name already set: $git_name"
fi

if [ -z "$git_email" ]; then
    echo ""
    echo "Please enter your PowerSchool email:"
    read -r user_email
    git config --global user.email "$user_email"
    success "Git email set to: $user_email"
else
    success "Git email already set: $git_email"
fi

# ============================================
# Step 4: Clone the repository (blobless sparse checkout)
# ============================================
progress "Setting up UX Prototypes repository..."

# Determine install location
INSTALL_DIR="$HOME/Cursor/UX-PROTOTYPES"

if [ -d "$INSTALL_DIR" ]; then
    success "Repository already exists at $INSTALL_DIR"
    cd "$INSTALL_DIR"
    echo "Pulling latest changes..."
    git pull origin main
else
    echo "Cloning repository to $INSTALL_DIR (blobless — faster & smaller)..."
    mkdir -p "$HOME/Cursor"
    cd "$HOME/Cursor"
    
    # Blobless clone: downloads commits and trees but fetches file contents on demand.
    # This is significantly faster and uses much less disk space.
    if git clone --filter=blob:none --sparse https://github.com/powerschool-llc/UX-PROTOTYPES.git 2>/dev/null; then
        success "Cloned (blobless sparse)"
    else
        warn "Blobless clone failed, trying standard HTTPS clone..."
        git clone https://github.com/powerschool-llc/UX-PROTOTYPES.git
        success "Cloned via HTTPS"
    fi
    
    cd UX-PROTOTYPES
fi

# ============================================
# Step 4.5: Configure sparse checkout + submodule
# ============================================
progress "Configuring sparse checkout (save disk space)..."

echo ""
echo "💡 This will only check out your folder, keeping your drive from filling up"
echo ""

# Try to detect designer name from git config
DETECTED_NAME=$(git config --global user.name)
if [ -n "$DETECTED_NAME" ]; then
    echo "Detected your name from Git config: $DETECTED_NAME"
    read -p "Press Enter to use this name, or type a different name: " OVERRIDE_NAME
    if [ -n "$OVERRIDE_NAME" ]; then
        DESIGNER_NAME="$OVERRIDE_NAME"
    else
        DESIGNER_NAME="$DETECTED_NAME"
    fi
else
    read -p "Enter your full name (as it appears in designers/ folder, or press Enter to skip): " DESIGNER_NAME
fi

if [ -n "$DESIGNER_NAME" ]; then
    # Enable sparse checkout
    git sparse-checkout init --cone
    
    # Set up sparse checkout paths — infrastructure + designer's own folder
    git sparse-checkout set \
        server.js \
        package.json \
        package-lock.json \
        submodule-map.json \
        public/ \
        routes/ \
        middleware/ \
        utils/ \
        scripts/ \
        templates/ \
        config/ \
        .github/ \
        docs/ \
        onboarding/
    
    # Checkout the sparse paths
    git checkout main 2>/dev/null || git checkout master 2>/dev/null || true
    
    # Initialize only this designer's submodule
    if git submodule init "designers/${DESIGNER_NAME}" 2>/dev/null; then
        git submodule update --depth=1 "designers/${DESIGNER_NAME}"
        success "Submodule initialized for: designers/${DESIGNER_NAME}"
    else
        warn "Could not init submodule for '${DESIGNER_NAME}'. You may need to check the exact folder name."
        echo "   Available designers can be found in submodule-map.json"
    fi
    
    success "Sparse checkout configured — only your folder is checked out"
    echo ""
    echo "💡 To see other designers' work, run: npm run fetch-designer \"Designer Name\""
else
    warn "No designer name provided, skipping sparse checkout"
    echo "   You can set it up later with: git sparse-checkout init --cone"
fi

# ============================================
# Step 5: Install dependencies
# ============================================
progress "Installing dependencies..."

npm ci --omit=dev
success "Dependencies installed"

# ============================================
# Step 6: Configure designer identity
# ============================================
progress "Configuring your designer identity..."

echo ""
echo "This helps protect your folder from accidental commits."
echo ""

# Run designer setup (non-interactive mode would be ideal, but we'll skip for now)
# Users can run this manually after setup
echo "💡 After setup, run: npm run setup-designer"
echo "   This configures folder protection for your work."
echo ""

# ============================================
# Step 7: Install Git hooks
# ============================================
progress "Setting up safety checks..."

npm run install-hooks 2>/dev/null || node scripts/install-hooks.js 2>/dev/null
success "Git hooks installed"

# ============================================
# Step 8: Generate VS Code workspace file
# ============================================
if [ -n "$DESIGNER_NAME" ] && [ -d "designers/${DESIGNER_NAME}" ]; then
    echo ""
    echo "Generating VS Code workspace file..."
    
    cat > "UX-PROTOTYPES.code-workspace" <<WORKSPACE
{
  "folders": [
    {
      "name": "${DESIGNER_NAME} (your prototypes)",
      "path": "designers/${DESIGNER_NAME}"
    },
    {
      "name": "UX-PROTOTYPES (infrastructure — read-only)",
      "path": "."
    }
  ],
  "settings": {
    "files.readonlyInclude": {
      "server.js": true,
      "scripts/**": true,
      "routes/**": true,
      "middleware/**": true,
      "utils/**": true,
      "package.json": true,
      "package-lock.json": true
    }
  }
}
WORKSPACE
    
    success "Workspace file created: UX-PROTOTYPES.code-workspace"
fi

# ============================================
# Step 9: Verify setup
# ============================================
progress "Verifying setup..."

npm run verify 2>/dev/null
success "Setup verified!"

# ============================================
# Done!
# ============================================
echo ""
echo ""
echo "╔════════════════════════════════════════════════════════════╗"
echo "║                                                            ║"
echo "║         🎉 Setup Complete! You're ready to go!             ║"
echo "║                                                            ║"
echo "╚════════════════════════════════════════════════════════════╝"
echo ""
echo "📁 Your project is at: $INSTALL_DIR"
echo ""
echo "📖 Quick Start:"
echo "   1. Run: npm run setup-designer (configure folder protection)"
echo "   2. Run: npm run create (create your first prototype)"
echo "   3. Run: npm start (start development server)"
echo ""
echo "📚 Full documentation: Open docs.html in your browser"
echo ""
echo "⚠️  IMPORTANT: Run 'npm run setup-designer' before committing!"
echo ""

# Try to open in Cursor
if command -v cursor &> /dev/null; then
    echo "Opening in Cursor..."
    if [ -f "UX-PROTOTYPES.code-workspace" ]; then
        cursor "UX-PROTOTYPES.code-workspace"
    else
        cursor "$INSTALL_DIR"
    fi
elif [ -d "/Applications/Cursor.app" ]; then
    echo "Opening in Cursor..."
    if [ -f "UX-PROTOTYPES.code-workspace" ]; then
        open -a "Cursor" "UX-PROTOTYPES.code-workspace"
    else
        open -a "Cursor" "$INSTALL_DIR"
    fi
else
    echo "💡 Tip: Install Cursor from https://cursor.sh"
    echo "   Then open the folder: $INSTALL_DIR"
fi

echo ""
echo "Press any key to close this window..."
read -n 1
