#!/usr/bin/env bash
# server.sh — gestión unificada del servidor de bots
#
# Uso:
#   ./dev-scripts/server/server.sh start            # iniciar el launcher
#   ./dev-scripts/server/server.sh stop             # detener el launcher
#   ./dev-scripts/server/server.sh restart          # reiniciar el launcher
#   ./dev-scripts/server/server.sh status           # resumen general del servidor
#   ./dev-scripts/server/server.sh ps               # proceso con detalle
#   ./dev-scripts/server/server.sh logs [lines]     # tail -f de logs
#   ./dev-scripts/server/server.sh kill             # SIGKILL forzado (emergencia)
#   ./dev-scripts/server/server.sh enable  <id>     # habilitar un agente
#   ./dev-scripts/server/server.sh disable <id>     # deshabilitar un agente
#   ./dev-scripts/server/server.sh dashboard        # TUI interactivo

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

CMD="${1:-status}"
shift || true
ARG="${1:-}"

toggle_agent_enabled() {
  local id="$1" value="$2"
  for cfg in agents/*/config.yaml; do
    [[ -f "$cfg" ]] || continue
    local cid
    cid=$(grep -m1 '^  id:' "$cfg" | awk '{print $2}')
    if [[ "$cid" == "$id" ]]; then
      sed -i "s/^\\(  enabled:\\).*/\\1 $value/" "$cfg"
      ok "$id  enabled: $value"
      info "Reinicia el launcher para aplicar: ./dev-scripts/server/server.sh restart"
      return 0
    fi
  done
  fail "Agente '$id' no encontrado"
}

case "$CMD" in
  start)
    exec "$REPO_ROOT/dev-scripts/server/start.sh"
    ;;

  stop)
    exec "$REPO_ROOT/dev-scripts/server/stop.sh"
    ;;

  restart)
    exec "$REPO_ROOT/dev-scripts/server/restart.sh"
    ;;

  ps)
    exec "$REPO_ROOT/dev-scripts/server/ps.sh"
    ;;

  logs)
    exec "$REPO_ROOT/dev-scripts/server/logs.sh" ${ARG:+"$ARG"}
    ;;

  dashboard|tui)
    exec "$REPO_ROOT/dev-scripts/server/dashboard.sh"
    ;;

  enable)
    [[ -n "$ARG" ]] || fail "Uso: $0 enable <agent-id>"
    toggle_agent_enabled "$ARG" "true"
    ;;

  disable)
    [[ -n "$ARG" ]] || fail "Uso: $0 disable <agent-id>"
    toggle_agent_enabled "$ARG" "false"
    ;;

  kill)
    if ! is_launcher_running; then
      dim "  El launcher no está corriendo."
      exit 0
    fi
    pid="$(read_launcher_pid)"
    kill -9 "$pid" 2>/dev/null || true
    rm -f "$(launcher_pid_file)"
    ok "Launcher killed (PID $pid)"
    ;;

  status)
    echo ""
    echo -e "  ${BLU}Bot Server Status${RST}"
    printf '%s\n' "  $(printf '─%.0s' {1..40})"

    if is_launcher_running; then
      pid="$(read_launcher_pid)"
      echo -e "  ${GRN}● Launcher running${RST}  PID $pid"
    else
      echo -e "  ${DIM}○ Launcher stopped${RST}"
    fi

    echo ""

    enabled=0
    disabled=0
    total=0
    while IFS='|' read -r id _v en _d _c; do
      ((total++)) || true
      if [[ "$en" == "true" ]]; then
        ((enabled++)) || true
      else
        ((disabled++)) || true
      fi
    done < <(list_agents_raw)

    echo -e "  Agentes totales:    $total"
    echo -e "  ${GRN}● Enabled:${RST}          $enabled"
    echo -e "  ${DIM}○ Disabled:${RST}         $disabled"
    echo ""

    "$REPO_ROOT/dev-scripts/agent/list.sh"

    if is_launcher_running; then
      echo ""
      "$REPO_ROOT/dev-scripts/server/ps.sh"
    fi
    ;;

  *)
    echo "Uso: $0 {start|stop|restart|status|ps|logs|kill|enable|disable|dashboard}"
    echo ""
    echo "Comandos:"
    echo "  start            Iniciar el launcher unificado"
    echo "  stop             Detener el launcher"
    echo "  restart          Reiniciar el launcher"
    echo "  status           Resumen general del servidor"
    echo "  ps               Proceso del launcher con detalle (PID, mem, CPU)"
    echo "  logs    [lines]  Tail -f de logs del launcher"
    echo "  kill             SIGKILL forzado (solo emergencias)"
    echo "  enable  <id>     Habilitar un agente (requiere restart)"
    echo "  disable <id>     Deshabilitar un agente (requiere restart)"
    echo "  dashboard        TUI interactivo de gestión"
    exit 1
    ;;
esac
