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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../../.." && pwd)"
# shellcheck source=ai/tools/operator-questions/lib.sh
source "$script_dir/lib.sh"
oq_init
if [[ "${OQ_SKIP_CONSUME_PENDING:-false}" != "true" ]]; then
  oq_consume_all_pending_telegram_decisions
fi

format="text"
include_all=false
while (($# > 0)); do
  case "$1" in
    --json) format="json"; shift ;;
    --all) include_all=true; shift ;;
    -h | --help)
      echo "Usage: ai/tools/operator-questions/list-approved-actions.sh [--json] [--all]"
      exit 0
      ;;
    *) echo "list approved actions error: unknown argument: $1" >&2; exit 2 ;;
  esac
done

(
  cd "$repo_root/ai/runtime"
  ../../node_modules/.bin/tsc -p tsconfig.json >/dev/null
)

args=(approved-actions --json)
if [[ "$include_all" == "true" ]]; then
  args+=(--all)
fi
json="$(
  OQ_REPO_ROOT="$OQ_REPO_ROOT" \
  OQ_STATE_DIR="$OQ_STATE_DIR" \
  node "$repo_root/ai/runtime/dist/cli.js" "${args[@]}"
)"

if [[ "$format" == "json" ]]; then
  printf '%s\n' "$json"
  exit 0
fi

node - "$json" "$include_all" <<'NODE'
const data = JSON.parse(process.argv[2]);
const includeAll = process.argv[3] === 'true';
console.log('Approved Operator Actions');
console.log(`State dir: ${data.state_dir}`);
console.log('');
const visibleActions = includeAll ? data.actions : data.actions.filter((item) => !item.stale);
if (visibleActions.length === 0) {
  console.log('No approved actions found.');
} else {
  console.log('Approved but not executed actions require dispatcher evaluation. Stale approvals are hidden by default; use --all for audit.');
  console.log('ID        Action        Status         Stale  Target');
  for (const item of visibleActions) {
    console.log(`${item.question_id.padEnd(8)}  ${item.action.padEnd(12)}  ${item.execution_status.padEnd(13)}  ${String(item.stale).padEnd(5)}  ${item.target_chunks}`);
  }
}
NODE
