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

json=false
dry_run=false
while (($# > 0)); do
  case "$1" in
    --json) json=true; shift ;;
    --dry-run) dry_run=true; shift ;;
    -h | --help)
      cat <<'EOF'
Usage:
  ai/tools/operator-questions/consume-pending.sh [--json] [--dry-run]

Consumes already-recorded Telegram decisions into canonical operator-question
answers. Safe to run repeatedly; accepted or duplicate decisions are ignored.
EOF
      exit 0
      ;;
    *) echo "consume pending error: unknown argument: $1" >&2; exit 2 ;;
  esac
done

consumed=()
skipped=0
while IFS=$'\t' read -r question_id telegram_token _decision_path; do
  [[ -n "$question_id" ]] || continue
  if [[ "$dry_run" == "true" ]]; then
    consumed+=("$question_id:$telegram_token")
  elif oq_consume_telegram_decision "$question_id" >/dev/null; then
    consumed+=("$question_id:$telegram_token")
  else
    skipped=$((skipped + 1))
  fi
done < <(oq_unconsumed_telegram_decisions)

if [[ "$json" == "true" ]]; then
  printf '{"dry_run":%s,"consumable_count":%s,"skipped_count":%s,"consumable":[' "$dry_run" "${#consumed[@]}" "$skipped"
  for i in "${!consumed[@]}"; do
    IFS=: read -r qid token <<< "${consumed[$i]}"
    [[ "$i" == "0" ]] || printf ','
    printf '{"question_id":"%s","telegram_token":"%s"}' "$qid" "$token"
  done
  printf ']}\n'
  exit 0
fi

if [[ "$dry_run" == "true" ]]; then
  printf 'Consumable Telegram decisions: %s\n' "${#consumed[@]}"
else
  printf 'Consumed Telegram decisions: %s\n' "${#consumed[@]}"
fi
for item in "${consumed[@]}"; do
  IFS=: read -r qid token <<< "$item"
  printf '%s\n' "- $qid from Telegram token $token"
done
[[ "$skipped" == "0" ]] || printf 'Skipped invalid decisions: %s\n' "$skipped"
