"""Python 3 example. Replace process_event with durable, idempotent storage."""
import hashlib, json, os, time, urllib.request, urllib.error, urllib.parse
from pathlib import Path
API = "https://us-central1-stocker-fcda2.cloudfunctions.net/institutionalSignalsApi/v1/events"
# Omit these environment variables to receive all connected categories.
selection = {name: os.environ[env] for name, env in [
    ("categories", "STBN_CATEGORIES"), ("symbols", "STBN_SYMBOLS"), ("group", "STBN_GROUP")
] if os.environ.get(env)}
# Each distinct filter needs its own cursor. Include an account-specific name if
# running multiple subscriptions in the same folder. Never share cursor files.
identity = os.environ.get("STBN_ACCOUNT", "default") + json.dumps(selection, sort_keys=True)
STATE = Path("stbn-cursor-" + hashlib.sha256(identity.encode()).hexdigest()[:16] + ".txt")
key = os.environ["STBN_API_KEY"]
def process_event(event):
    # Deduplicate by event["id"] in your database before performing side effects.
    print(json.dumps(event), flush=True)
while True:
    cursor = STATE.read_text().strip() if STATE.exists() else ""
    params = dict(selection)
    if cursor: params["after"] = cursor
    request = urllib.request.Request(API + "?" + urllib.parse.urlencode(params), headers={"Authorization": "Bearer " + key})
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            page = json.load(response)
        for event in page["data"]:
            process_event(event)
        temporary = STATE.with_suffix(".tmp")
        temporary.write_text(page["next_cursor"])
        temporary.replace(STATE)
        if not page["has_more"]: time.sleep(5)
    except urllib.error.HTTPError as error:
        if error.code in (400, 401, 403): raise SystemExit("Check request, API key or subscription; HTTP " + str(error.code))
        time.sleep(max(5, int(error.headers.get("Retry-After", "30"))))
    except (urllib.error.URLError, TimeoutError):
        time.sleep(30)
