#!/bin/bash

# API restart script with virtual environment support
# Properly activates venv before starting the API

cd /home/plagis/workspace/plagis_aumentum

echo "🔄 Restarting Aumentum API with venv..."
echo ""

# Find and kill existing API process
API_PID=$(ps aux | grep "python.*aumentum_api.py" | grep -v grep | awk '{print $2}')

if [ -n "$API_PID" ]; then
    echo "⏹️  Stopping existing API (PID: $API_PID)..."
    kill $API_PID
    sleep 2
    
    # Force kill if still running
    if ps -p $API_PID > /dev/null 2>&1; then
        echo "   Force killing..."
        kill -9 $API_PID
        sleep 1
    fi
    
    echo "   ✅ Stopped"
else
    echo "ℹ️  No existing API process found"
fi

echo ""
echo "🚀 Starting API with virtual environment..."
echo "   Port: 8001"
echo "   Logs: server.log"
echo ""

# Check if venv exists
if [ ! -d "venv" ]; then
    echo "❌ Virtual environment not found!"
    echo "   Please create it first: python3 -m venv venv"
    exit 1
fi

# Start API with venv in background using bash subshell
bash -c "source venv/bin/activate && nohup python3 aumentum_api.py > server.log 2>&1 &"

sleep 3

# Find the new PID
NEW_PID=$(ps aux | grep "python.*aumentum_api.py" | grep -v grep | awk '{print $2}')

if [ -n "$NEW_PID" ]; then
    echo "✅ API started successfully (PID: $NEW_PID)"
    echo ""
    echo "📊 Testing health check..."
    
    sleep 2
    
    # Test health endpoint
    HEALTH_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:8001/health)
    
    if [ "$HEALTH_STATUS" = "200" ]; then
        echo "   ✅ API is healthy and ready"
        echo ""
        echo "🧪 Testing supporting documents endpoint..."
        TEST_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:8001/documents/pdf-by-document-number-fixed?document_id=10000000228624")
        
        if [ "$TEST_STATUS" = "200" ] || [ "$TEST_STATUS" = "404" ]; then
            echo "   ✅ Supporting documents endpoint is working (HTTP $TEST_STATUS)"
            if [ "$TEST_STATUS" = "404" ]; then
                echo "      Note: 404 means endpoint works but document not found in DB"
            fi
        elif [ "$TEST_STATUS" = "422" ]; then
            echo "   ⚠️  Still getting 422 error - API may need more time to start"
            echo "      Wait 5 seconds and try again"
        else
            echo "   Status: HTTP $TEST_STATUS"
        fi
    else
        echo "   ⚠️  API started but health check returned: $HEALTH_STATUS"
        echo "   Check server.log for details"
    fi
    
    echo ""
    echo "📝 Recent log output:"
    echo "-------------------"
    tail -30 server.log | head -20
    echo "-------------------"
    echo ""
    echo "💡 View live logs: tail -f server.log"
    echo "💡 Stop API: kill $NEW_PID"
    
else
    echo "❌ Failed to start API"
    echo ""
    echo "📝 Error log:"
    echo "-------------------"
    tail -30 server.log
    echo "-------------------"
    exit 1
fi

echo ""
echo "✨ Ready to test supporting documents in UI!"
echo "   Refresh your browser and try viewing a supporting document"
echo ""

