#!/bin/bash
# Quick deployment script for PDF generation fix

echo "=========================================="
echo "PDF Generation Fix - Deployment Script"
echo "=========================================="
echo ""

# Check if we're in the right directory
if [ ! -f "loans/minimal_analytics.py" ]; then
    echo "❌ Error: Not in the correct directory"
    echo "   Please run this from /home/acbptxvs/public_html"
    exit 1
fi

echo "📋 Step 1: Creating backup..."
cp loans/minimal_analytics.py loans/minimal_analytics.py.backup.$(date +%Y%m%d_%H%M%S)
if [ $? -eq 0 ]; then
    echo "✅ Backup created successfully"
else
    echo "❌ Backup failed"
    exit 1
fi

echo ""
echo "📋 Step 2: Checking ReportLab installation..."
source venv/bin/activate 2>/dev/null || true
python -c "import reportlab; print('✅ ReportLab version:', reportlab.Version)" 2>/dev/null
if [ $? -ne 0 ]; then
    echo "⚠️  ReportLab not found, installing..."
    pip install reportlab
fi

echo ""
echo "📋 Step 3: Validating syntax..."
python -m py_compile loans/minimal_analytics.py
if [ $? -eq 0 ]; then
    echo "✅ Syntax validation passed"
else
    echo "❌ Syntax error detected"
    exit 1
fi

echo ""
echo "📋 Step 4: Restarting application..."
touch tmp/restart.txt
if [ $? -eq 0 ]; then
    echo "✅ Application restart triggered"
else
    echo "❌ Failed to restart application"
    exit 1
fi

echo ""
echo "=========================================="
echo "✅ Deployment completed successfully!"
echo "=========================================="
echo ""
echo "Next steps:"
echo "1. Go to: https://branchbusinessadvance.co.ke/loans/"
echo "2. Click 'Generate PDF' button"
echo "3. Verify PDF downloads correctly"
echo ""
echo "If issues occur, rollback with:"
echo "  cp loans/minimal_analytics.py.backup.* loans/minimal_analytics.py"
echo "  touch tmp/restart.txt"
echo ""
