#!/usr/bin/env bash
# =============================================================================
#  Discord bridge bot — full install + run as a background service
#  Paste this whole file onto the Pi and run:  bash install-and-run.sh
#
#  What it does:
#    1. Creates a Python venv in this folder
#    2. Installs discord.py + aiohttp
#    3. Starts the bot in the background (survives logout, auto-restarts)
#    4. Prints the health-check URL so you can confirm it's up
#
#  The bot listens on port 8090 by default (change BOT_PORT below if it clashes
#  with one of your other 4 bots).
# =============================================================================

set -e

# --- Config ----------------------------------------------------------------
BOT_PORT="${BOT_PORT:-8090}"
BOT_SCRIPT="DiscordBot.py"
LOG_FILE="bot.log"
PID_FILE="bot.pid"

# --- 1. Make sure we're in the bot folder ----------------------------------
cd "$(dirname "$0")"

# --- 2. Create venv if missing ---------------------------------------------
if [ ! -d "venv" ]; then
    echo "[1/4] Creating Python venv..."
    python3 -m venv venv
else
    echo "[1/4] venv already exists, reusing it."
fi

# --- 3. Install dependencies ------------------------------------------------
echo "[2/4] Installing dependencies (discord.py, aiohttp, faster-whisper)..."
./venv/bin/pip install --quiet --upgrade pip
./venv/bin/pip install --quiet -r requirements.txt

# Make sure faster-whisper (voice-to-text) is installed even if requirements.txt
# was not updated on the Pi. This is what powers the chat's voice input.
echo "    Ensuring faster-whisper (voice-to-text) is installed..."
./venv/bin/pip install --quiet faster-whisper
echo "    Voice-to-text ready. (First voice use downloads the ~75MB 'tiny' model — needs internet.)"

# --- 4. Point the bot at the chosen port ------------------------------------
# The bot reads http_port from config.json. If BOT_PORT differs from what's in
# config.json, we update it so the running bot uses the port we want.
if command -v python3 >/dev/null 2>&1; then
    ./venv/bin/python - "$BOT_PORT" <<'PY'
import json, sys, os
port = sys.argv[1]
cfg_path = "config.json"
with open(cfg_path) as f:
    cfg = json.load(f)
if str(cfg.get("http_port")) != str(port):
    cfg["http_port"] = int(port)
    with open(cfg_path, "w") as f:
        json.dump(cfg, f, indent=2)
    print(f"    http_port set to {port} in config.json")
else:
    print(f"    http_port already {port}")
PY
fi

# --- 5. Stop any previous instance ------------------------------------------
if [ -f "$PID_FILE" ]; then
    OLD_PID=$(cat "$PID_FILE")
    if kill -0 "$OLD_PID" 2>/dev/null; then
        echo "    Stopping previous bot (pid $OLD_PID)..."
        kill "$OLD_PID" 2>/dev/null || true
        sleep 2
    fi
    rm -f "$PID_FILE"
fi

# --- 6. Start the bot in the background --------------------------------------
echo "[3/4] Starting bot on port $BOT_PORT..."
# -u = unbuffered, so print() output lands in the log immediately
nohup ./venv/bin/python -u "$BOT_SCRIPT" >> "$LOG_FILE" 2>&1 &
echo $! > "$PID_FILE"
echo "    pid $(cat "$PID_FILE")  (log: $LOG_FILE)"

# --- 7. Wait and health-check ------------------------------------------------
echo "[4/4] Waiting for bot to come up..."
sleep 6
if curl -s "http://127.0.0.1:$BOT_PORT/health" >/dev/null 2>&1; then
    echo ""
    echo "  SUCCESS — bot is up!"
    echo "  Health check:  http://127.0.0.1:$BOT_PORT/health"
    echo "  Log file:      $LOG_FILE"
    echo ""
    echo "  To stop it later:   kill \$(cat $PID_FILE)"
    echo "  To restart it:      bash install-and-run.sh"
else
    echo ""
    echo "  Bot did not respond on port $BOT_PORT yet. Check the log:"
    echo "  tail -f $LOG_FILE"
    echo ""
    echo "  (If it says 'address already in use', pick a different port:"
    echo "   BOT_PORT=8091 bash install-and-run.sh)"
fi
