#!/usr/bin/env bash
# Restart COMPLETO de V4 (botón "Restart Scanners" del panel Settings):
#   1) cold-boot SOLO de los emuladores del scanner 6000/6002 (restart_v3_lowpower.sh en V4_MODE=1:
#      relaunch headless + Magisk + frida + Evony + auto-login desde disco). En V4_MODE NO arranca el
#      backend V3 ni espera sus ~90s de attach -> se acabó el "detour por V3" que confundía al usuario.
#   2) switch a V4 (run_v4.sh both) -> attacha el agente V4 directamente sobre 6000/6002.
# Se lanza DESACOPLADO desde el backend (start_new_session) porque los pasos matan/relanzan el propio
# backend V4. ~1.5-2 min. Recupera cualquier estado colgado (emulador/juego en negro/agente atascado/FREEZE).
#
# SEGURIDAD DEL BOT: este restart SOLO toca los emuladores 6000/6002 y el backend :8772 (scanner).
# NUNCA toca el bot (emulador 6004 / backend :8780/:8781). Lo verificamos explícitamente antes/después.
set -u
HERE="$(cd "$(dirname "$0")" && pwd)"
V3="$(cd "$HERE/../evony-scout-v3-research" && pwd)"
ts(){ date +%H:%M:%S; }

# --- snapshot del bot ANTES (para garantizar que el restart del scanner no lo altera) ---
BOT_PID_BEFORE="$(lsof -ti tcp:8780 2>/dev/null | head -1)"
BOT_EMU_BEFORE="$(adb -s emulator-6004 get-state 2>/dev/null | tr -d '\r')"
echo "[restart-v4-full] $(ts) bot ANTES:  :8780=${BOT_PID_BEFORE:-libre}  emulator-6004=${BOT_EMU_BEFORE:-off}"

echo "[restart-v4-full] $(ts) cold-boot SOLO scanners 6000/6002 (V4_MODE=1, sin arrancar V3)..."
V4_MODE=1 bash "$V3/restart_v3_lowpower.sh"

echo "[restart-v4-full] $(ts) switch a V4 (run_v4.sh both)..."
bash "$HERE/run_v4.sh" both

# --- verificar que el bot NO se tocó ---
BOT_PID_AFTER="$(lsof -ti tcp:8780 2>/dev/null | head -1)"
BOT_EMU_AFTER="$(adb -s emulator-6004 get-state 2>/dev/null | tr -d '\r')"
echo "[restart-v4-full] $(ts) bot DESPUES: :8780=${BOT_PID_AFTER:-libre}  emulator-6004=${BOT_EMU_AFTER:-off}"
if [ "$BOT_EMU_BEFORE" != "$BOT_EMU_AFTER" ]; then
  echo "[restart-v4-full] $(ts) AVISO: el emulador del bot (6004) cambió de estado durante el restart del scanner (no debería). Revisar."
else
  echo "[restart-v4-full] $(ts) OK: bot intacto (el restart del scanner no tocó 6004/:8780)."
fi
echo "[restart-v4-full] $(ts) hecho."
