#!/usr/bin/env bash
# stop.sh — detiene el launcher unificado
#
# Uso:
#   ./dev-scripts/server/stop.sh

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

if ! is_launcher_running; then
  dim "  El launcher no está corriendo."
  exit 0
fi

pid="$(read_launcher_pid)"
info "Deteniendo launcher (PID $pid)..."

kill -TERM "$pid" 2>/dev/null || true

# Wait up to 5s for graceful shutdown
for _ in {1..10}; do
  kill -0 "$pid" 2>/dev/null || break
  sleep 0.5
done

# SIGKILL if still alive
if kill -0 "$pid" 2>/dev/null; then
  warn "Launcher no respondió a SIGTERM, enviando SIGKILL..."
  kill -9 "$pid" 2>/dev/null || true
fi

rm -f "$(launcher_pid_file)"
ok "Launcher detenido"
