#!/bin/bash

# RAG Service Startup Script for Staging/Production
# This script starts the consolidated RAG service

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
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_warning() {
    echo -e "${YELLOW}[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)"
SERVICE_DIR="$SCRIPT_DIR"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

print_status "Starting RAG Service..."
print_status "Service directory: $SERVICE_DIR"
print_status "Project root: $PROJECT_ROOT"

# Check if Python is available
if ! command -v python3 &> /dev/null; then
    print_error "Python 3 is not installed or not in PATH"
    exit 1
fi

# Check if pip is available
if ! command -v pip3 &> /dev/null; then
    print_error "pip3 is not installed or not in PATH"
    exit 1
fi

# Change to service directory
cd "$SERVICE_DIR"

# Create virtual environment if it doesn't exist
if [ ! -d "venv" ]; then
    print_status "Creating Python virtual environment..."
    python3 -m venv venv
    print_success "Virtual environment created"
fi

# Activate virtual environment
print_status "Activating virtual environment..."
source venv/bin/activate

# Install/upgrade requirements
print_status "Installing Python dependencies..."
pip install --upgrade pip
pip install -r requirements.txt
print_success "Dependencies installed"

# Check if .env file exists, if not copy from example
if [ ! -f ".env.local" ] && [ -f ".env.example" ]; then
    print_warning ".env.local not found, copying from .env.example"
    cp .env.example .env.local
    print_status "Please edit .env.local with your configuration"
fi

# Set environment variables
export PYTHONPATH="$SERVICE_DIR:$PYTHONPATH"
export FLASK_APP=app.py
export FLASK_ENV=production

# Get configuration
RAG_SERVICE_HOST=${RAG_SERVICE_HOST:-"0.0.0.0"}
RAG_SERVICE_PORT=${RAG_SERVICE_PORT:-"5002"}

print_status "Starting RAG Service..."
print_status "Host: $RAG_SERVICE_HOST"
print_status "Port: $RAG_SERVICE_PORT"
print_status "Service URL: http://$RAG_SERVICE_HOST:$RAG_SERVICE_PORT/rag-service/"

# Start the service
if [ "$1" = "background" ] || [ "$1" = "daemon" ]; then
    print_status "Starting in background mode..."
    nohup python3 app.py > rag_service.log 2>&1 &
    echo $! > rag_service.pid
    print_success "RAG Service started in background (PID: $(cat rag_service.pid))"
    print_status "Logs: tail -f $SERVICE_DIR/rag_service.log"
else
    print_status "Starting in foreground mode..."
    python3 app.py
fi
