#!/usr/bin/env bash
# cogitod-managed-human-launch
set -uo pipefail

HARNESS="$1"; REAL="$2"; shift 2
LIBEXEC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

direct() { exec "$REAL" "$@"; }
# Opt-in only: tmux terminal-presence is an experimental wrap. The render path
# below sizes the session to the terminal and drops the status bar so an
# interactive TUI is not reflowed on attach, but the default stays a direct launch.
[ "${COGITOD_TERMINAL_PRESENCE:-}" = 1 ] || direct "$@"
[ "${COGITOD_LAUNCH_MODE:-}" = direct ] && direct "$@"
[ "${COGITOD_HARNESS_WRAPPED:-}" = 1 ] && direct "$@"
[ -n "${TMUX:-}" ] && direct "$@"
[ -t 0 ] && [ -t 1 ] || direct "$@"
command -v tmux >/dev/null 2>&1 || direct "$@"

# shellcheck source=../lib/breathe-port.sh
. "$LIBEXEC/breathe-port.sh"
ENDPOINT="${BREATHE_MCP_ENDPOINT:-http://127.0.0.1:${BREATHE_PORT}}"
curl -fsS --max-time 0.35 "$ENDPOINT/health" >/dev/null 2>&1 || direct "$@"

enc() {
  printf %s "$1" | sed \
    -e 's/%/%25/g' -e 's/ /%20/g' -e 's/&/%26/g' -e 's/+/%2B/g' \
    -e 's/#/%23/g' -e 's/?/%3F/g' -e 's/=/%3D/g'
}
lifecycle() {
  local action="$1"
  if [ -z "${PANE:-}" ]; then
    [ "$action" != start ]
    return
  fi
  local response
  response="$(curl -fsS --max-time 0.5 -X POST \
    "$ENDPOINT/v1/hook/terminal-presence?harness=$(enc "$HARNESS")&ppid=$$&tmux=$(enc "$PANE")&cwd=$(enc "$PWD")" \
    -H 'Content-Type: application/json' \
    --data-binary "{\"action\":\"$action\",\"launch_id\":\"$LAUNCH_ID\"}" 2>/dev/null)" || return 1
  [ "$action" != start ] || printf '%s' "$response" | grep -q '"registered":true'
}

STATE="${TMPDIR:-/tmp}/cogitod-harness-${UID:-0}-$$"
STATUS="$STATE/status"
GATE="$STATE/start-registered"
LAUNCH_ID="$(od -An -N16 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')"
if [[ ! "$LAUNCH_ID" =~ ^[0-9a-f]{32}$ ]]; then
  LAUNCH_ID="$(printf '%08x%08x%08x%08x' "$$" "${RANDOM:-0}" "$(date +%s)" "${UID:-0}")"
fi
SESSION="cogitod-${HARNESS}-${LAUNCH_ID:0:12}"
# Birth the session at the real terminal size so `attach` does not reflow the pane
# and corrupt an interactive TUI's differential redraw. Without -x/-y the session is
# born 80x24 and resized on attach.
SIZE_OPTS=()
TERM_SIZE="$(stty size 2>/dev/null </dev/tty || stty size 2>/dev/null || true)"
TERM_LINES="${TERM_SIZE%% *}"; TERM_COLS="${TERM_SIZE##* }"
if [[ "$TERM_COLS" =~ ^[0-9]+$ ]] && [[ "$TERM_LINES" =~ ^[0-9]+$ ]] \
  && [ "$TERM_COLS" -gt 0 ] && [ "$TERM_LINES" -gt 0 ]; then
  SIZE_OPTS=(-x "$TERM_COLS" -y "$TERM_LINES")
fi
(umask 077 && mkdir "$STATE") || direct "$@"
COGITOD_HARNESS_WRAPPED=1 tmux new-session -d ${SIZE_OPTS[@]+"${SIZE_OPTS[@]}"} \
  -e COGITOD_HARNESS_WRAPPED=1 -e "COGITOD_LAUNCH_ID=$LAUNCH_ID" -s "$SESSION" \
  "$LIBEXEC/cogito-harness-runner.sh" "$STATUS" "$GATE" "$ENDPOINT" \
  "$HARNESS" "$$" "$PWD" "$REAL" "$@" || {
    rm -rf "$STATE"
    direct "$@"
  }
# Drop the status bar before the runner draws (it blocks on $GATE): a status row
# steals a line and forces the TUI to reflow when the bar toggles on attach.
tmux set-option -t "$SESSION" status off 2>/dev/null || true
PANE="$(tmux display-message -p -t "$SESSION:0.0" '#{pane_id}' 2>/dev/null || true)"
lifecycle start || true
: > "$GATE"
tmux attach-session -t "$SESSION"
TMUX_RC=$?
PANE_DEAD="$(tmux display-message -p -t "$PANE" '#{pane_dead}' 2>/dev/null || echo gone)"
if [ "$PANE_DEAD" = 0 ]; then
  exit "$TMUX_RC"
fi
[ -r "$STATUS" ] || lifecycle stop
RC=125
if [ -r "$STATUS" ]; then
  read -r RC < "$STATUS" || RC="$TMUX_RC"
elif [ "$TMUX_RC" -ne 0 ]; then
  RC="$TMUX_RC"
fi
rm -rf "$STATE"
case "$RC" in ''|*[!0-9]*) exit "$TMUX_RC" ;; *) exit "$RC" ;; esac
