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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=ai/tools/codex-io-bridge/lib.sh
source "$script_dir/lib.sh"
cio_init

once=false
no_telegram=false
mirror_prompts=false
timeout=""
interval="${CIO_INTERVAL_SECONDS:-2}"

while (($# > 0)); do
  case "$1" in
    --target) CIO_TARGET="${2:?}"; shift 2 ;;
    --once) once=true; shift ;;
    --no-telegram) no_telegram=true; shift ;;
    --mirror-prompts) mirror_prompts=true; shift ;;
    --timeout) timeout="${2:?}"; shift 2 ;;
    -h | --help)
      cat <<'EOF'
Usage:
  ai/tools/codex-io-bridge/watch.sh [--target codex-autopilot:0.0] [--once] [--mirror-prompts] [--no-telegram] [--timeout seconds]

Observes a Codex tmux pane and writes heartbeat/progress state. Prompt
mirroring is deprecated; --mirror-prompts now records detected Codex pane text
as non-actionable internal context and never creates operator questions.
Approved-action execution is handled by ai/tools/approved-action-dispatcher,
not by this bridge.
EOF
      exit 0
      ;;
    *) echo "codex io watch error: unknown argument: $1" >&2; exit 2 ;;
  esac
done

cio_init
[[ -z "$timeout" || "$timeout" =~ ^[0-9]+$ ]] || {
  echo "codex io watch error: --timeout must be seconds" >&2
  exit 2
}

if ! command -v tmux >/dev/null 2>&1; then
  echo "codex io watch error: tmux is required" >&2
  exit 1
fi
if ! cio_tmux_has_target; then
  echo "codex io watch error: tmux target unavailable: $CIO_TARGET" >&2
  exit 1
fi

last_hash_file="$CIO_STATE_DIR/last-prompt.hash"
cio_touch_heartbeat
cio_write_progress "started" "" "watching $CIO_TARGET"

while true; do
  cio_touch_heartbeat
  cio_write_progress "observing" "" "observing $CIO_TARGET"
  if [[ "$mirror_prompts" != "true" ]]; then
    [[ "$once" == "true" ]] && {
      printf 'Codex I/O bridge observed %s; prompt mirroring disabled.\n' "$CIO_TARGET"
      exit 0
    }
    sleep "$interval"
    continue
  fi
  capture="$(cio_capture)"
  if prompt="$(cio_detect_prompt "$capture")"; then
    hash="$(printf '%s' "$prompt" | cio_hash)"
    previous="$(cat "$last_hash_file" 2>/dev/null || true)"
    if [[ "$hash" != "$previous" ]]; then
      printf '%s\n' "$hash" > "$last_hash_file"
      cio_write_progress "codex_internal_context" "" "detected non-actionable Codex pane context"
      printf 'Codex I/O bridge detected non-actionable internal context in %s; no operator question created.\n' "$CIO_TARGET"
      [[ "$once" == "true" ]] && exit 0
    elif [[ "$once" == "true" ]]; then
      cio_write_progress "duplicate_prompt" "" "duplicate prompt ignored"
      printf 'Duplicate prompt ignored for %s\n' "$CIO_TARGET"
      exit 0
    fi
  elif [[ "$once" == "true" ]]; then
    cio_write_progress "no_prompt" "" "no interactive prompt detected"
    printf 'No interactive prompt detected for %s\n' "$CIO_TARGET"
    exit 1
  else
    cio_write_progress "idle" "" "no interactive prompt detected"
  fi
  sleep "$interval"
done
