#!/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}"

if [[ ! -s "$SESSION_ID_FILE" ]]; then
  echo "[kill] missing pinned session id file: $SESSION_ID_FILE"
  exit 0
fi

SESSION_ID="$(tr -d '[:space:]' < "$SESSION_ID_FILE")"
if [[ -z "$SESSION_ID" ]]; then
  echo "[kill] empty pinned session id in: $SESSION_ID_FILE"
  exit 0
fi

# Best-effort cleanup for the pinned supervisor session only. Do not kill
# unrelated interactive Codex sessions.
exclude='codex_kill_active_processes\.sh|codex_active_process\.sh|codex_event_control_room\.sh|codex_autorun_nogit\.sh|run_tmux_supervised\.sh|grep |rg '

mapfile -t pids < <(
  ps -eo pid=,cmd= 2>/dev/null \
    | grep -F "$SESSION_ID" \
    | grep -v -E "$exclude" \
    | awk '{print $1}' \
    | sort -u
)

if [[ "${#pids[@]}" -eq 0 ]]; then
  echo "[kill] no active Codex processes found"
  exit 0
fi

echo "[kill] sending TERM to active Codex PIDs: ${pids[*]}"
kill "${pids[@]}" 2>/dev/null || true
sleep 2

mapfile -t remaining < <(
  ps -eo pid=,cmd= 2>/dev/null \
    | grep -F "$SESSION_ID" \
    | grep -v -E "$exclude" \
    | awk '{print $1}' \
    | sort -u
)

if [[ "${#remaining[@]}" -gt 0 ]]; then
  echo "[kill] sending KILL to remaining Codex PIDs: ${remaining[*]}"
  kill -9 "${remaining[@]}" 2>/dev/null || true
fi

exit 0
