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

RUNTIME_DIR="${JARVIS_FINANCE_RUNTIME_DIR:-$HOME/jarvis_runtime/finance-system}"
LOG_DIR="$RUNTIME_DIR/logs"
BACKEND_PID_FILE="$LOG_DIR/finance_backend.pid"
FRONTEND_PID_FILE="$LOG_DIR/finance_frontend.pid"
BACKEND_PORT="${BACKEND_PORT:-8000}"
FRONTEND_PORT="${FRONTEND_PORT:-5173}"

stop_pid_file() {
  local label="$1"
  local pid_file="$2"
  if [[ ! -f "$pid_file" ]]; then
    echo "$label: no PID file ($pid_file)"
    return 0
  fi
  local pid
  pid="$(tr -cd '0-9' < "$pid_file" || true)"
  if [[ -z "$pid" ]]; then
    echo "$label: invalid PID file, removing"
    rm -f "$pid_file"
    return 0
  fi
  if kill -0 "$pid" 2>/dev/null; then
    echo "Stopping $label PID $pid"
    kill "$pid" 2>/dev/null || true
    for _ in $(seq 1 30); do
      if ! kill -0 "$pid" 2>/dev/null; then
        break
      fi
      sleep 0.2
    done
    if kill -0 "$pid" 2>/dev/null; then
      echo "$label did not stop gracefully; sending KILL" >&2
      kill -9 "$pid" 2>/dev/null || true
    fi
  else
    echo "$label: PID $pid is not running"
  fi
  rm -f "$pid_file"
}

stop_port() {
  local label="$1"
  local port="$2"
  if ! command -v fuser >/dev/null 2>&1; then
    return 0
  fi
  local pids
  pids="$(fuser -n tcp "$port" 2>/dev/null || true)"
  if [[ -z "$pids" ]]; then
    echo "$label port $port: free"
    return 0
  fi
  echo "Stopping stale $label listener(s) on port $port"
  kill $pids 2>/dev/null || true
  sleep 1
  pids="$(fuser -n tcp "$port" 2>/dev/null || true)"
  if [[ -n "$pids" ]]; then
    echo "Killing stale $label listener(s) on port $port" >&2
    kill -9 $pids 2>/dev/null || true
  fi
}

mkdir -p "$LOG_DIR"
stop_pid_file "FastAPI backend" "$BACKEND_PID_FILE"
stop_pid_file "Vue frontend" "$FRONTEND_PID_FILE"
stop_port "FastAPI backend" "$BACKEND_PORT"
stop_port "Vue frontend" "$FRONTEND_PORT"
echo "Dashboard stop complete."
