"""PostHog-loop playbook, step 7: activate, score, bind the protocol's bands.

The bands written to PostHog are the protocol's bands, fingerprint and all.
"""

import json
import os
import sys
from pathlib import Path

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")

model_id = state["model_id"]
model = api.get(f"/models/{model_id}")
body = {}
promotion = model.get("promotion") or {}
if promotion.get("verdict") == "needs_acknowledgement":
    # Explicit consent only: the operator names the advisory gates they accept
    # and the reason; the bundle acknowledges those that are failing now. A
    # failing gate the operator did not name is left for the API to refuse.
    raw = os.environ.get("TESSERA_QUICKSTART_ACKNOWLEDGEMENT", "")
    if raw:
        consent = json.loads(raw)
        gates = [gate for gate in consent["gates"] if gate in promotion.get("advisory", [])]
        if gates:
            body["acknowledge_gates"] = {"gates": gates, "reason": consent["reason"]}
bundle = api.post(f"/models/{model_id}/bundles", body, key="posthog-loop-bundle")
slot = api.post(
    "/slots",
    {
        "environment": "test",
        "name": "growth",
        "entity_type": "user",
        "mode": "live",
        "scoring": "batch_only",
    },
    key="posthog-loop-slot",
)
activated = api.post(f"/slots/{slot['slot_id']}:activate", {"bundle_id": bundle["bundle_id"]})
print(f"slot growth active: {activated['active_bundle_id'] == bundle['bundle_id']}")
refresh = api.post("/slots/growth/refreshes", {"cutoff": state["end"]}, key="posthog-loop-refresh")
refresh = api.wait(
    f"/slots/growth/refreshes/{refresh['refresh_id']}",
    lambda item: item.get("status") in ("succeeded", "failed"),
    what="the batch refresh",
)
print(f"refresh: {refresh['status']}, users scored: {refresh.get('entities_scored')}")
binding = {
    "label": "repeat_purchase_30d",
    "policy": state["banding_policy"],
    "policy_fingerprint": state["banding_policy_fingerprint"],
}
bands = api.put("/slots/growth/bands", {"bindings": [binding]})
names = [band["band"] for band in bands["bindings"][0]["policy"]["bands"]]
print(f"bands bound: {', '.join(names)}")
state.update(slot_id=slot["slot_id"], scored=refresh.get("entities_scored"))
