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(path, request_data):
    base, headers = _client()
    data = json.dumps({"request_data": request_data}).encode("utf-8")
    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 main():
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    rd = {"endpoint_id": inputs.get("endpoint_id")}
    if inputs.get("incident_id"):
        rd["incident_id"] = inputs["incident_id"]
    print(json.dumps(post("/endpoints/unisolate", rd)))


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)
