#!/usr/bin/env sh
# Production collectors must durably retain this exact batch until the response
# passes identity and accounting checks. This is a minimal protocol example.

: "${READABLE_INGESTION_KEY:?Set READABLE_INGESTION_KEY}"
: "${READABLE_SITE_ID:?Set READABLE_SITE_ID}"
: "${READABLE_INTEGRATION_ID:?Set READABLE_INTEGRATION_ID}"
: "${TMPDIR:=/tmp}"

RUN_ID="$(date -u +%s)"
NOW="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
BATCH_ID="batch:example-${RUN_ID}"
RECEIPT_FILE="$(mktemp "${TMPDIR%/}/readable-receipt.XXXXXX")"
trap 'rm -f "$RECEIPT_FILE"' EXIT HUP INT TERM

HTTP_STATUS="$(curl --silent --show-error --connect-timeout 5 --max-time 15 --max-redirs 0 --request POST \
  "https://www.tryreadable.ai/api/external-agentic/traffic/batches" \
  --header "Authorization: Bearer ${READABLE_INGESTION_KEY}" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: ${BATCH_ID}" \
  --header "X-Readable-Ingestion-Version: 1" \
  --data "{
    \"schema\": \"readable.external-agentic.traffic\",
    \"version\": 1,
    \"site_id\": \"${READABLE_SITE_ID}\",
    \"batch_id\": \"${BATCH_ID}\",
    \"created_at\": \"${NOW}\",
    \"source\": {
      \"type\": \"server_log\",
      \"provider\": \"generic\",
      \"integration_id\": \"${READABLE_INTEGRATION_ID}\",
      \"collector\": \"curl-example\",
      \"collector_version\": \"1.0.0\"
    },
    \"event_count\": 1,
    \"events\": [{
      \"event_id\": \"evt:example-${RUN_ID}\",
      \"occurred_at\": \"${NOW}\",
      \"request\": {
        \"request_id\": \"request:example-${RUN_ID}\",
        \"method\": \"GET\",
        \"scheme\": \"https\",
        \"hostname\": \"www.example.com\",
        \"path\": \"/products/example\",
        \"user_agent\": \"ChatGPT-User/1.0\",
        \"referrer_url\": \"https://chatgpt.com/\"
      },
      \"response\": {
        \"status\": 200,
        \"content_type\": \"text/html; charset=utf-8\",
        \"duration_ms\": 84,
        \"bytes_sent\": 18422
      },
      \"extensions\": {}
    }]
  }" --output "$RECEIPT_FILE" --write-out '%{http_code}')"

[ "$HTTP_STATUS" = "200" ] || { cat "$RECEIPT_FILE" >&2; exit 1; }
jq -e --arg site "$READABLE_SITE_ID" --arg batch "$BATCH_ID" '
  .success == true and .accepted == true and
  .site_id == $site and .batch_id == $batch and .event_count == 1 and
  .event_count == (.inserted + .deduplicated + .rejected)
' "$RECEIPT_FILE" >/dev/null || { echo "Invalid acknowledgement; retain the batch for retry" >&2; exit 1; }
jq . "$RECEIPT_FILE"
