#!/usr/bin/env python3
import urllib.request, json

BASE = "https://ota.46-4-121-190.sslip.io"

def call(method, url, data=None, token=None):
    h = {"Content-Type": "application/json"}
    if token:
        h["Authorization"] = f"Bearer {token}"
    req = urllib.request.Request(url, data=(json.dumps(data).encode() if data else None), headers=h, method=method)
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            return json.loads(r.read())
    except urllib.error.HTTPError as e:
        return {"err": e.code, "msg": e.read()[:200].decode()}

tok = call("POST", f"{BASE}/authentication", {"strategy": "local", "username": "admin", "password": "353fde0a0fe4e8a0b2799e54"})["accessToken"]

# release known-good 1.0.111
r = call("PATCH", f"{BASE}/uploads/6a770cf8bce64410088d075a", {"status": "released"}, tok)
print("release 6a770cf8 (1.0.111):", r.get("status") or r)
# demote my 1.0.113
r2 = call("PATCH", f"{BASE}/uploads/6a772081bce64410088d075c", {"status": "obsolete"}, tok)
print("demote 6a772081 (1.0.113):", r2.get("status") or r2)

# verify exactly one released
d = call("GET", f"{BASE}/uploads", token=tok)
uploads = d.get("data", d) if isinstance(d, dict) else d
print("--- released uploads now ---")
for u in uploads:
    if u.get("status") == "released":
        print("RELEASED:", u["_id"], u.get("version"), u.get("updateId"))
