#!/usr/bin/env bash
# start.sh — inicia el launcher unificado (todos los agentes habilitados)
#
# Uso:
#   ./dev-scripts/server/start.sh              # inicia el launcher unificado

source "$(dirname "$0")/../_common.sh"
load_env

if is_launcher_running; then
  pid="$(read_launcher_pid)"
  fail "El launcher ya está corriendo (PID $pid). Usa restart.sh para reiniciar."
fi

BIN="$REPO_ROOT/bin/launcher"
LOG="$(launcher_log_file)"
PID_F="$(launcher_pid_file)"

# Always rebuild — Go is fast and avoids stale binaries from changes in pkg/, agents/, etc.
info "Ejecutando tests..."
"$GO" test -tags goolm ./... || fail "Tests fallaron — corrige antes de compilar"

info "Compilando launcher..."
mkdir -p "$(dirname "$BIN")"
"$GO" build -tags goolm -o "$BIN" ./cmd/launcher || fail "Error de compilación"

info "Iniciando launcher unificado..."

nohup "$BIN" --log-level "${LOG_LEVEL:-info}" \
  >> "$LOG" 2>&1 &

pid=$!
echo "$pid" > "$PID_F"

sleep 1
if kill -0 "$pid" 2>/dev/null; then
  # Count enabled agents
  enabled=0
  total=0
  while IFS='|' read -r _id _v en _d _c; do
    ((total++)) || true
    [[ "$en" == "true" ]] && ((enabled++)) || true
  done < <(list_agents_raw)

  ok "Launcher PID $pid  ($enabled/$total agentes habilitados)  →  logs: $LOG"
else
  rm -f "$PID_F"
  fail "Launcher arrancó pero murió — revisa: tail -f $LOG"
fi
