#!/usr/bin/env bash
# PM relay helper — absolute-path wrapper around call.py so it can be invoked
# from ANY working directory with no `cd` and no JSON-quoting by hand.
#
# Usage:
#   tools/relay/pm read                      # drain PM inbox
#   tools/relay/pm pending                   # pending counts for all roles
#   tools/relay/pm send <to> <kind> <body>   # post_message from pm
#       e.g. tools/relay/pm send dev-c directive "## DIRECTIVE ... "
#
# Always works regardless of cwd because it resolves call.py by absolute path.
set -euo pipefail

RELAY_DIR="/home/alee/Sources/relicario/tools/relay"
CALL="python3 $RELAY_DIR/call.py"

cmd="${1:-}"
case "$cmd" in
  read)
    $CALL read_messages '{"for":"pm"}'
    ;;
  pending)
    for r in dev-a dev-b dev-c pm; do
      printf '%s: ' "$r"
      $CALL list_pending "{\"for\":\"$r\"}"
      echo
    done
    ;;
  send)
    to="${2:?usage: pm send <to> <kind> <body>}"
    kind="${3:?usage: pm send <to> <kind> <body>}"
    body="${4:?usage: pm send <to> <kind> <body>}"
    # Build JSON with python to handle escaping of the body safely.
    python3 - "$to" "$kind" "$body" <<'PY'
import json, sys, urllib.request
to, kind, body = sys.argv[1], sys.argv[2], sys.argv[3]
payload = {"from": "pm", "to": to, "kind": kind, "body": body}
import subprocess
print(subprocess.run(
    ["python3", "/home/alee/Sources/relicario/tools/relay/call.py",
     "post_message", json.dumps(payload)],
    capture_output=True, text=True).stdout, end="")
PY
    ;;
  *)
    echo "usage: pm {read|pending|send <to> <kind> <body>}" >&2
    exit 2
    ;;
esac
