#!/bin/bash

# Start AI Lawyer RAG Service
# Advanced Document Processing with FAISS + BM25 + Grok AI
echo "Starting AI Lawyer RAG Service (Advanced)..."
echo "================================================================"

# Set the working directory
cd "$(dirname "$0")/.."

# Use the leadgen RAG venv which has all dependencies
VENV_DIR="/var/www/html/leadgen/airagagent/rag_env"
if [ -d "$VENV_DIR" ]; then
    echo "Activating leadgen RAG virtual environment..."
    source "$VENV_DIR/bin/activate"
else
    # Fallback to local venv
    VENV_DIR="python_service/venv"
    if [ -d "$VENV_DIR" ]; then
        echo "Activating local virtual environment..."
        source "$VENV_DIR/bin/activate"
    else
        echo "Warning: No virtual environment found, using system Python"
    fi
fi

# Load environment variables
if [ -f ".env" ]; then
    echo "Loading environment variables from .env..."
    export FLASK_API_KEY=$(grep "^FLASK_API_KEY=" .env | cut -d'=' -f2)
    export GROK_API_KEY=$(grep "^GROK_API_KEY=" .env | cut -d'=' -f2)
fi

# Set AI Lawyer specific port (5007)
export RAG_PORT="${RAG_PORT:-5007}"

# Set data directory for AI Lawyer (separate from main RAG)
export DATA_DIR="/var/www/html/eventheodds/ai-lawyer-rag/data"

echo "AI Lawyer RAG Port: $RAG_PORT"
echo "Data Directory: $DATA_DIR"

# Ensure data directories exist
mkdir -p "$DATA_DIR/rag_cache"
mkdir -p "$DATA_DIR/csv"

# Start the Advanced AI Lawyer RAG service
echo "Starting Advanced Legal RAG Service..."
cd ai-lawyer-rag
exec python advanced_legal_rag_service.py
