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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=./common.sh
source "$SCRIPT_DIR/common.sh"

ensure_repo_root

ORCH_URL="${ORCHESTRATOR_URL:-http://localhost:3001}"
API_KEY="${ORCHESTRATOR_API_KEY:-}"

usage() {
  cat <<USAGE
Usage: $(basename "$0") <recent|watch> [--limit N]

Commands:
  recent   Fetch recent orchestrator events (JSON)
  watch    Stream live orchestrator events (SSE)

Options:
  --limit N   Number of recent events to return (default: 50)

Environment:
  ORCHESTRATOR_URL      Orchestrator base URL (default: http://localhost:3001)
  ORCHESTRATOR_API_KEY  Required API key for orchestrator requests
USAGE
}

cmd="${1:-recent}"
if [[ $# -gt 0 ]]; then
  shift
fi

limit=50
while [[ $# -gt 0 ]]; do
  case "$1" in
    --limit)
      limit="${2:-50}"
      shift 2
      ;;
    *)
      echo "[agent-framework] unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

if [[ -z "$API_KEY" ]]; then
  echo "[agent-framework] ORCHESTRATOR_API_KEY is required" >&2
  exit 1
fi

case "$cmd" in
  recent)
    curl -fsSL \
      -H "X-API-Key: $API_KEY" \
      -H "Content-Type: application/json" \
      "$ORCH_URL/agents/events/recent?limit=$limit"
    ;;
  watch)
    curl -NfsSL \
      -H "X-API-Key: $API_KEY" \
      -H "Accept: text/event-stream" \
      "$ORCH_URL/agents/events"
    ;;
  *)
    usage
    exit 1
    ;;
esac
