"""PostHog-loop playbook, step 3: the label the loop acts on.

`repeat_purchase_30d` reads a label table: one row per user with the outcome
and the instant it became known (the sample dataset's
`labels_repeat_purchase.csv`), uploaded to a `file_upload` source. On your
product it is whatever records the outcome: billing, a warehouse table, a
webhook.
"""

import sys
from pathlib import Path

import httpx

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))  # playbooks/playbook_api.py
from playbook_api import Api, State

api, state = Api(), State("posthog-loop")

source = api.post(
    "/sources",
    {"name": "repeat-purchase outcomes", "kind": "file_upload", "config": {}},
    key="posthog-loop-label-source",
)
label = api.post(
    "/labels",
    {
        "name": "repeat_purchase_30d",
        "entity_type": "user",
        "task": "binary",
        "source": {
            "kind": "label_table",
            "source_id": source["source_id"],
            "entity_id_column": "entity_id",
            "value_column": "value",
            "observed_at_column": "observed_at",
        },
        "maturation_days": 7,
    },
    key="posthog-loop-label",
)
print(f"label: {label['name']}")

table = (Path(state["sample_dir"]) / "labels_repeat_purchase.csv").read_bytes()
session = api.post(
    "/uploads",
    {"filename": "labels_repeat_purchase.csv", "format": "csv", "source_id": source["source_id"]},
    key="posthog-loop-label-upload",
)
httpx.put(session["upload_url"], content=table, timeout=120.0).raise_for_status()
api.post(f"/uploads/{session['upload_id']}:complete")
upload = api.get(f"/uploads/{session['upload_id']}")
sync = api.wait(
    f"/syncs/{upload['sync_id']}",
    lambda item: item.get("status") in ("succeeded", "failed"),
    what="the label table sync",
    polls=150,
)
print(f"label table sync: {sync['status']}")
stats = api.get(f"/labels/{label['label_id']}/stats")
print(f"label observations stored: {int(stats.get('observations') or 0) > 0}")
state.update(label_id=label["label_id"], label_source_id=source["source_id"])
