#!/usr/bin/env bash
# Mixpanel webhook adapter: create the source, receive an event, 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. In Mixpanel, the webhook uses HTTP Basic
#    auth with username "tessera" and this value as the password.
WEBHOOK_SECRET="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')"

# 2. Create the adapter source (write-only secret, sealed with Cloud KMS).
SOURCE="$(curl -sS -X POST "$TESSERA_API_BASE/sources" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d '{"name": "mixpanel-events", "kind": "stream",
       "config": {"subtype": "adapter", "provider": "mixpanel",
                  "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/mixpanel/$SRC_ID"
echo "receiver: $TESSERA_INGEST_BASE/adapters/mixpanel/{src_id}"

# 3. One Mixpanel event, Basic-authenticated as tessera:<secret>.
curl -sS -X POST "$RECEIVER" -u "tessera:$WEBHOOK_SECRET" \
  -H "Content-Type: application/json" --data-binary @mixpanel-event.json \
  | summarize event

# A wrong password 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" \
  -u "tessera:$WRONG_SECRET" \
  -H "Content-Type: application/json" --data-binary @mixpanel-event.json)"
echo "wrong credential: $STATUS"

# 4. Preview: reserved $-prefixed and mp_* properties route to context.
curl -sS -X POST "$TESSERA_API_BASE/sources/$SRC_ID/mapping:preview" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"sample_payload\": $(cat mixpanel-event.json)}" \
  | python3 -c '
import json, sys
event = json.load(sys.stdin)["events"][0]
print("preview:", event["event_type"])
print("attributes:", ",".join(sorted(event["attributes"])))
print("context:", ",".join(sorted(event["context"])))
'

# 5. Backfill: the Export API's NDJSON, chunked to <= 500 events per request.
#    Denied identity events in the export ($identify) are acknowledged and
#    skipped; everything else publishes.
CHUNKS="$(mktemp -d)"
python3 split_ndjson.py mixpanel-export.ndjson "$CHUNKS"
for chunk in "$CHUNKS"/chunk-*.ndjson; do
  curl -sS -X POST "$RECEIVER" -u "tessera:$WEBHOOK_SECRET" \
    -H "Content-Type: application/x-ndjson" --data-binary @"$chunk" \
    | summarize backfill-chunk
done

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