# Dimension Labs helpers for the universal API. Save as dimensionlabs.py next to your script.
# Python 3.9 or later, with requests installed (pip install requests). Set DL_API_KEY in the environment.
# Docs: https://docs.dimensionlabs.io/api/tracker
import os, time
from datetime import datetime, timezone
import requests

DL = "https://tracker.dimensionlabs.io"

def send_to_dimension_labs(msg, historical=False, api_key=None, retries=5):
    """Send one message. Use historical=True for anything older than an hour, then run a backfill.
    Retries 429 and 5xx with exponential backoff; duplicates are removed by Dimension Labs, so retries are safe."""
    api_key = api_key or os.environ.get("DL_API_KEY")
    if not api_key:
        raise RuntimeError("Set DL_API_KEY to your source API key.")
    path = "trackhistorical" if historical else "track"
    params = {"platform": "universal", "v": "11.1.0-rest", "type": "incoming" if msg["incoming"] else "outgoing", "apiKey": api_key}
    for attempt in range(retries + 1):
        r = requests.post(f"{DL}/{path}", params=params, json=msg, timeout=30)
        if r.ok:
            return
        if (r.status_code == 429 or r.status_code >= 500) and attempt < retries:
            after = r.headers.get("Retry-After")
            time.sleep(float(after) if after and after.isdigit() else 0.5 * 2 ** attempt)
            continue
        raise RuntimeError(f"Dimension Labs returned {r.status_code}: {r.text}")

def to_millis(value):
    """Any date to Unix milliseconds. Numbers below 1e12 are seconds. Text without a zone is read as UTC."""
    if isinstance(value, (int, float)):
        return int(round(value * 1000)) if value < 1e12 else int(value)
    s = str(value).strip()
    if s.replace(".", "", 1).isdigit():
        return to_millis(float(s))
    s = s.replace("Z", "+00:00").replace(" ", "T", 1)
    dt = datetime.fromisoformat(s)
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return int(dt.timestamp() * 1000)
