#!/usr/bin/env bash
set -euo pipefail

AMQ_BIN="${AMQ_BIN:-/opt/homebrew/bin/amq}"
DEMO_OWNED=0
if [[ -n "${PI_AMQ_DEMO_DIR:-}" ]]; then
  DEMO_DIR="${PI_AMQ_DEMO_DIR}"
else
  DEMO_DIR="$(mktemp -d "${TMPDIR:-/tmp}/pi-amq-demo.XXXXXX")"
  DEMO_OWNED=1
fi
DEMO_ROOT="${DEMO_DIR}/mail"

amq_demo() {
  env \
    -u AM_ROOT -u AM_ROOT_ID -u AM_BASE_ROOT -u AM_BASE_ROOT_ID \
    -u AM_SESSION -u AM_ME \
    "${AMQ_BIN}" "$@"
}

json_id() {
  node -e 'let value=""; process.stdin.on("data", chunk => value += chunk); process.stdin.on("end", () => process.stdout.write(JSON.parse(value).id));'
}

mkdir -p "${DEMO_DIR}"
(
  cd "${DEMO_DIR}"
  amq_demo coop init --root "${DEMO_ROOT}" --agents terminal-a,terminal-b,user --no-gitignore --json >/dev/null
)

echo "demo_root=${DEMO_ROOT}"
echo "[terminal-a] publish status and send urgent/normal/low"
amq_demo presence set --root "${DEMO_ROOT}" --me terminal-a --status busy --note "sending demo cohort" --json
URGENT_ID="$(amq_demo send --root "${DEMO_ROOT}" --me terminal-a --to terminal-b --priority urgent --kind todo --subject urgent --body "urgent demo" --json | json_id)"
NORMAL_ID="$(amq_demo send --root "${DEMO_ROOT}" --me terminal-a --to terminal-b --priority normal --kind question --subject normal --body "normal demo question" --json | json_id)"
LOW_ID="$(amq_demo send --root "${DEMO_ROOT}" --me terminal-a --to terminal-b --priority low --kind status --subject low --body "low demo status" --json | json_id)"
printf 'sent urgent=%s normal=%s low=%s\n' "${URGENT_ID}" "${NORMAL_ID}" "${LOW_ID}"

echo "[terminal-b] inspect priority order, claim exact IDs, and reply"
amq_demo list --root "${DEMO_ROOT}" --me terminal-b --new --limit 10 --json
amq_demo read --root "${DEMO_ROOT}" --me terminal-b --id "${URGENT_ID}" --json
amq_demo read --root "${DEMO_ROOT}" --me terminal-b --id "${NORMAL_ID}" --json
amq_demo read --root "${DEMO_ROOT}" --me terminal-b --id "${LOW_ID}" --json
REPLY_ID="$(amq_demo reply --root "${DEMO_ROOT}" --me terminal-b --id "${NORMAL_ID}" --kind answer --body "normal demo answer" --json | json_id)"
printf 'reply=%s\n' "${REPLY_ID}"
amq_demo presence set --root "${DEMO_ROOT}" --me terminal-b --status idle --note "demo cohort drained" --json

echo "[terminal-a] claim reply, inspect receipts, and list status"
amq_demo read --root "${DEMO_ROOT}" --me terminal-a --id "${REPLY_ID}" --json
amq_demo receipts list --root "${DEMO_ROOT}" --me terminal-b --msg-id "${URGENT_ID}" --json
amq_demo receipts list --root "${DEMO_ROOT}" --me terminal-b --msg-id "${NORMAL_ID}" --json
amq_demo receipts list --root "${DEMO_ROOT}" --me terminal-a --msg-id "${REPLY_ID}" --json
amq_demo presence list --root "${DEMO_ROOT}" --me terminal-a --json

if [[ "${DEMO_OWNED}" == "1" && "${KEEP_DEMO:-0}" != "1" ]]; then
  rm -rf -- "${DEMO_DIR}"
else
  echo "kept_demo_dir=${DEMO_DIR}"
fi
