#!/bin/bash
set -euo pipefail

: "${SYNAPSE_URL:?SYNAPSE_URL is required}"
: "${SYNAPSE_API_KEY:?SYNAPSE_API_KEY is required}"

SOURCE="${SYNAPSE_DEFAULT_SOURCE:-gnexus-book}"
SUBJECT="${1:-Gnexus Book alert}"
ACTION="${2:-alert}"
TEXT="${3:-}"
PRIORITY="${4:-high}"
ENDPOINT="${SYNAPSE_URL%/}/api/v1/events"

BODY="$(python3 - "$SOURCE" "$SUBJECT" "$ACTION" "$TEXT" "$PRIORITY" <<'PY'
import json
import sys

source, subject, action, text, priority = sys.argv[1:6]
print(
    json.dumps(
        {
            "source": source,
            "subject": subject,
            "action": action,
            "priority": priority,
            "payload": {"service": "gnexus-book", "text": text},
            "dedup_key": f"gnexus-book:{action}:{subject}",
            "ttl_seconds": 3600,
        },
        ensure_ascii=False,
    )
)
PY
)"

curl -fsS --max-time 10 \
  -X POST "$ENDPOINT" \
  -H "Authorization: Bearer $SYNAPSE_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary "$BODY" >/dev/null
