#!/usr/bin/env bash
# tail-logs.sh — follow the audit log feed, polling every 5s.
# Stops on Ctrl-C.
#
# Usage:
#   AIRONCLAW_TOKEN=... ./tail-logs.sh [event_type]

set -euo pipefail

EVENT_TYPE="${1:-}"
BASE="${AIRONCLAW_BASE_URL:-https://dashboard.aironclaw.com}"
TOKEN="${AIRONCLAW_TOKEN:?AIRONCLAW_TOKEN must be set}"

LAST_TS=$(date +%s)

while true; do
  Q="from=${LAST_TS}&limit=50"
  [[ -n "$EVENT_TYPE" ]] && Q="${Q}&event_type=${EVENT_TYPE}"
  curl -fsS -H "Authorization: Bearer ${TOKEN}" \
    "${BASE}/api/logs?${Q}" | \
    jq -r '.logs[] |
      [.timestamp, .event_type, (.client_ip // "-"), (.tool // .model // "-"), (.rule_name // "")] |
      @tsv'
  LAST_TS=$(date +%s)
  sleep 5
done
