#!/bin/bash

# SACAP FAQ App - Stop Script for Staging/Production
# This script stops all services

set -e

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

print_header() {
    echo -e "${PURPLE}╔══════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${PURPLE}║                SACAP FAQ App - Stop Services                 ║${NC}"
    echo -e "${PURPLE}╚══════════════════════════════════════════════════════════════╝${NC}"
    echo ""
}

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

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

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

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR"

print_header
print_status "Stopping SACAP FAQ App services..."

cd "$PROJECT_ROOT"

# Function to stop a service by PID file
stop_service() {
    local service_name=$1
    local pid_file=$2

    if [ -f "$pid_file" ]; then
        PID=$(cat "$pid_file")
        print_status "Stopping $service_name (PID: $PID)..."

        # Activate virtual environment before stopping the service
        if [ -f "services/rag-service/venv/bin/activate" ]; then
            source services/rag-service/venv/bin/activate
        fi

        if kill -0 "$PID" 2>/dev/null; then
            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 $service_name..."
                kill -9 "$PID"
            fi

            print_success "$service_name stopped"
        else
            print_status "$service_name process not running"
        fi

        # Deactivate virtual environment
        deactivate 2>/dev/null || true

        rm -f "$pid_file"
    else
        print_status "No PID file found for $service_name"
    fi
}

# Stop all services
print_status "Stopping all services..."

# Stop Vite (if running)
stop_service "Vite" "vite.pid"

# Stop Laravel (if running)
stop_service "Laravel" "laravel.pid"

# Stop RAG Service
stop_service "RAG Service" "services/rag-service/rag_service.pid"

# Additional cleanup - kill any remaining processes
print_status "Cleaning up any remaining processes..."

# Kill any remaining Python RAG service processes
pkill -f "python.*rag.*app.py" || true

# Kill any remaining Laravel artisan serve processes
pkill -f "artisan serve" || true

# Kill any remaining Vite processes
pkill -f "vite" || true

print_success "All services stopped! 🛑"
print_status "Cleanup complete."
