#!/usr/bin/env python3
"""Full OTA server health check — verify server is serving correctly and
inspect the uploads state for any sign of tampering."""
import urllib.request, json

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

def call(method, path, body=None, tok=None, headers=None):
    h = dict(headers or {})
    h["Content-Type"] = "application/json"
    if tok: h["Authorization"] = f"Bearer {tok}"
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(f"{BASE}{path}", data=data, method=method, headers=h)
    try:
        with urllib.request.urlopen(req, timeout=30) as r:
            raw = r.read().decode('utf-8', 'replace')
            try: return r.status, json.loads(raw)
            except: return r.status, raw[:500]
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode('utf-8','replace')[:500]
    except Exception as e:
        return None, f"{type(e).__name__}: {e}"

# 1. Auth
s, tok = call("POST", "/authentication", {"strategy":"local","username":"admin","password":"353fde0a0fe4e8a0b2799e54"})
print("AUTH:", s, (tok.get("accessToken","")[:20]+"...") if isinstance(tok,dict) else tok)
if not isinstance(tok, dict) or not tok.get("accessToken"):
    print("AUTH FAILED — cannot proceed"); raise SystemExit
tok = tok["accessToken"]

# 2. List all uploads
s, d = call("GET", "/uploads", tok=tok)
print("\n=== ALL UPLOADS (status) ===")
uploads = d.get("data", d) if isinstance(d, dict) else d
if isinstance(uploads, list):
    for u in uploads:
        print(f"  {u.get('uploadId','?')[:20]}... status={u.get('status')} version={u.get('version')} updateId={str(u.get('updateId'))[:20]}...")
else:
    print("  unexpected:", str(uploads)[:300])

# 3. Health endpoint if any
for ep in ["/health", "/api/health", "/status", "/api/status"]:
    s, r = call("GET", ep)
    print(f"\nGET {ep}: {s} {str(r)[:200]}")
