#!/usr/bin/env bash
#
# Kill any lingering host-level dev servers (Next.js, Expo Metro, Convex CLI
# watchers, turbo orchestrators) that survived a Ctrl-C. Does not touch the
# dockerized Convex/Postgres stack — use `bun db:down` for that.
#
# Usage: scripts/dev-kill   (wired as `bun dev:kill`)
set -euo pipefail

info() { printf '\033[36m▶ %s\033[0m\n' "$*"; }
ok()   { printf '\033[32m✓ %s\033[0m\n' "$*"; }

PORTS=(3000 3001 8081 19000 19001 19002)
PATTERNS=('next-server' 'next dev' 'expo start' 'turbo run dev' 'convex dev')

killed=false

for port in "${PORTS[@]}"; do
  pids="$(lsof -ti "tcp:$port" -sTCP:LISTEN 2>/dev/null || true)"
  [ -z "$pids" ] && continue
  for pid in $pids; do
    cmd="$(ps -p "$pid" -o comm= 2>/dev/null || true)"
    info "Killing $cmd (pid $pid) on port $port"
    kill "$pid" 2>/dev/null || true
    killed=true
  done
done

for pattern in "${PATTERNS[@]}"; do
  pids="$(pgrep -f "$pattern" 2>/dev/null || true)"
  [ -z "$pids" ] && continue
  for pid in $pids; do
    info "Killing '$pattern' (pid $pid)"
    kill "$pid" 2>/dev/null || true
    killed=true
  done
done

if [ "$killed" = true ]; then
  sleep 1
  ok "Dev servers stopped."
else
  ok "No dev servers were running."
fi
