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

PROJECT_ROOT="${PROJECT_ROOT:-/home/happyuser/projects/DEX}"
SESSION_ID_FILE="${SESSION_ID_FILE:-$PROJECT_ROOT/.agent/codex_session_id}"
VERBOSE="${VERBOSE:-0}"

if [[ ! -s "$SESSION_ID_FILE" ]]; then
  exit 1
fi

SESSION_ID="$(tr -d '[:space:]' < "$SESSION_ID_FILE")"
if [[ -z "$SESSION_ID" ]]; then
  exit 1
fi

# Return 0 when the pinned supervisor Codex session appears to be active.
# This intentionally ignores unrelated interactive Codex sessions.
match="$(
  ps -eo pid=,cmd= 2>/dev/null \
    | grep -F "$SESSION_ID" \
    | grep -v -E 'codex_active_process\.sh|codex_event_control_room\.sh|codex_autorun_nogit\.sh|run_tmux_supervised\.sh|grep ' \
    || true
)"

if [[ -n "$match" ]]; then
  if [[ "$VERBOSE" == "1" ]]; then
    printf '%s\n' "$match"
  fi
  exit 0
fi

exit 1
