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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$script_dir/../../.." && pwd)"

dry_run=false
json=false

usage() {
  cat <<'EOF'
Usage:
  ai/tools/operator-questions/resolve-stale-approved-actions.sh [--dry-run] [--json]

Marks stale, non-executed approved-action intents as resolved_stale with audit
evidence. Executed, denied, ignored, and already-resolved records are left
untouched. This never executes actions and never deletes state.
EOF
}

while (($# > 0)); do
  case "$1" in
    --dry-run) dry_run=true; shift ;;
    --json) json=true; shift ;;
    -h | --help) usage; exit 0 ;;
    *) echo "resolve stale approved actions error: unknown argument: $1" >&2; exit 2 ;;
  esac
done

approved_json="$(OQ_SKIP_CONSUME_PENDING=true "$script_dir/list-approved-actions.sh" --json --all)"
selection="$(node -e '
const data = JSON.parse(process.argv[1] || "{}");
const inactive = new Set(["executed", "resolved_stale", "ignored", "superseded", "invalid"]);
const stale = (data.actions || []).filter((item) => item.stale && !inactive.has(item.execution_status || ""));
console.log(JSON.stringify(stale));
' "$approved_json")"

if [[ "$dry_run" == "true" ]]; then
  if [[ "$json" == "true" ]]; then
    node -e 'const items = JSON.parse(process.argv[1] || "[]"); console.log(JSON.stringify({dry_run:true,count:items.length,items}, null, 2));' "$selection"
  else
    node -e 'const items = JSON.parse(process.argv[1] || "[]"); console.log(`Stale approved actions: ${items.length}`); for (const item of items) console.log(`${item.question_id} ${item.action} ${(item.stale_reasons || []).join(",")}`);' "$selection"
  fi
  exit 0
fi

resolved=0
while IFS=$'\037' read -r question_id action reasons; do
  [[ -n "$question_id" ]] || continue
  "$script_dir/resolve-approved-action.sh" \
    --question-id "$question_id" \
    --status resolved_stale \
    --reason "stale approval resolved by cleanup: ${reasons:-unknown}" >/dev/null
  "$repo_root/ai/tools/action-timeline/append.sh" \
    --type approved_action_blocked \
    --status blocked \
    --question-id "$question_id" \
    --action "$action" \
    --message "stale approval resolved by cleanup: ${reasons:-unknown}" >/dev/null
  resolved=$((resolved + 1))
done < <(node - "$selection" <<'NODE'
const items = JSON.parse(process.argv[2] || '[]');
for (const item of items) {
  console.log([item.question_id || '', item.action || '', (item.stale_reasons || []).join(',')].join('\x1f'));
}
NODE
)

if [[ "$json" == "true" ]]; then
  printf '{"resolved_count":%s}\n' "$resolved"
else
  printf 'Resolved stale approved actions: %s\n' "$resolved"
fi
