#!/usr/bin/env bash
# S3 bucket connector: create the source (vaulted credentials), test, map, sync.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?your tsk_test_… key}"
: "${TESSERA_S3_ACCESS_KEY_ID:?read-only IAM access key id}"
: "${TESSERA_S3_SECRET_ACCESS_KEY:?read-only IAM secret}"
AUTH=(-H "Authorization: Bearer $TESSERA_API_KEY")

# 1. Create the source. Credentials are write-only: envelope-encrypted at
#    rest and never readable through the API again.
SOURCE="$(curl -sS -X POST "$TESSERA_API_BASE/sources" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-s3-source" \
  -d '{
    "name": "shipment-events",
    "kind": "s3",
    "config": {
      "bucket": "acme-shipment-events",
      "region": "us-east-1",
      "prefix": "events/",
      "format": "csv"
    },
    "credentials": {
      "access_key_id": "'"$TESSERA_S3_ACCESS_KEY_ID"'",
      "secret_access_key": "'"$TESSERA_S3_SECRET_ACCESS_KEY"'"
    }
  }')"
SOURCE_ID="$(printf '%s' "$SOURCE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["source_id"])')"
printf '%s' "$SOURCE" | python3 -c '
import json, sys
source = json.load(sys.stdin)
print("source created: %s credentials_set=%s" % (source["kind"], source["credentials_set"]))
'

# 2. Test the connection.
curl -sS -X POST "$TESSERA_API_BASE/sources/$SOURCE_ID/test-connection" "${AUTH[@]}" \
  | python3 -c 'import json,sys; print("test-connection:", json.load(sys.stdin)["status"])'

# 3. Map columns, then run the first sync.
curl -sS -X PUT "$TESSERA_API_BASE/sources/$SOURCE_ID/mapping" "${AUTH[@]}" \
  -H "Content-Type: application/json" --data-binary @mapping-logistics.json > /dev/null

SYNC="$(curl -sS -X POST "$TESSERA_API_BASE/sources/$SOURCE_ID/syncs" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-s3-first-sync" \
  -d '{"mode": "full"}')"
SYNC_ID="$(printf '%s' "$SYNC" | python3 -c 'import json,sys; print(json.load(sys.stdin)["sync_id"])')"
for _ in $(seq 1 300); do
  SYNC="$(curl -sS "$TESSERA_API_BASE/syncs/$SYNC_ID" "${AUTH[@]}")"
  STATUS="$(printf '%s' "$SYNC" | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])')"
  if [ "$STATUS" = "succeeded" ] || [ "$STATUS" = "failed" ]; then break; fi
  sleep 1
done
printf '%s' "$SYNC" | python3 -c '
import json, sys
sync = json.load(sys.stdin)
print("first sync: %s rows_landed=%s rejected=%s"
      % (sync["status"], sync["rows_landed"], sync["rows_rejected"]))
'
