#!/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"
log_file="$state_dir/runtime-api.log"
socket_path="${AI_RUNTIME_SOCKET:-$state_dir/runtime.sock}"
tmux_session="${AI_RUNTIME_TMUX_SESSION:-blueprint-runtime-api}"

mkdir -p "$state_dir"

if command -v tmux >/dev/null 2>&1 && tmux has-session -t "$tmux_session" 2>/dev/null; then
  printf 'Runtime API daemon already running: session=%s socket=%s\n' "$tmux_session" "$socket_path"
  exit 0
fi

if [[ -f "$pid_file" ]] && kill -0 "$(cat "$pid_file")" 2>/dev/null; then
  pid="$(cat "$pid_file")"
  stat="$(ps -p "$pid" -o stat= 2>/dev/null || true)"
  if [[ "$stat" != Z* ]]; then
    printf 'Runtime API daemon already running: pid=%s socket=%s\n' "$pid" "$socket_path"
    exit 0
  fi
fi

cd "$repo_root/ai/runtime"
node scripts/atomic-build.mjs >/dev/null

rm -f "$socket_path"

command_text="cd '$repo_root/ai/runtime' && OQ_REPO_ROOT='$repo_root' AI_RUNTIME_REPO_ROOT='$repo_root' AI_RUNTIME_SOCKET='$socket_path' AI_RUNTIME_STATE='$state_dir/status.json' AI_RUNTIME_HEARTBEAT='$state_dir/heartbeat' node dist/daemon/runtime-daemon.js >>'$log_file' 2>&1"

if command -v tmux >/dev/null 2>&1; then
  tmux new-session -d -s "$tmux_session" "$command_text"
  printf 'Runtime API daemon started: session=%s socket=%s\n' "$tmux_session" "$socket_path"
  exit 0
fi

setsid bash -lc "$command_text" >/dev/null 2>&1 &
pid="$!"
printf '%s\n' "$pid" > "$pid_file"
printf 'Runtime API daemon started: pid=%s socket=%s\n' "$pid" "$socket_path"
