"""Security-lake playbook, step 8: evidence on, bundle, activate, bind the bands.

A signals evaluation with evidence on makes every score carry the events that
moved it. The bundle copies that configuration, the batch slot serves it, and
the protocol's review bands are bound to the label, so alert rules and exports
read the same bands the report judges.
"""

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("security-lake")

model_id = state["model_id"]
created = api.post(
    f"/models/{model_id}/signals-evaluations",
    {"evidence": {"enabled": True, "top_k": 8}, "seed": 0},
    key="security-lake-signals",
)
signals = api.wait(
    f"/models/{model_id}/signals-evaluations/{created['report_id']}",
    lambda item: item.get("status") in ("succeeded", "failed"),
    what="the evidence evaluation",
)
print(f"evidence evaluation: {signals['status']}")
if signals["status"] != "succeeded":
    sys.exit(json.dumps(signals)[:3000])

model = api.get(f"/models/{model_id}")
body = {"signals": {"enabled": True}}
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="security-lake-bundle")
runtime_signals = (bundle.get("runtime") or {}).get("signals") or {}
print(f"bundle: evidence in the runtime: {bool(runtime_signals.get('evidence'))}")

slot = api.post(
    "/slots",
    {
        "environment": "test",
        "name": "security",
        "entity_type": "user",
        "mode": "live",
        "scoring": "batch_only",
    },
    key="security-lake-slot",
)
activated = api.post(f"/slots/{slot['slot_id']}:activate", {"bundle_id": bundle["bundle_id"]})
print(f"slot security active: {activated['active_bundle_id'] == bundle['bundle_id']}")
binding = {
    "label": "repeated_logon_failure_1d",
    "policy": state["banding_policy"],
    "policy_fingerprint": state["banding_policy_fingerprint"],
}
bands = api.put("/slots/security/bands", {"bindings": [binding]})
names = [band["band"] for band in bands["bindings"][0]["policy"]["bands"]]
print(f"bands bound: {', '.join(names)}")
state.update(bundle_id=bundle["bundle_id"])
