#!/usr/bin/env zsh
# llm-status.sh — Show current state of all LLM stack components.
source "$(dirname "$0")/llm.conf"

_port_in_use() {
  lsof -ti tcp:$1 >/dev/null 2>&1
}

_status() {
  local label=$1 pid_file=$2 port=$3

  printf "  %-11s" "$label"

  local pid=""
  if [[ -f "$pid_file" ]]; then
    pid=$(cat "$pid_file")
  else
    pid=$(lsof -ti tcp:$port 2>/dev/null | head -1)
  fi

  if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
    local models_json=$(curl -sf --max-time 3 "http://localhost:$port/v1/models" 2>/dev/null)
    if [[ -n "$models_json" ]]; then
      local model_name=$(echo "$models_json" | python3 -c \
        "import sys,json; d=json.load(sys.stdin); print(d['data'][0]['id'].split('/')[-1] if d.get('data') else '?')" 2>/dev/null)
      printf "\033[32m● UP\033[0m    PID %-7s :%-5s %s\n" "$pid" "$port" "$model_name"
    else
      printf "\033[33m◐ STARTING\033[0m PID %-7s :%-5s\n" "$pid" "$port"
    fi
  else
    printf "\033[31m○ DOWN\033[0m\n"
  fi
}

_status_proxy() {
  printf "  %-11s" "proxy"
  local pid=""
  if [[ -f "$PROXY_PID" ]]; then
    pid=$(cat "$PROXY_PID")
  else
    pid=$(lsof -ti tcp:$PROXY_PORT 2>/dev/null | head -1)
  fi
  if [[ -n "$pid" ]] && kill -0 "$pid" 2>/dev/null; then
    printf "\033[32m● UP\033[0m    PID %-7s :%-5s\n" "$pid" "$PROXY_PORT"
  else
    printf "\033[31m○ DOWN\033[0m\n"
  fi
}

echo "╔══════════════════════════════════════════════╗"
echo "║  LLM Stack Status                           ║"
echo "╚══════════════════════════════════════════════╝"
echo ""

# ── Inference servers ─────────────────────────────────────────────────────────
echo "Inference:"
_status "primary" "$PRIMARY_PID" "$PRIMARY_PORT"
_status_proxy

# ── Memory ────────────────────────────────────────────────────────────────────
echo ""
echo "Memory:"
vm_stat | awk '
  /Pages free/        { free=$3+0 }
  /Pages active/      { active=$3+0 }
  /Pages wired/       { wired=$4+0 }
  /Pages occupied/    { compressed=$5+0 }
  END {
    page=16384
    total_gb=48
    used_gb=((active+wired+compressed)*page/1073741824)
    free_gb=(free*page/1073741824)
    printf "  used: %.1f GB / %d GB  |  free: %.1f GB\n", used_gb, total_gb, free_gb
  }'
sysctl -n vm.swapusage 2>/dev/null | awk '{printf "  swap: %s\n", $0}'

# ── Models on disk ────────────────────────────────────────────────────────────
echo ""
echo "Models ($MODEL_DIR):"
if [[ -d "$MODEL_DIR" ]]; then
  for d in "$MODEL_DIR"/*/; do
    name=$(basename "$d")
    size=$(du -sh "$d" 2>/dev/null | cut -f1)
    printf "  %-48s %s\n" "$name" "$size"
  done
else
  echo "  (model dir not found: $MODEL_DIR)"
fi
