#!/bin/bash

# RAG Service Stop Script

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

print_status() {
    echo -e "${BLUE}[RAG-SERVICE]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[RAG-SERVICE]${NC} $1"
}

print_error() {
    echo -e "${RED}[RAG-SERVICE]${NC} $1"
}

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

print_status "Stopping RAG Service..."

cd "$SCRIPT_DIR"

# Check if PID file exists
if [ -f "rag_service.pid" ]; then
    PID=$(cat rag_service.pid)
    print_status "Found PID file with PID: $PID"
    
    # Check if process is still running
    if kill -0 "$PID" 2>/dev/null; then
        print_status "Stopping process $PID..."
        kill "$PID"
        
        # Wait for process to stop
        for i in {1..10}; do
            if ! kill -0 "$PID" 2>/dev/null; then
                break
            fi
            sleep 1
        done
        
        # Force kill if still running
        if kill -0 "$PID" 2>/dev/null; then
            print_status "Force killing process $PID..."
            kill -9 "$PID"
        fi
        
        print_success "RAG Service stopped"
    else
        print_status "Process $PID is not running"
    fi
    
    # Remove PID file
    rm -f rag_service.pid
else
    print_status "No PID file found"
fi

# Also try to kill any Python processes running app.py
print_status "Checking for any remaining RAG service processes..."
pkill -f "python.*app.py" || true

print_success "RAG Service stop script completed"
