#!/usr/bin/env bash
# bot_v2 — lanza el backend (puerto 8781). INDEPENDIENTE de V3.
# Requisitos: emulator-6006 booteado + cuenta del bot logueada en Evony +
# frida-server en el emulador (ya viene en el clon del AVD de V3).
# El backend attacha solo el agente agent_bot.js a 6006 (no toca V3).
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
PY="/Applications/Xcode.app/Contents/Developer/usr/bin/python3"

# 0) validar backend
"$PY" -c "import py_compile; py_compile.compile('$HERE/bot_web.py', doraise=True)" || { echo "bot_web.py sintaxis rota"; exit 1; }

# 1) compilar agente si falta
[ -f "$HERE/agent_bot.js" ] || { echo "[run] compilando agente..."; bash "$HERE/build_agent.sh"; }

# 2) relanzar backend
pkill -f "bot_v2/bot_web.py" 2>/dev/null || true; sleep 1
lsof -ti :8781 2>/dev/null | xargs -I{} kill -9 {} 2>/dev/null || true

# Por defecto LOCAL (127.0.0.1) — el bot LANZA ataques, mejor no exponerlo.
# Para acceso en red (móvil), exporta BOT_BIND con la IP de Tailscale antes de correr.
BIND="${BOT_BIND:-127.0.0.1}"
echo "[run] bot_v2 -> http://$BIND:8781  (emulador emulator-6006)"
BOT_BIND="$BIND" BOT_PORT=8781 BOT_EMULATOR=emulator-6006 nohup "$PY" "$HERE/bot_web.py" > /tmp/bot_v2.log 2>&1 &
disown
sleep 3
echo "--- /tmp/bot_v2.log ---"
tail -10 /tmp/bot_v2.log 2>/dev/null || true
