import json, os, sys, time, hashlib, secrets, string, urllib.request, urllib.error


def _client():
    s = json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
    base = s.get("url", "").rstrip("/") + "/public_api/v1"
    key = s.get("api_key", "")
    kid = str(s.get("api_key_id", ""))
    headers = {"x-xdr-auth-id": kid, "Content-Type": "application/json", "Accept": "application/json"}
    if str(s.get("auth_type") or "standard").lower() == "advanced":
        nonce = "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(64))
        ts = str(int(time.time()) * 1000)
        headers["x-xdr-nonce"] = nonce
        headers["x-xdr-timestamp"] = ts
        headers["Authorization"] = hashlib.sha256((key + nonce + ts).encode("utf-8")).hexdigest()
    else:
        headers["Authorization"] = key
    return base, headers


def post_raw(path, body):
    base, headers = _client()
    data = json.dumps(body).encode("utf-8") if body is not None else None
    req = urllib.request.Request(base + path, data=data, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=90) as r:
        raw = r.read()
        return json.loads(raw) if raw else {}


def post(path, request_data=None):
    return post_raw(path, {"request_data": request_data} if request_data is not None else None)


def csv(v):
    return [x.strip() for x in str(v or "").split(",") if x.strip()]


def to_ms(v):
    if v in (None, ""):
        return None
    s = str(v)
    if s.isdigit():
        return int(s)
    try:
        from datetime import datetime
        return int(datetime.fromisoformat(s.replace("Z", "+00:00")).timestamp() * 1000)
    except Exception:
        return None


def main():
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    print(json.dumps(post("/distributions/get_dist_url/", {"distribution_id": inputs.get("distribution_id"), "package_type": inputs.get("package_type")})))


try:
    main()
except urllib.error.HTTPError as e:
    print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
    sys.exit(1)
except Exception as e:
    print(json.dumps({"error": str(e)}))
    sys.exit(1)
