#!/usr/bin/env python3
"""Post four synthetic readings and verify the batch through a separate viewer principal."""

import gzip
import json
import os
import time
import urllib.request
import uuid
from pathlib import Path

origin = os.environ.get("INTOUCH_ORIGIN", "http://127.0.0.1:8917").rstrip("/")
envfile = Path(__file__).resolve().parents[1] / ".env"
tokens = (
    dict(line.split("=", 1) for line in envfile.read_text().splitlines() if "=" in line)
    if envfile.exists()
    else {}
)


def principal(key):
    return "Bearer " + (os.environ.get(key) or tokens[key])


stamp = time.time_ns() // 1000000
batch = {
    "id": str(uuid.uuid4()),
    "trigger": "manual",
    "samples": [
        {
            "kind": "movement",
            "ts": stamp - 60 + i * 20,
            "values": {
                "x": x,
                "y": 0,
                "z": 0,
                "unit": "m/s2",
                "source": "synthetic-example",
            },
        }
        for i, x in enumerate((0.1, 0.4, 1.1, 0.3))
    ],
}
payload = gzip.compress(json.dumps(batch).encode())
req = urllib.request.Request(
    origin + "/v1/batches",
    data=payload,
    headers={
        "Authorization": principal("WEB_TOKEN"),
        "Content-Type": "application/json",
        "Content-Encoding": "gzip",
    },
)
with urllib.request.urlopen(req, timeout=10) as r:
    ack = json.load(r)
assert ack["id"] == batch["id"] and ack["accepted"] == 4
req = urllib.request.Request(
    origin + "/v1/devices/web-lab/samples",
    headers={"Authorization": principal("VIEW_TOKEN")},
)
with urllib.request.urlopen(req, timeout=10) as r:
    assert sum(s["batch"] == batch["id"] for s in json.load(r)["samples"]) == 4
print(
    "Verified four 20 ms readings in web-lab ·", len(payload), "compressed body bytes"
)
