#!/usr/bin/env bash
# V4 — compila los dos agentes (W/E) desde agent_v4.ts reemplazando los placeholders.
# Mismo toolchain que V3 (frida-il2cpp-bridge@0.13.1 + frida-compile@19.0.5 en /tmp/il2cpp_work).
# El agente V4 escanea por PROTOBUF DIRECTO (__request_worldmap), sin mover la cámara (V4_DIRECT=true
# dentro de agent_v4.ts; ponlo en false para fallback a barrido por cámara estilo V3).
# Uso: ./build_agents_v4.sh            -> defaults (W/0, E/0)
#      ./build_agents_v4.sh W 0 E 0    -> explícito (regionW serverW regionE serverE)
set -e
HERE="$(cd "$(dirname "$0")" && pwd)"
WORK="/tmp/il2cpp_work"
NODE_BIN="/Users/danicosta/.nvm/versions/node/v22.11.0/bin"
export PATH="$NODE_BIN:$PATH"

if [ ! -d "$WORK/node_modules/.bin" ]; then
  echo "[build] ERROR: $WORK no preparado (frida-compile/frida-il2cpp-bridge)."
  echo "        Reconstruir como en V3: ver reference_build_env (frida-il2cpp-bridge@0.13.1 + frida-compile@19.0.5)."
  exit 1
fi

RW="${1:-W}"; SW="${2:-0}"; RE="${3:-E}"; SE="${4:-0}"

cp "$HERE/agent_v4.ts" "$WORK/agent_v4.ts"
cd "$WORK"
sed -e "s/SCANHALF_PLACEHOLDER/$RW/" -e "s/FORCESERVER_PLACEHOLDER/$SW/" agent_v4.ts > agent_v4_W.ts
sed -e "s/SCANHALF_PLACEHOLDER/$RE/" -e "s/FORCESERVER_PLACEHOLDER/$SE/" agent_v4.ts > agent_v4_E.ts
echo "[build] V4 W=region:$RW server:$SW | E=region:$RE server:$SE"
# El backend V4 carga agent_W.js / agent_E.js desde su dir (iscout_web.py:1556) -> esos nombres.
node_modules/.bin/frida-compile agent_v4_W.ts -o agent_W.js
node_modules/.bin/frida-compile agent_v4_E.ts -o agent_E.js
cp agent_W.js agent_E.js "$HERE/"
echo "[build] OK -> agent_W.js ($(wc -c < "$HERE/agent_W.js")b) agent_E.js ($(wc -c < "$HERE/agent_E.js")b)"
