"""Quickstart step 4 (planned Python SDK) — define the label, upload observations."""

import os
import time
from pathlib import Path

import httpx

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", "."))
sample_dir = state_dir / "sample"

label_source = client.sources.create(
    models.SourceCreateRequest(name="quickstart-labels", kind="file_upload", config={})
)

label = client.api.create_label(
    models.LabelCreateRequest(
        name="repeat_purchase_30d",
        entity_type="user",
        task="binary",
        source=models.LabelSourceInput(
            root=models.LabelTableSource(
                kind="label_table",
                source_id=label_source.source_id,
                entity_id_column="entity_id",
                value_column="value",
                observed_at_column="observed_at",
            )
        ),
        maturation_days=7,
    )
)
print(f"label {label.name}: task={label.task.value} maturation_days={label.maturation_days}")

session = client.api.create_upload(
    models.UploadCreateRequest(
        filename="labels_repeat_purchase.csv",
        format="csv",
        source_id=label_source.source_id,
    )
)
httpx.put(
    str(session.upload_url),
    content=(sample_dir / "labels_repeat_purchase.csv").read_bytes(),
).raise_for_status()
client.api.complete_upload(session.upload_id)
upload = client.api.get_upload(session.upload_id)
for _ in range(300):
    sync = client.syncs.get(str(upload.sync_id))
    if sync.status.value in ("succeeded", "failed"):
        break
    time.sleep(1)
print(f"label sync: {sync.status.value}")

stats = client.api.get_label_stats(label.label_id)
print(f"observations: {stats.observations}")
print(f"matured: {stats.maturation_coverage.matured}")

(state_dir / "label_id").write_text(label.label_id)
client.close()
