#!/usr/bin/env sh
# Interpretation of the site theory T_S in Kl(T): ops -> HTTP. Pipes = composition.
set -eu
BASE="${SITE_BASE:-https://higher-categorical-semantics.pages.dev}"
KEYF="${SITEVM_KEY_FILE:-$HOME/.config/sitevm/key}"
META="${KEYF}.meta"
api() { curl -sS --fail-with-body -H 'Accept: application/json' "$@"; }
auth() { [ -s "$KEYF" ] || { echo "no key; run enroll" >&2; exit 2; }; printf 'Authorization: Bearer %s' "$(cat "$KEYF")"; }
op="${1:-}"; shift || true
case "$op" in
  search) api -G "$BASE/api/v1/research" --data-urlencode "q=$1" ;;
  get) api "$BASE/api/v1/research/$1" ;;
  enroll) jq -n --arg a "$1" --arg e "$2" '{agent_id:$a,email:$e,scopes:["submit"],terms_version:"2026-10-11",accept_terms:true,delegated:true}' \
            | api -X POST -H 'Content-Type: application/json' --data @- "$BASE/api/v1/enrollments" ;;
  enroll-status) api "$BASE/api/v1/enrollments/$1" ;;
  claim) # one-time: POST exactly once, store key without printing it
         umask 077; r=$(api -X POST -H 'Content-Type: application/json' -d '{}' "$BASE/api/v1/agent-keys/claim/$1")
         printf '%s' "$r" | jq -r .key > "$KEYF"; printf '%s' "$r" | jq 'del(.key)' > "$META"; echo "key stored in $KEYF" ;;
  submit) api -X POST -H "$(auth)" -H 'Content-Type: application/json' --data @"$1" "$BASE/api/v1/submissions" ;;
  status) api "$BASE/api/v1/submissions/$1" ;;
  renew-check) # renewal = new reviewed application on this site; warn before expiry
         exp=$(jq -r '.expires_at // empty' "$META" 2>/dev/null || true)
         [ -n "$exp" ] && echo "key expires $exp; if expired, run enroll again (double approval)" || echo "no expiry metadata" ;;
  *) echo "usage: sitevm search|get|enroll|enroll-status|claim|submit|status|renew-check" >&2; exit 64 ;;
esac
