#!/bin/bash

# PWA Setup Script for Echoes of the Ashes
# This script helps set up the PWA for the first time

set -e  # Exit on error

echo "=================================================="
echo "  Echoes of the Ashes - PWA Setup"
echo "=================================================="
echo ""

# Check if we're in the right directory
if [ ! -f "docker-compose.yml" ]; then
    echo "❌ Error: docker-compose.yml not found!"
    echo "Please run this script from the project root directory."
    exit 1
fi

echo "✅ Found docker-compose.yml"
echo ""

# Step 1: Check .env file
echo "📝 Step 1: Checking .env file..."
if [ ! -f ".env" ]; then
    echo "❌ Error: .env file not found!"
    echo "Please create .env file with database credentials."
    exit 1
fi

if ! grep -q "JWT_SECRET_KEY" .env; then
    echo "⚠️  Warning: JWT_SECRET_KEY not found in .env"
    echo "Generating a secure JWT secret key..."
    JWT_SECRET=$(openssl rand -hex 32)
    echo "" >> .env
    echo "# JWT Secret for API Authentication" >> .env
    echo "JWT_SECRET_KEY=$JWT_SECRET" >> .env
    echo "✅ Added JWT_SECRET_KEY to .env"
else
    echo "✅ JWT_SECRET_KEY already configured"
fi
echo ""

# Step 2: Install npm dependencies
echo "📦 Step 2: Installing NPM dependencies..."
if [ ! -d "pwa/node_modules" ]; then
    echo "Installing dependencies in pwa/ directory..."
    cd pwa
    npm install
    cd ..
    echo "✅ NPM dependencies installed"
else
    echo "✅ NPM dependencies already installed"
fi
echo ""

# Step 3: Check for PWA icons
echo "🎨 Step 3: Checking PWA icons..."
MISSING_ICONS=0
for icon in pwa/public/pwa-192x192.png pwa/public/pwa-512x512.png pwa/public/apple-touch-icon.png pwa/public/favicon.ico; do
    if [ ! -f "$icon" ]; then
        echo "⚠️  Missing: $icon"
        MISSING_ICONS=1
    fi
done

if [ $MISSING_ICONS -eq 1 ]; then
    echo ""
    echo "⚠️  Warning: Some PWA icons are missing."
    echo "Creating placeholder icons..."
    
    # Create simple placeholder icons using ImageMagick if available
    if command -v convert &> /dev/null; then
        echo "Using ImageMagick to create placeholder icons..."
        cd pwa/public
        
        # Create 192x192 icon
        convert -size 192x192 xc:#646cff -font DejaVu-Sans-Bold -pointsize 72 \
                -fill white -gravity center -annotate +0+0 'E' pwa-192x192.png 2>/dev/null || true
        
        # Create 512x512 icon
        convert -size 512x512 xc:#646cff -font DejaVu-Sans-Bold -pointsize 200 \
                -fill white -gravity center -annotate +0+0 'E' pwa-512x512.png 2>/dev/null || true
        
        # Create apple touch icon
        convert -size 180x180 xc:#646cff -font DejaVu-Sans-Bold -pointsize 72 \
                -fill white -gravity center -annotate +0+0 'E' apple-touch-icon.png 2>/dev/null || true
        
        cd ../..
        echo "✅ Created placeholder icons"
    else
        echo "⚠️  ImageMagick not found. Please create icons manually."
        echo "See pwa/public/README.md for instructions."
    fi
else
    echo "✅ All PWA icons present"
fi
echo ""

# Step 4: Run database migration
echo "🗄️  Step 4: Running database migration..."
echo "This adds web authentication support to the players table."
read -p "Do you want to run the migration now? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if docker ps | grep -q echoes_of_the_ashes_bot; then
        docker exec -it echoes_of_the_ashes_bot python migrate_web_auth.py
        echo "✅ Migration completed"
    else
        echo "⚠️  Bot container not running. You'll need to run migration manually:"
        echo "   docker exec -it echoes_of_the_ashes_bot python migrate_web_auth.py"
    fi
else
    echo "⚠️  Skipping migration. Remember to run it before starting the API!"
    echo "   docker exec -it echoes_of_the_ashes_bot python migrate_web_auth.py"
fi
echo ""

# Step 5: Build and start services
echo "🐳 Step 5: Building and starting Docker services..."
read -p "Do you want to build and start the PWA services now? (y/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    echo "Building API and PWA containers..."
    docker-compose up -d --build echoes_of_the_ashes_api echoes_of_the_ashes_pwa
    echo "✅ Services started"
    echo ""
    echo "Waiting for services to initialize (10 seconds)..."
    sleep 10
    
    # Check service health
    echo ""
    echo "🔍 Checking service health..."
    
    if docker ps | grep -q echoes_of_the_ashes_api; then
        echo "✅ API container is running"
    else
        echo "❌ API container is not running!"
        echo "Check logs: docker logs echoes_of_the_ashes_api"
    fi
    
    if docker ps | grep -q echoes_of_the_ashes_pwa; then
        echo "✅ PWA container is running"
    else
        echo "❌ PWA container is not running!"
        echo "Check logs: docker logs echoes_of_the_ashes_pwa"
    fi
else
    echo "⚠️  Skipping Docker build. Build manually with:"
    echo "   docker-compose up -d --build echoes_of_the_ashes_api echoes_of_the_ashes_pwa"
fi
echo ""

# Summary
echo "=================================================="
echo "  Setup Complete!"
echo "=================================================="
echo ""
echo "📝 Next Steps:"
echo ""
echo "1. Verify services are running:"
echo "   docker ps | grep echoes"
echo ""
echo "2. Check logs for errors:"
echo "   docker logs echoes_of_the_ashes_api"
echo "   docker logs echoes_of_the_ashes_pwa"
echo ""
echo "3. Test the API:"
echo "   curl https://echoesoftheashgame.patacuack.net/api/"
echo ""
echo "4. Access the PWA:"
echo "   https://echoesoftheashgame.patacuack.net"
echo ""
echo "5. Test registration:"
echo "   curl -X POST https://echoesoftheashgame.patacuack.net/api/auth/register \\"
echo "     -H 'Content-Type: application/json' \\"
echo "     -d '{\"username\": \"testuser\", \"password\": \"testpass123\"}'"
echo ""
echo "📚 Documentation:"
echo "   - PWA_IMPLEMENTATION.md - Implementation summary"
echo "   - PWA_DEPLOYMENT.md - Deployment guide"
echo "   - pwa/README.md - PWA project overview"
echo ""
echo "🎮 Enjoy your new web-based game!"
echo ""
