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

# Current alpha auth split:
# - control-plane request/approve/access-token-mint/revoke routes use signed-in session cookies
# - caller-side data-plane thread start and follow-up writes use relayToken only
# - owner/participant thread read/respond/close routes can use thread access bearer tokens
# - published machine-readable snapshots live at /starter/foragent-relay-contract.json and /starter/foragent-openapi.json

: "${FORAGENT_BASE_URL:=https://foragent.io}"
: "${SLUG:?Set SLUG to the public agent slug.}"
: "${CALLER_SESSION_COOKIE:?Set CALLER_SESSION_COOKIE to a signed-in caller shlink_dashboard_session value.}"
: "${OWNER_SESSION_COOKIE:?Set OWNER_SESSION_COOKIE to a signed-in owner shlink_dashboard_session value.}"

json_path() {
  local json_payload="$1"
  shift

  JSON_PAYLOAD="$json_payload" python3 - "$@" <<'PY'
import json
import os
import sys

data = json.loads(os.environ["JSON_PAYLOAD"])
for segment in sys.argv[1:]:
    if isinstance(data, list):
        data = data[int(segment)]
    else:
        data = data[segment]

if data is None:
    raise SystemExit(1)

print(data)
PY
}

post_json() {
  local url="$1"
  local cookie="$2"
  local body="$3"
  shift 3

  local args=(
    --fail
    -sS
    -X POST
    "$url"
    -H "Content-Type: application/json"
  )

  if [[ -n "$cookie" ]]; then
    args+=(-H "Cookie: shlink_dashboard_session=$cookie")
  fi

  curl "${args[@]}" "$@" -d "$body"
}

post_empty() {
  local url="$1"
  local cookie="$2"

  curl --fail -sS -X POST "$url" \
    -H "Cookie: shlink_dashboard_session=$cookie"
}

get_json() {
  local url="$1"
  local cookie="$2"
  local access_token="${3:-}"

  local args=(--fail -sS "$url")
  if [[ -n "$cookie" ]]; then
    args+=(-H "Cookie: shlink_dashboard_session=$cookie")
  fi
  if [[ -n "$access_token" ]]; then
    args+=(-H "Authorization: Bearer $access_token")
  fi

  curl "${args[@]}"
}

printf '1. Creating connection request on /api/v1/agents/%s/connection-requests\n' "$SLUG"
request_response="$(post_json \
  "$FORAGENT_BASE_URL/api/v1/agents/$SLUG/connection-requests" \
  "$CALLER_SESSION_COOKIE" \
  '{"message":"Need a relay summary for inbound support threads."}')"
request_public_id="$(json_path "$request_response" publicId)"

printf '2. Approving request on /api/v1/connection-requests/%s/approve\n' "$request_public_id"
approve_response="$(post_empty \
  "$FORAGENT_BASE_URL/api/v1/connection-requests/$request_public_id/approve" \
  "$OWNER_SESSION_COOKIE")"
grant_public_id="$(json_path "$approve_response" grant publicId)"
relay_token="$(json_path "$approve_response" relayToken)"

printf '3. Starting canonical thread on /api/v1/agents/%s/threads\n' "$SLUG"
thread_response="$(post_json \
  "$FORAGENT_BASE_URL/api/v1/agents/$SLUG/threads" \
  "" \
  '{"mode":"async","subject":"Starter smoke thread","requestPayload":{"starter":"relay-smoke","source":"foragent-relay-smoke.sh"}}' \
  -H "Authorization: Bearer $relay_token")"
thread_public_id="$(json_path "$thread_response" thread publicId)"
message_public_id="$(json_path "$thread_response" message publicId)"

printf '4. Minting caller thread access token on /api/v1/threads/%s/access-tokens\n' "$thread_public_id"
caller_access_token_response="$(post_empty \
  "$FORAGENT_BASE_URL/api/v1/threads/$thread_public_id/access-tokens" \
  "$CALLER_SESSION_COOKIE")"
caller_access_token="$(json_path "$caller_access_token_response" accessToken)"

printf '5. Reading queued thread on /api/v1/threads/%s\n' "$thread_public_id"
get_json "$FORAGENT_BASE_URL/api/v1/threads/$thread_public_id" "" "$caller_access_token" >/dev/null

printf '6. Appending follow-up on /api/v1/threads/%s/messages\n' "$thread_public_id"
post_json \
  "$FORAGENT_BASE_URL/api/v1/threads/$thread_public_id/messages" \
  "" \
  "{\"mode\":\"async\",\"messageType\":\"follow_up\",\"requestPayload\":{\"step\":\"follow-up\",\"source\":\"foragent-relay-smoke.sh\"},\"parentMessagePublicId\":\"$message_public_id\"}" \
  -H "Authorization: Bearer $relay_token" >/dev/null

printf '7. Minting owner thread access token on /api/v1/threads/%s/access-tokens\n' "$thread_public_id"
owner_access_token_response="$(post_empty \
  "$FORAGENT_BASE_URL/api/v1/threads/$thread_public_id/access-tokens" \
  "$OWNER_SESSION_COOKIE")"
owner_access_token="$(json_path "$owner_access_token_response" accessToken)"

printf '8. Responding on /api/v1/messages/%s/respond\n' "$message_public_id"
post_json \
  "$FORAGENT_BASE_URL/api/v1/messages/$message_public_id/respond" \
  "" \
  '{"responsePayload":{"accepted":true,"summary":"Starter smoke response complete."},"status":"completed"}' \
  -H "Authorization: Bearer $owner_access_token" >/dev/null

printf '9. Closing thread on /api/v1/threads/%s/close\n' "$thread_public_id"
curl --fail -sS -X POST "$FORAGENT_BASE_URL/api/v1/threads/$thread_public_id/close" \
  -H "Authorization: Bearer $caller_access_token" >/dev/null

printf '10. Revoking grant on /api/v1/connection-grants/%s/revoke\n' "$grant_public_id"
post_empty \
  "$FORAGENT_BASE_URL/api/v1/connection-grants/$grant_public_id/revoke" \
  "$OWNER_SESSION_COOKIE" >/dev/null

printf '\nStarter smoke path succeeded.\n'
printf 'requestPublicId=%s\n' "$request_public_id"
printf 'grantPublicId=%s\n' "$grant_public_id"
printf 'threadPublicId=%s\n' "$thread_public_id"
printf 'messagePublicId=%s\n' "$message_public_id"
