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

GRAPH = "https://graph.microsoft.com/v1.0"


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


def _inputs():
    return json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))


def _token(cfg):
    tenant = str(cfg.get("tenant_id", ""))
    url = "https://login.microsoftonline.com/" + tenant + "/oauth2/v2.0/token"
    form = urllib.parse.urlencode({
        "grant_type": "client_credentials",
        "client_id": str(cfg.get("client_id", "")),
        "client_secret": str(cfg.get("client_secret", "")),
        "scope": "https://graph.microsoft.com/.default",
    }).encode("utf-8")
    req = urllib.request.Request(url, data=form, headers={"Content-Type": "application/x-www-form-urlencoded"}, 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 graph(method, path, token, body=None, params=None):
    url = GRAPH + path
    if params:
        clean = {k: v for k, v in params.items() if v not in (None, "")}
        if clean:
            url += "?" + urllib.parse.urlencode(clean)
    data = json.dumps(body).encode("utf-8") if body is not None else None
    headers = {"Authorization": "Bearer " + token, "Accept": "application/json"}
    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 _run(fn):
    try:
        cfg = _cfg()
        inputs = _inputs()
        token = _token(cfg)
        print(json.dumps(fn(token, inputs)))
    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)


q = lambda v: urllib.parse.quote(str(v), safe="")


def _odata_escape(v):
    return str(v).replace("'", "''")


def main(token, inputs):
    mailbox = inputs.get("mailbox")
    if not mailbox:
        raise Exception("mailbox is required")

    subject = inputs.get("subject")
    from_address = inputs.get("from_address")
    search = inputs.get("search")
    limit = int(inputs.get("limit") or 25)

    if search:
        params = {"$search": '"' + search + '"', "$top": limit}
    elif subject or from_address:
        parts = []
        if subject:
            parts.append("subject eq '" + _odata_escape(subject) + "'")
        if from_address:
            parts.append("from/emailAddress/address eq '" + _odata_escape(from_address) + "'")
        params = {"$filter": " and ".join(parts), "$top": limit}
    else:
        params = {"$top": limit}

    return graph("GET", "/users/" + q(mailbox) + "/messages", token, params=params)


_run(main)
