#!/usr/bin/env bash
# Label-free quickstart step 3 — create the derived label. No label file is
# uploaded: the supervision comes from the entities' own future events.
set -euo pipefail

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

LABEL="$(curl -sS -X POST "$TESSERA_API_BASE/labels" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: label-free-label" \
  -d '{
    "name": "churn_30d",
    "entity_type": "user",
    "task": "binary",
    "source": {
      "kind": "derived",
      "rule": {
        "template": "churn",
        "horizon_days": 30,
        "predicate": {"event_type_pattern": "order.*", "min_count": 1},
        "outcome": "absence",
        "anchor_cadence": "daily_last_event"
      }
    }
  }')"
printf '%s' "$LABEL" | python3 -c '
import json, sys
label = json.load(sys.stdin)
print(json.dumps({
    "label_id": label["label_id"],
    "name": label["name"],
    "task": label["task"],
    "source_kind": label["source"]["kind"],
    "maturation_days": label["maturation_days"],
}, indent=2))
'
printf '%s' "$LABEL" | python3 -c 'import json,sys; print(json.load(sys.stdin)["label_id"], end="")' \
  > "$TESSERA_STATE_DIR/label_id"
