#!/bin/bash
# PromoBot management script
DIR="$(cd "$(dirname "$0")" && pwd)"
PIDFILE="$DIR/bot.pid"
LOGFILE="$DIR/bot.log"
PYTHON="$DIR/venv/bin/python"

start() {
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "🤖 Bot is already running (PID: $(cat $PIDFILE))"
        return
    fi
    echo "🚀 Starting bot..."
    nohup $PYTHON "$DIR/bot.py" >> "$LOGFILE" 2>&1 &
    echo $! > "$PIDFILE"
    sleep 2
    if kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "✅ Bot started (PID: $(cat $PIDFILE))"
        echo "📄 Logs: tail -f $LOGFILE"
    else
        echo "❌ Bot failed to start. Check logs:"
        tail -20 "$LOGFILE"
        rm -f "$PIDFILE"
    fi
}

stop() {
    if [ ! -f "$PIDFILE" ]; then
        echo "⚠️  Bot is not running (no PID file)"
        return
    fi
    PID=$(cat "$PIDFILE")
    if kill -0 "$PID" 2>/dev/null; then
        echo "🛑 Stopping bot (PID: $PID)..."
        kill "$PID"
        sleep 2
        if kill -0 "$PID" 2>/dev/null; then
            kill -9 "$PID"
        fi
        echo "✅ Bot stopped."
    else
        echo "⚠️  Bot was not running."
    fi
    rm -f "$PIDFILE"
}

restart() {
    stop
    sleep 1
    start
}

status() {
    if [ -f "$PIDFILE" ] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
        echo "🟢 Bot is running (PID: $(cat $PIDFILE))"
    else
        echo "🔴 Bot is not running."
        rm -f "$PIDFILE" 2>/dev/null
    fi
}

logs() {
    if [ -f "$LOGFILE" ]; then
        tail -50 "$LOGFILE"
    else
        echo "No logs yet."
    fi
}

case "$1" in
    start)   start ;;
    stop)    stop ;;
    restart) restart ;;
    status)  status ;;
    logs)    logs ;;
    *)
        echo "Usage: bash bot.sh {start|stop|restart|status|logs}"
        exit 1
        ;;
esac
