#!/usr/bin/env bash
# arq-operator-inbox — substrate-resident notification queue for the operator
#
# Twin (or any worker) emits arq://act/operator_notification_pending/<event>-<ts>
# acts. Operator runs this to list unseen ones; passing --mark-seen flips them
# to arq://act/operator_notification_acknowledged/<ref>-<ts> so they don't
# resurface.
#
# Usage:
#   arq-operator-inbox                  — list pending notifications
#   arq-operator-inbox --mark-seen <ref> — mark one acknowledged
#   arq-operator-inbox --mark-all-seen   — acknowledge everything pending
#
# Designed to be called at session-start so future Twin sessions surface
# any bg-emitted notifications that landed between sessions.

set -euo pipefail

CMD="${1:-list}"

case "$CMD" in
  list|"")
    pending=$(twin --use-keychain index --class act --type operator_notification_pending --limit 50 --json 2>/dev/null)
    if [ -z "$pending" ] || [ "$pending" = "[]" ]; then
      echo "No pending operator notifications."
      exit 0
    fi
    # Get list of acknowledged refs to filter out
    acked=$(twin --use-keychain index --class act --type operator_notification_acknowledged --limit 100 --json 2>/dev/null)
    python3 - <<PYEOF
import json, sys
pending = json.loads("""$pending""")
try:
    acked_list = json.loads("""$acked""") or []
    acked_refs = {a.get("ref","") for a in acked_list}
except: acked_refs = set()
unseen = [p for p in pending if p.get("ref","") not in acked_refs]
print(f"Pending notifications: {len(unseen)} (of {len(pending)} total · {len(acked_refs)} acknowledged)")
print()
for p in unseen[:20]:
    ref = p.get("ref","?")
    addr = p.get("address","?")
    issued = (p.get("issued_at") or "?")[:19]  # Sentry-flagged: None[:19] TypeError if key present but null
    print(f"  [{issued}] {ref}")
    print(f"    {addr}")
PYEOF
    ;;
  --mark-seen)
    REF="${2:?usage: arq-operator-inbox --mark-seen <ref>}"
    twin --use-keychain act emit \
      --payload "{\"acknowledged_ref\":\"$REF\",\"acknowledged_at\":\"$(date -u +%FT%TZ)\"}" \
      act operator_notification_acknowledged "$REF-$(date -u +%Y%m%dT%H%M%SZ)" 2>&1 | tail -2
    ;;
  --mark-all-seen)
    twin --use-keychain index --class act --type operator_notification_pending --limit 100 --json 2>/dev/null | \
      python3 -c "
import json, sys
for p in json.load(sys.stdin):
    print(p.get('ref',''))" | \
      _ack_failed=0
      _ack_total=0
      while read -r ref; do
        [ -z "$ref" ] && continue
        _ack_total=$((_ack_total + 1))
        # Sentry-flagged: silent 2>&1 swallows failures; capture exit + surface
        if ! twin --use-keychain act emit \
            --payload "{\"acknowledged_ref\":\"$ref\",\"acknowledged_at\":\"$(date -u +%FT%TZ)\",\"via\":\"mark-all-seen\"}" \
            act operator_notification_acknowledged "$ref-bulk-$(date -u +%Y%m%dT%H%M%SZ)" >/dev/null 2>&1; then
          _ack_failed=$((_ack_failed + 1))
          echo "  ack-failed: $ref" >&2
        fi
      done
    if [ "$_ack_failed" -gt 0 ]; then
      echo "Acknowledged $((_ack_total - _ack_failed)) / $_ack_total (${_ack_failed} failed — see stderr)."
      exit 1
    fi
    echo "All $_ack_total pending notifications acknowledged."
    ;;
  *)
    echo "Usage: arq-operator-inbox [list|--mark-seen <ref>|--mark-all-seen]" >&2
    exit 2
    ;;
esac
