#!/bin/bash
# Supervisor script to keep trading bots alive

BOT_DIR="/home/wkmabra/.openclaw/workspace"
VENV_PY="$BOT_DIR/venv/bin/python"
LOG_FILE="$BOT_DIR/supervisor.log"

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

start_bot() {
    local name=$1
    local script=$2
    
    # Check if already running
    if pgrep -f "$script" > /dev/null 2>&1; then
        return 0
    fi
    
    log "Starting $name..."
    cd "$BOT_DIR"
    $VENV_PY $script >> "$LOG_FILE" 2>&1 &
    echo $! > "/tmp/supervisor_${name}.pid"
}

stop_bot() {
    local name=$1
    local pidfile="/tmp/supervisor_${name}.pid"
    
    if [ -f "$pidfile" ]; then
        local pid=$(cat "$pidfile")
        if kill -0 $pid 2>/dev/null; then
            kill $pid 2>/dev/null
            log "Stopped $name (was running)"
        fi
        rm -f "$pidfile"
    fi
}

# Main loop
log "Supervisor starting..."

BOTS=(
    "BTC:btc_v2.py"
    #"ETH:eth_v2.py"
    #"XRP:xrp_v2.py"
    #"SOL:sol_v2.py"
)

while true; do
    for bot in "${BOTS[@]}"; do
        name="${bot%%:*}"
        script="${bot##*:}"
        
        if ! pgrep -f "$script" > /dev/null 2>&1; then
            log "Bot $name not running, starting..."
            cd "$BOT_DIR"
            $VENV_PY "$script" >> "$LOG_FILE" 2>&1 &
        fi
    done
    
    # Update dashboard HTML
    cd "$BOT_DIR"
    python3 update_dashboard.py >> "$LOG_FILE" 2>&1

    # Check dashboard server
    if ! pgrep -f "http.server 8081" > /dev/null 2>&1; then
        log "Dashboard not running, starting..."
        cd "$BOT_DIR"
        python3 -m http.server 8081 >> "$LOG_FILE" 2>&1 &
    fi
    
    sleep 30
done
