#!/usr/bin/env bash
# Amplitude webhook adapter: create the source, receive deliveries, preview
# the mapping, then backfill exported history through the same receiver.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_INGEST_BASE:?e.g. https://ingest.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?your tsk_test_… key}"
AUTH=(-H "Authorization: Bearer $TESSERA_API_KEY")

summarize() {
  python3 -c 'import json, sys; r = json.load(sys.stdin); print("%s: %s events=%s" % (sys.argv[1], r["outcome"], r["events"]))' "$1"
}

# 1. A random shared credential. Paste the same value into Amplitude's
#    webhook destination as the Bearer token header.
WEBHOOK_SECRET="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')"

# 2. Create the adapter source. The secret is write-only and sealed with
#    Cloud KMS before it is stored; reads show {"set": true} in its place.
SOURCE="$(curl -sS -X POST "$TESSERA_API_BASE/sources" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d '{"name": "amplitude-events", "kind": "stream",
       "config": {"subtype": "adapter", "provider": "amplitude",
                  "webhook_secret": "'"$WEBHOOK_SECRET"'"}}')"
SRC_ID="$(printf '%s' "$SOURCE" | python3 -c 'import json, sys; print(json.load(sys.stdin)["source_id"])')"
RECEIVER="$TESSERA_INGEST_BASE/adapters/amplitude/$SRC_ID"
echo "receiver: $TESSERA_INGEST_BASE/adapters/amplitude/{src_id}"

# 3. A delivery exactly as Amplitude's webhook destination sends it: a JSON
#    array of events with the shared credential as a Bearer token.
curl -sS -X POST "$RECEIVER" --oauth2-bearer "$WEBHOOK_SECRET" \
  -H "Content-Type: application/json" --data-binary @amplitude-delivery.json \
  | summarize delivery

# Identity-management events ($identify, $merge_user, $groupidentify) are
# denied by the catalog: acknowledged, counted, never published.
curl -sS -X POST "$RECEIVER" --oauth2-bearer "$WEBHOOK_SECRET" \
  -H "Content-Type: application/json" --data-binary @amplitude-identify.json \
  | summarize identify

# A wrong credential is rejected before the body is even parsed.
WRONG_SECRET="$(python3 -c 'import secrets; print(secrets.token_urlsafe(16))')"
STATUS="$(curl -sS -o /dev/null -w '%{http_code}' -X POST "$RECEIVER" \
  --oauth2-bearer "$WRONG_SECRET" \
  -H "Content-Type: application/json" --data-binary @amplitude-delivery.json)"
echo "wrong credential: $STATUS"

# 4. Preview: the exact canonical events the live path publishes, with zero
#    side effects.
curl -sS -X POST "$TESSERA_API_BASE/sources/$SRC_ID/mapping:preview" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"sample_payload\": $(cat amplitude-delivery.json)}" \
  | python3 -c 'import json, sys; r = json.load(sys.stdin); print("preview:", " ".join(e["event_type"] for e in r["events"]))'

# 5. Backfill: Amplitude Export API lines -> NDJSON chunks of <= 500 events,
#    posted to the same receiver with the same credential.
CHUNKS="$(mktemp -d)"
python3 export_to_ndjson.py amplitude-export.jsonl "$CHUNKS"
for chunk in "$CHUNKS"/chunk-*.ndjson; do
  curl -sS -X POST "$RECEIVER" --oauth2-bearer "$WEBHOOK_SECRET" \
    -H "Content-Type: application/x-ndjson" --data-binary @"$chunk" \
    | summarize backfill-chunk
done

# 6. The published events land on the listener's timeline.
COUNT=0
for _ in $(seq 1 30); do
  COUNT="$(curl -sS "$TESSERA_API_BASE/entities/user/listener-20417/events" "${AUTH[@]}" \
    | python3 -c 'import json, sys; print(len(json.load(sys.stdin)["data"]))')"
  if [ "$COUNT" -ge 2 ]; then break; fi
  sleep 1
done
echo "timeline events for listener-20417: $COUNT"
