#!/usr/bin/env bash
##
## relay-policy-plugin — strfry write-policy plugin
##
## strfry starts this script once and feeds it JSON lines on stdin (one per
## event). The script forwards each line to the relay-policy HTTP sidecar and
## echoes the sidecar's JSON decision to stdout. If the sidecar is unavailable
## the event is rejected with a safe fallback so the relay does not accept
## unapproved events during a transient outage.
##
## stdin  format: {"event":{...},"receivedAt":N,"sourceType":"...","sourceInfo":"..."}
## stdout format: {"id":"<event-id>","action":"accept|reject|shadowReject","msg":"..."}
##

RELAY_POLICY_URL="${RELAY_POLICY_URL:-http://relay-policy:3080/decide}"

while IFS= read -r line; do
  # Extract event id for the fallback response — pure bash, no external tools.
  event_id=$(printf '%s' "$line" \
    | grep -o '"id":"[^"]*"' \
    | head -1 \
    | sed 's/"id":"//; s/"//')

  decision=$(printf '%s' "$line" \
    | curl -sf --max-time 5 \
        -X POST "$RELAY_POLICY_URL" \
        -H "Content-Type: application/json" \
        --data-binary @- 2>/dev/null)

  if [[ -z "$decision" ]]; then
    printf '{"id":"%s","action":"reject","msg":"policy service unavailable"}\n' \
      "${event_id:-unknown}"
  else
    printf '%s\n' "$decision"
  fi
done
