#!/usr/bin/env bash

codex_io_repo_root() {
  local script_dir
  script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
  if git -C "$script_dir" rev-parse --show-toplevel >/dev/null 2>&1; then
    git -C "$script_dir" rev-parse --show-toplevel
    return
  fi
  cd "$script_dir/../../.." && pwd
}

cio_init() {
  CIO_REPO_ROOT="${CIO_REPO_ROOT:-$(codex_io_repo_root)}"
  CIO_STATE_DIR="${CIO_STATE_DIR:-$CIO_REPO_ROOT/.tmp/codex-io-bridge}"
  CIO_TARGET="${CIO_TARGET:-codex-autopilot:0.0}"
  CIO_SESSION="${CIO_SESSION:-codex-io-bridge}"
  CIO_LOG="${CIO_LOG:-/tmp/codex-io-bridge.log}"
  CIO_HEARTBEAT_FILE="$CIO_STATE_DIR/bridge.heartbeat"
  CIO_PROGRESS_FILE="$CIO_STATE_DIR/progress.env"
  mkdir -p "$CIO_STATE_DIR"
}

cio_quote() {
  printf '%q' "$1"
}

cio_now() {
  date +%s
}

cio_touch_heartbeat() {
  cio_now > "$CIO_HEARTBEAT_FILE"
}

cio_write_progress() {
  local state="$1"
  local question_id="${2:-}"
  local message="${3:-}"
  {
    printf 'state=%s\n' "$(cio_quote "$state")"
    printf 'current_question_id=%s\n' "$(cio_quote "$question_id")"
    printf 'message=%s\n' "$(cio_quote "$message")"
    printf 'last_progress_at=%s\n' "$(cio_now)"
  } > "$CIO_PROGRESS_FILE"
}

cio_tmux_has_target() {
  tmux display-message -p -t "$CIO_TARGET" '#{pane_id}' >/dev/null 2>&1
}

cio_capture() {
  tmux capture-pane -t "$CIO_TARGET" -p -S -40
}

cio_prompt_text() {
  local text="$1"
  printf '%s\n' "$text" |
    awk '
      NF { lines[++count] = $0 }
      END {
        start = count > 12 ? count - 11 : 1
        for (i = start; i <= count; i++) print lines[i]
      }
    '
}

cio_detect_prompt() {
  local text="$1"
  # Do not mirror the bridge/Q&A prompt that was itself injected into the
  # Codex pane; otherwise resolving a stale bridge question can create an
  # endless freeform-question loop.
  if printf '%s\n' "$text" | grep -Eq '(Reply options:|Operator question: Codex is waiting for input)'; then
    return 1
  fi

  # Only mirror the active Codex input line. Scanning the whole pane is too
  # noisy because source diffs, logs, and previous Telegram prompts often
  # contain words like "question", "approve", or "continue".
  local active_line
  active_line="$(
    printf '%s\n' "$text" |
      awk '/^› / { line = $0 } END { print line }'
  )"
  if [[ -n "$active_line" ]] && printf '%s\n' "$active_line" | grep -Eiq '([?]|approval|approve|permission|continue|yes/no|y/n|enter your|provide|confirm)'; then
    cio_prompt_text "$text"
    return 0
  fi
  return 1
}

cio_hash() {
  cksum | awk '{ print $1 }'
}
