#!/usr/bin/env bash
# App híbrida (escáner + bot en una cuenta). Arranque en el ORDEN correcto.
#
# ⚠️ El orden importa: si el backend attacha el agente mientras Evony carga en frío,
# el juego se queda clavado en "Loading" o se muere. Por eso esperamos a que la cuenta
# esté dentro antes de arrancar el backend.
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
DEV="${BOT_EMULATOR:-emulator-6008}"
PORT="${BOT_PORT:-8783}"

echo "[run] dispositivo=$DEV puerto=$PORT"

# 1) emulador vivo
if ! adb devices | grep -q "^${DEV}[[:space:]]*device"; then
  echo "[run] $DEV no está. Arráncalo:"
  echo "      /opt/homebrew/share/android-commandlinetools/emulator/emulator -avd evony_hibrid -port 6008 -no-snapshot-load -no-snapshot-save -no-boot-anim -gpu host -no-audio &"
  exit 1
fi

# 2) frida-server
if ! adb -s "$DEV" shell "ps -A | grep -q frida-server" 2>/dev/null; then
  echo "[run] arrancando frida-server..."
  adb -s "$DEV" shell "su -c '/data/local/tmp/frida-server -D'" >/dev/null 2>&1 || true
  sleep 3
fi

# 3) Evony delante
adb -s "$DEV" shell "am start -n com.topgamesinc.evony/com.topgamesinc.androidplugin.UnityActivity" >/dev/null 2>&1 || true

# 4) esperar a que la cuenta esté DENTRO (no sólo el proceso arriba)
echo "[run] esperando a que Evony cargue la cuenta..."
for i in $(seq 1 60); do
  RSS=$(adb -s "$DEV" shell "ps -A | grep evony" 2>/dev/null | awk '{print $6}' | tr -d '\r')
  if [ -n "$RSS" ] && [ "$RSS" -gt 1000000 ] 2>/dev/null; then echo "[run] cuenta cargada (RSS ${RSS}K)"; break; fi
  sleep 5
done

# 5) backend
cd "$HERE"
echo "[run] backend en http://127.0.0.1:$PORT"
exec python3 bot_web.py
