#!/usr/bin/env bash
# fj-api <agent> <METHOD> <path> [json-body]
#
# Authenticated Forgejo REST call AS a pipeline agent (their own token).
#   fj-api sculptor GET /repos/miriam/motion-mesh/issues?limit=5
#   fj-api sculptor POST /repos/miriam/motion-mesh/issues/1/comments '{"body":"..."}'
set -euo pipefail
AGENT="${1:-}"; METHOD="${2:-GET}"; APIPATH="${3:-}"; BODY="${4:-}"
[ -n "$AGENT" ] && [ -n "$APIPATH" ] || { echo "usage: fj-api <agent> <METHOD> <path> [json]" >&2; exit 2; }
CREDS="${FJ_AGENT_CREDENTIALS:-$HOME/.pi/agent/fj-agent-credentials.json}"
[ -f "$CREDS" ] || { echo "fj-api: $CREDS not found" >&2; exit 1; }
TOKEN="$(python3 - "$AGENT" "$CREDS" <<'PY'
import json, sys, os
d = json.load(open(os.path.expanduser(sys.argv[2])))
a = sys.argv[1]
print((d.get(a) or d.get("mm-agent-" + a) or {}).get("token", ""))
PY
)"
[ -n "$TOKEN" ] || { echo "fj-api: no token for $AGENT" >&2; exit 2; }
API="https://git.miri.work/api/v1"
if [ -n "$BODY" ]; then
  exec curl -s -X "$METHOD" -H "Authorization: token $TOKEN" -H "Content-Type: application/json" -d "$BODY" "$API$APIPATH"
else
  exec curl -s -X "$METHOD" -H "Authorization: token $TOKEN" "$API$APIPATH"
fi
