#!/usr/bin/env bash
# ps.sh — muestra el estado del launcher unificado y agentes
#
# Uso:
#   ./dev-scripts/server/ps.sh

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

if ! is_launcher_running; then
  echo ""
  dim "  Launcher no está corriendo."
  echo ""
  echo "  Agentes:"
  while IFS='|' read -r id _v enabled _d _c; do
    if [[ "$enabled" == "true" ]]; then
      echo -e "  ${GRN}●${RST} $id (enabled)"
    else
      echo -e "  ${DIM}○ $id (disabled)${RST}"
    fi
  done < <(list_agents_raw)
  exit 0
fi

pid="$(read_launcher_pid)"

# Uptime
if [[ -f /proc/$pid/stat ]]; then
  start_ticks=$(awk '{print $22}' /proc/$pid/stat 2>/dev/null || echo 0)
  clk_tck=$(getconf CLK_TCK)
  boot_time=$(awk '/btime/{print $2}' /proc/stat)
  proc_start=$((boot_time + start_ticks / clk_tck))
  now=$(date +%s)
  elapsed=$((now - proc_start))
  days=$((elapsed / 86400))
  hours=$(( (elapsed % 86400) / 3600 ))
  mins=$(( (elapsed % 3600) / 60 ))
  if [[ $days -gt 0 ]]; then
    uptime="${days}d ${hours}h"
  elif [[ $hours -gt 0 ]]; then
    uptime="${hours}h ${mins}m"
  else
    uptime="${mins}m"
  fi
else
  uptime="n/a"
fi

# Memory and CPU
read -r mem_kb cpu_pct < <(ps -p "$pid" -o rss=,pcpu= 2>/dev/null || echo "0 0")
if [[ "$mem_kb" -gt 1048576 ]]; then
  mem="$(( mem_kb / 1048576 )) GB"
elif [[ "$mem_kb" -gt 1024 ]]; then
  mem="$(( mem_kb / 1024 )) MB"
else
  mem="${mem_kb} KB"
fi

# Log size
log="$(launcher_log_file)"
if [[ -f "$log" ]]; then
  log_bytes=$(stat -c%s "$log" 2>/dev/null || echo 0)
  if [[ "$log_bytes" -gt 1048576 ]]; then
    log_size="$(( log_bytes / 1048576 )) MB"
  elif [[ "$log_bytes" -gt 1024 ]]; then
    log_size="$(( log_bytes / 1024 )) KB"
  else
    log_size="${log_bytes} B"
  fi
else
  log_size="-"
fi

echo ""
echo -e "  ${GRN}● Launcher running${RST}  PID $pid"
echo -e "  uptime: $uptime  mem: $mem  cpu: ${cpu_pct}%  log: $log_size"
echo ""
echo "  Agentes:"

while IFS='|' read -r id _v enabled _d _c; do
  if [[ "$enabled" == "true" ]]; then
    echo -e "  ${GRN}●${RST} $id (enabled, running in launcher)"
  else
    echo -e "  ${DIM}○ $id (disabled)${RST}"
  fi
done < <(list_agents_raw)
