"""Idempotent ingestion: the same event_id can never land twice."""

import os
import time

from tessera import Tessera

client = Tessera(
    base_url=os.environ["TESSERA_API_BASE"],
    ingest_url=os.environ["TESSERA_INGEST_BASE"],
)

event = {
    "entity": {"type": "user", "id": "sdk_sample_2"},
    "event_type": "order.placed",
    "attributes": {"order_value": 19.99},
    "timestamp": "2026-01-15T09:30:00Z",
    "event_id": "3f8a6c1e-9b24-4d75-a0c3-5e1d7b2f4a90",  # your idempotency id
}

# Send it twice — a retry, a replayed queue, a double-clicked backfill.
client.events.track(**event)
client.events.flush()
client.events.track(**event)
result = client.events.flush()
print(f"second send: accepted={result.accepted}")

# The platform dedupes on event_id: exactly one event exists.
for _ in range(30):
    timeline = client.api.list_entity_events(entity_type="user", entity_id="sdk_sample_2")
    if len(timeline.data) >= 1:
        break
    time.sleep(1)
time.sleep(2)  # give a duplicate every chance to appear
timeline = client.api.list_entity_events(entity_type="user", entity_id="sdk_sample_2")
print(f"events with id 3f8a6c1e-9b24-4d75-a0c3-5e1d7b2f4a90: {len(timeline.data)}")
client.close()
