import json
import os
import urllib.request
import uuid
from datetime import datetime, timezone

api_key = os.environ["READABLE_INGESTION_KEY"]
site_id = os.environ["READABLE_SITE_ID"]
integration_id = os.environ["READABLE_INTEGRATION_ID"]
run_id = str(uuid.uuid4())
batch_id = f"batch:example-{run_id}"
now = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
payload = {
    "schema": "readable.external-agentic.traffic", "version": 1,
    "site_id": site_id, "batch_id": batch_id, "created_at": now,
    "source": {"type": "application_event", "provider": "generic",
               "integration_id": integration_id, "collector": "python-example",
               "collector_version": "1.0.0"},
    "event_count": 1,
    "events": [{"event_id": f"evt:example-{run_id}", "occurred_at": now,
                "request": {"request_id": f"request:example-{run_id}", "method": "GET",
                            "scheme": "https", "hostname": "www.example.com",
                            "path": "/products/example", "user_agent": "ChatGPT-User/1.0",
                            "referrer_url": "https://chatgpt.com/"},
                "response": {"status": 200, "content_type": "text/html",
                             "duration_ms": 84, "bytes_sent": 18422}, "extensions": {}}],
}
request = urllib.request.Request(
    "https://www.tryreadable.ai/api/external-agentic/traffic/batches",
    data=json.dumps(payload).encode(), method="POST",
    headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json",
             "Idempotency-Key": batch_id, "X-Readable-Ingestion-Version": "1"},
)
class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

with urllib.request.build_opener(NoRedirect()).open(request, timeout=15) as response:
    receipt = json.load(response)
if (receipt.get("success") is not True or receipt.get("accepted") is not True or
        receipt.get("site_id") != site_id or receipt.get("batch_id") != batch_id or
        receipt.get("event_count") != payload["event_count"] or
        receipt["event_count"] != receipt["inserted"] + receipt["deduplicated"] + receipt["rejected"]):
    raise RuntimeError("Invalid acknowledgement; retain the batch for retry")
print(json.dumps(receipt, indent=2))
