#!/bin/bash

echo "════════════════════════════════════════════════════════════════"
echo "  🔧 FIXING 500 INTERNAL SERVER ERROR"
echo "════════════════════════════════════════════════════════════════"
echo ""

# Fix 1: File and Directory Permissions
echo "1️⃣  Fixing file permissions..."
sudo chmod +x /home/plagis
sudo chmod +x /home/plagis/workspace
sudo chmod +x /home/plagis/workspace/plagis_aumentum
sudo chmod -R 755 /home/plagis/workspace/plagis_aumentum/web_frontend/
echo "   ✅ Permissions fixed"
echo ""

# Fix 2: Verify API is Running
echo "2️⃣  Checking API server..."
if ps aux | grep -q "[a]umentum_api.py"; then
    echo "   ✅ API server is running"
else
    echo "   ⚠️  Starting API server..."
    cd /home/plagis/workspace/plagis_aumentum
    source venv/bin/activate
    nohup python3 aumentum_api.py > api.log 2>&1 &
    sleep 2
    echo "   ✅ API server started"
fi
echo ""

# Fix 3: Restart Nginx
echo "3️⃣  Restarting nginx..."
sudo systemctl restart nginx
sleep 1
echo "   ✅ Nginx restarted"
echo ""

# Fix 4: Test Configuration
echo "4️⃣  Testing configuration..."
echo ""

echo "   Testing API directly (127.0.0.1:8001):"
if curl -s http://127.0.0.1:8001/ | grep -q "service"; then
    echo "   ✅ API responding"
else
    echo "   ❌ API not responding"
fi

echo ""
echo "   Testing nginx frontend (127.0.0.1:7000):"
if curl -s http://127.0.0.1:7000/ | grep -q "DOCTYPE"; then
    echo "   ✅ Frontend accessible"
else
    echo "   ❌ Frontend not accessible - checking error..."
    echo ""
    echo "   Last nginx errors:"
    sudo tail -5 /var/log/nginx/error.log
fi

echo ""
echo "   Testing nginx API proxy (127.0.0.1:7000/api/):"
if curl -s http://127.0.0.1:7000/api/ | grep -q "service"; then
    echo "   ✅ API proxy working"
else
    echo "   ❌ API proxy not working"
fi

echo ""
echo "════════════════════════════════════════════════════════════════"
echo "  🎯 RESULTS"
echo "════════════════════════════════════════════════════════════════"
echo ""
echo "If all tests passed:"
echo "  ✅ Access: http://10.10.10.127:7000"
echo "  ✅ Hard refresh browser: Ctrl+Shift+R"
echo ""
echo "If tests failed:"
echo "  Check error log: sudo tail -20 /var/log/nginx/error.log"
echo ""
echo "════════════════════════════════════════════════════════════════"

