"""Quickstart step 7 (planned Python SDK) — bundle, slot, activate, batch score."""

import json
import os
import time
from pathlib import Path

from tessera import Tessera
from tessera._generated import models

client = Tessera(base_url=os.environ["TESSERA_API_BASE"])
state_dir = Path(os.environ.get("TESSERA_STATE_DIR", "."))
model_id = (state_dir / "model_id").read_text().strip()

# Optional, explicit acknowledgement after reviewing this model's evaluation.
# The registry still refuses blocking gates and rechecks the exact advisory set.
model = client.api.get_model(model_id)
raw_ack = os.environ.get("TESSERA_QUICKSTART_ACKNOWLEDGEMENT", "")
ack = models.AcknowledgeGates.model_validate(json.loads(raw_ack)) if raw_ack else None
if ack is not None and not ack.reason.strip():
    raise SystemExit("Acknowledgement must contain gate IDs and a non-empty reason")
promotion = model.promotion
body = None
if promotion is None or promotion.verdict == models.Verdict.blocked:
    raise SystemExit("Promotion is blocked or unavailable; inspect the model and evaluation")
if promotion.verdict == models.Verdict.needs_acknowledgement and ack is not None:
    # The operator names the advisory gates they accept; the bundle acknowledges
    # those that are failing now, and the API refuses any failing gate left out.
    failing = {getattr(gate, "value", gate) for gate in promotion.advisory}
    accepted = [gate for gate in ack.gates if getattr(gate, "value", gate) in failing]
    if accepted:
        body = models.CreateBundleRequest(
            acknowledge_gates=models.AcknowledgeGates(gates=accepted, reason=ack.reason)
        )
bundle = client.api.create_model_bundle(model_id, body)
print(f"bundle pins contract v{bundle.pins['contract_version']}")

slot = client.api.create_slot(
    models.SlotCreateRequest(
        environment="test",
        name="quickstart",
        entity_type="user",
        mode="live",
        scoring="batch_only",
    )
)

# Activation re-verifies every pinned fingerprint before serving.
activated = client.api.activate_slot(
    slot.slot_id, models.SlotActivateRequest(bundle_id=bundle.bundle_id)
)
print(f"slot {activated.name} activated: {activated.active_bundle_id == bundle.bundle_id}")

refresh = client.api.create_slot_refresh(
    "quickstart", models.RefreshCreateRequest(cutoff="2025-07-01T00:00:00Z")
)
for _ in range(600):
    refresh = client.api.get_slot_refresh(refresh.refresh_id, "quickstart")
    if refresh.status.value in ("succeeded", "failed"):
        break
    time.sleep(2)
print(f"refresh: {refresh.status.value} entities_scored={refresh.entities_scored}")
client.close()
