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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
state_dir="${AI_RUNTIME_STATE_DIR:-$repo_root/.tmp/runtime-api}"
pid_file="$state_dir/pid"
socket_path="${AI_RUNTIME_SOCKET:-$state_dir/runtime.sock}"
tmux_session="${AI_RUNTIME_TMUX_SESSION:-blueprint-runtime-api}"

stopped=false
if command -v tmux >/dev/null 2>&1 && tmux has-session -t "$tmux_session" 2>/dev/null; then
  tmux kill-session -t "$tmux_session"
  stopped=true
fi

if [[ -f "$pid_file" ]]; then
  pid="$(cat "$pid_file")"
  if kill -0 "$pid" 2>/dev/null; then
    kill "$pid"
    for _ in $(seq 1 30); do
      if ! kill -0 "$pid" 2>/dev/null; then
        break
      fi
      sleep 0.1
    done
    stopped=true
  fi
fi
rm -f "$pid_file" "$socket_path"
if [[ "$stopped" == true ]]; then
  printf 'Runtime API daemon stopped.\n'
else
  printf 'Runtime API daemon not running.\n'
fi
