"""Quickstart step 1 (planned Python SDK) — send your first events."""

import os
import time
from datetime import UTC, datetime

from tessera import Tessera

client = Tessera(  # the API key comes from TESSERA_API_KEY
    base_url=os.environ["TESSERA_API_BASE"],
    ingest_url=os.environ["TESSERA_INGEST_BASE"],
)

now = datetime.now(UTC)

# track() validates locally and buffers; nothing hits the network yet.
client.events.track(
    {"type": "user", "id": "u_hello_1"},
    "order.placed",
    {"order_value": 42.5, "item_count": 2, "category": "apparel"},
    timestamp=now,
    event_id="hello-0001",
)
client.events.track(
    {"type": "user", "id": "u_hello_1"},
    "support.ticket_opened",
    {"ticket_topic": "delivery"},
    timestamp=now,
    event_id="hello-0002",
)

# flush() drains the buffer and reports what the platform accepted.
result = client.events.flush()
print(f"accepted={result.accepted} rejected={result.rejected}")

# Within a couple of seconds the events appear on the entity's timeline.
for _ in range(30):
    timeline = client.api.list_entity_events(entity_type="user", entity_id="u_hello_1")
    if len(timeline.data) >= 2:
        break
    time.sleep(1)

for item in timeline.data:
    print("timeline:", item.event.event_type)
print(f"timeline events for u_hello_1: {len(timeline.data)}")
client.close()
