#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
BACKEND_DIR="$ROOT_DIR/haixun-backend"
RUN_DIR="$BACKEND_DIR/.run"
COMPOSE_FILE="$BACKEND_DIR/deploy/docker-compose.yml"

stop_pid_file() {
  local name="$1"
  local file="$RUN_DIR/${name}.pid"
  if [[ ! -f "$file" ]]; then
    return 0
  fi
  local pid
  pid="$(cat "$file" 2>/dev/null || true)"
  if [[ -n "${pid:-}" ]] && kill -0 "$pid" 2>/dev/null; then
    echo "[stop-all] stopping $name (pid=$pid)"
    kill "$pid" 2>/dev/null || true
    for _ in $(seq 1 10); do
      kill -0 "$pid" 2>/dev/null || break
      sleep 0.2
    done
    kill -9 "$pid" 2>/dev/null || true
  fi
  rm -f "$file"
}

echo "[stop-all] stopping tracked processes..."
for name in worker web api; do
  stop_pid_file "$name"
done

echo "[stop-all] stopping stray processes..."
pkill -f "haixun-backend/worker/style-8d-worker" 2>/dev/null || true
pkill -f "worker:style-8d" 2>/dev/null || true
pkill -f "haixun-backend/web/node_modules/.bin/vite" 2>/dev/null || true
pkill -f "go run ./gateway.go -f etc/gateway.yaml" 2>/dev/null || true
# `go run` spawns a compiled binary child under the go-build cache (e.g.
# ~/Library/Caches/go-build/.../gateway) that is NOT killed when the parent
# wrapper dies; kill the orphan too so it stops serving stale routes on the API
# port and frees the port for the freshly built binary.
pkill -f "/gateway -f etc/gateway.yaml" 2>/dev/null || true
pkill -f "dev-with-style-8d.sh" 2>/dev/null || true

if command -v docker >/dev/null 2>&1 && [[ -f "$COMPOSE_FILE" ]]; then
  echo "[stop-all] stopping docker compose (mongo + redis)..."
  docker compose -f "$COMPOSE_FILE" down >/dev/null 2>&1 || true
fi

echo "[stop-all] done"