"""Track events with buffering, flush explicitly, read them back."""

import os
import time

from tessera import Tessera

# The API key comes from TESSERA_API_KEY; base URLs are env-driven so the
# same script runs against any deployment.
client = Tessera(
    base_url=os.environ["TESSERA_API_BASE"],
    ingest_url=os.environ["TESSERA_INGEST_BASE"],
)

# track() never performs network I/O: it validates locally and buffers.
# A background thread flushes at 100 events or every 2 seconds.
for index in range(5):
    client.events.track(
        {"type": "user", "id": "sdk_sample_1"},
        "page.viewed",
        {"path": f"/products/{index}", "referrer": "newsletter"},
    )

# flush() drains the buffer and returns cumulative delivery counters.
result = client.events.flush()
print(f"accepted={result.accepted} rejected={result.rejected} dropped={result.dropped}")

# Read the events back from the entity's timeline.
for _ in range(30):
    timeline = client.api.list_entity_events(entity_type="user", entity_id="sdk_sample_1")
    if len(timeline.data) >= 5:
        break
    time.sleep(1)
print(f"timeline events: {len(timeline.data)}")

client.close()  # close() (and an atexit hook) flushes any tail
