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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=ai/tools/operator-questions/lib.sh
source "$script_dir/lib.sh"
oq_init

usage() {
  cat <<'EOF'
Usage:
  ai/tools/operator-questions/wait-answer.sh <question-id> [--timeout <seconds>]

Waits indefinitely by default. Tests may pass --timeout.
EOF
}

fail() {
  printf 'operator wait error: %s\n' "$1" >&2
  exit "${2:-1}"
}

[[ $# -ge 1 ]] || { usage >&2; exit 2; }
question_id="$1"
shift
timeout=""

while (($# > 0)); do
  case "$1" in
    --timeout) timeout="${2:?}"; [[ "$timeout" =~ ^[0-9]+$ ]] || fail "--timeout must be seconds" 2; shift 2 ;;
    -h | --help) usage; exit 0 ;;
    *) fail "unknown argument: $1" 2 ;;
  esac
done

question_path="$(oq_question_path "$question_id")"
answer_path="$(oq_answer_path "$question_id")"
resolved_path="$(oq_resolved_path "$question_id")"
[[ -f "$question_path" ]] || fail "question not found: $question_id"
oq_load_env "$question_path"

start="$(date +%s)"
while true; do
  if [[ -f "$answer_path" ]]; then
    cat "$answer_path"
    exit 0
  fi

  if [[ -f "$resolved_path" ]]; then
    reason=""
    status=""
    # shellcheck disable=SC1090
    source "$resolved_path"
    fail "question resolved before answer: $question_id status=${status:-resolved} reason=${reason:-unknown}" 3
  fi

  oq_consume_telegram_decision "$question_id" >/dev/null || true

  if [[ -n "$timeout" ]] && (( $(date +%s) - start >= timeout )); then
    fail "timed out waiting for operator answer: $question_id"
  fi
  sleep 1
done
