import json, os, sys, urllib.parse, urllib.request, urllib.error

SCOPE = "https://api.securitycenter.microsoft.com/.default"
API = "https://api.securitycenter.microsoft.com/api"


def _cfg():
    return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))


def _token():
    cfg = _cfg()
    data = urllib.parse.urlencode({
        "grant_type": "client_credentials",
        "client_id": str(cfg.get("client_id") or ""),
        "client_secret": str(cfg.get("client_secret") or ""),
        "scope": SCOPE,
    }).encode("utf-8")
    url = "https://login.microsoftonline.com/" + str(cfg.get("tenant_id") or "") + "/oauth2/v2.0/token"
    req = urllib.request.Request(url, data=data,
                                 headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json"},
                                 method="POST")
    with urllib.request.urlopen(req, timeout=60) as r:
        tok = json.loads(r.read())
    if not tok.get("access_token"):
        raise Exception("Token request failed: " + json.dumps(tok))
    return tok["access_token"]


def request(method, path, params=None, body=None, full_url=None, token=None):
    url = full_url or (API + path)
    q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
    if q:
        url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {"Accept": "application/json", "Authorization": "Bearer " + (token or _token())}
    if data is not None:
        headers["Content-Type"] = "application/json"
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    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", "{}"))
    indicator_value = inputs.get("indicator_value")
    if not indicator_value:
        raise Exception("indicator_value is required")
    indicator_type = inputs.get("indicator_type")
    if not indicator_type:
        raise Exception("indicator_type is required")
    action = inputs.get("action")
    title = inputs.get("title")
    description = inputs.get("description")
    severity = inputs.get("severity")
    expiration_time = inputs.get("expiration_time")

    body = {}
    body["indicatorValue"] = indicator_value
    body["indicatorType"] = indicator_type
    body["action"] = action or "Alert"
    body["title"] = title or "Riposte indicator"
    body["description"] = description or "Created via Riposte"
    if severity not in (None, ""):
        body["severity"] = severity
    if expiration_time not in (None, ""):
        body["expirationTime"] = expiration_time

    result = request("POST", "/indicators", body=body)
    print(json.dumps(result))


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)
