#!/bin/bash
# Sales Prospector Runner with Auto-Restart

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="$SCRIPT_DIR/logs/runner.log"
PID_FILE="$SCRIPT_DIR/run.pid"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# Kill existing
if [[ -f "$PID_FILE" ]]; then
    OLD_PID=$(cat "$PID_FILE")
    if ps -p "$OLD_PID" > /dev/null 2>&1; then
        log "Killing old process $OLD_PID"
        kill "$OLD_PID" 2>/dev/null
        sleep 2
    fi
fi

log "=== Sales Prospector Runner Started ==="

while true; do
    log "Starting prospector..."
    
    bash "$SCRIPT_DIR/prospector-fixed.sh" >> "$LOG_FILE" 2>&1 &
    CURRENT_PID=$!
    echo $CURRENT_PID > "$PID_FILE"
    
    log "PID: $CURRENT_PID"
    
    # Wait for it to finish
    wait $CURRENT_PID
    EXIT_CODE=$?
    
    log "Prospector exited with code $EXIT_CODE"
    
    # Determine restart delay
    if [[ $EXIT_CODE -eq 0 ]]; then
        DELAY=10
        log "Clean exit, restarting in ${DELAY}s"
    else
        DELAY=30
        log "Crash detected, restarting in ${DELAY}s"
    fi
    
    sleep $DELAY
done
