#!/bin/bash

# Navigate to the correct directory
cd /home/aiteam/pcaa-dev/dashboard-backend

LOCKFILE="/tmp/orchestrator_loop.lock"

# Check if another instance is already running
if [ -f "$LOCKFILE" ]; then
    PID=$(cat "$LOCKFILE")
    if ps -p $PID > /dev/null; then
        echo "Error: Orchestrator Loop is already running (PID: $PID)."
        exit 1
    fi
fi

# Store the current PID in the lockfile
echo $$ > "$LOCKFILE"

# Ensure lockfile is removed on exit
trap "rm -f $LOCKFILE" EXIT

echo "Starting Orchestrator Loop for BID 1713. Running every 5 minutes."

while true; do
    echo "--- [$(date)] Executing orchestrate_pipeline.py ---"

    # ingest-limit=0  → unlimited: pull ALL new answered calls in one pass
    # transcribe-limit → respect Sarvam STT rate limits
    # analyze-limit    → respect LLM rate limits
    python3 orchestrate_pipeline.py --bid 1713 \
        --ingest-limit 0 \
        --transcribe-limit 20 \
        --analyze-limit 20

    echo "--- [$(date)] Finished iteration. Sleeping for 5 minutes ---"
    sleep 300
done
