"""Deposit-flight playbook, step 5: the observation-time build and its flag-off twin.

With observation time on, the build adds as-of anchors: points between and
after an account's events where the account has been silent, each carrying
the elapsed silence. The twin is the identical request without it; the
ablation of step 7 compares the two.
"""

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("deposit-flight")

# The M16 switch this playbook proves: "on" (the default) builds, trains and
# serves with observation time; "off" runs the same chain without it, and the
# quiet-book step then fails, because nothing rises under silence.
FLAG_ON = os.environ.get("TESSERA_PLAYBOOK_OBSERVATION_TIME", "on") != "off"

request = {
    "entity_type": "account",
    "labels": [state["label_id"]],
    "window": {
        "max_events_per_entity": 64,
        "time_range": {"start": state["start"], "end": state["window_end"]},
    },
    "split": {"method": "entity_hash", "train": 0.55, "val": 0.15, "test": 0.3, "seed": 7},
}
# Twins read the identical event snapshot: the flag-off build pins one, and
# the observation-time build reuses it.
sides = ["off", "on"] if FLAG_ON else ["off"]
datasets = {}
snapshot_id = None
for side in sides:
    body = dict(request)
    if side == "on":
        body["observation_time"] = {"enabled": True, "between_offsets": 2, "tail_offsets": 4}
        body["snapshot_id"] = snapshot_id
    build = api.post("/datasets", body, key=f"deposit-flight-dataset-{side}")
    built = api.wait(
        f"/datasets/{build['dataset_id']}",
        lambda ds: ds.get("status") in ("succeeded", "failed", "aborted_leakage"),
        what=f"the {side} build",
    )
    print(f"dataset {side}: {built['status']}")
    if built["status"] != "succeeded":
        sys.exit(json.dumps(built)[:3000])
    datasets[side] = built["dataset_id"]
    snapshot_id = built["snapshot_id"]
stats = api.get(f"/labels/{state['label_id']}/stats")
print(f"label positive rate known: {stats.get('positive_rate') is not None}")
print("builds: succeeded")
state.update(datasets=datasets)
