import base64, json, os, sys, urllib.parse, urllib.request, urllib.error
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

TOKEN_URL = "https://oauth2.googleapis.com/token"
API = "https://gmail.googleapis.com/gmail/v1/users/me"


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


def _token():
    cfg = _cfg()
    refresh = str(cfg.get("refresh_token") or "")
    if not refresh:
        raise Exception("refresh_token is not set — run gmail-single-user-exchange-code and paste it into the config")
    data = urllib.parse.urlencode({
        "client_id": str(cfg.get("client_id") or ""),
        "client_secret": str(cfg.get("client_secret") or ""),
        "refresh_token": refresh,
        "grant_type": "refresh_token",
    }).encode("utf-8")
    req = urllib.request.Request(TOKEN_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 refresh failed: " + json.dumps(tok))
    return tok["access_token"]


def request(method, path, params=None, body=None):
    url = 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()}
    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 build_raw(cfg, inputs, in_reply_to=None, references=None):
    body = inputs.get("body")
    html = inputs.get("html_body")
    att_name = inputs.get("attachment_name")
    att_b64 = inputs.get("attachment_base64")
    has_att = bool(att_name and att_b64)

    def body_part():
        if body and html:
            alt = MIMEMultipart("alternative")
            alt.attach(MIMEText(body, "plain", "utf-8"))
            alt.attach(MIMEText(html, "html", "utf-8"))
            return alt
        if html:
            return MIMEText(html, "html", "utf-8")
        return MIMEText(body or "", "plain", "utf-8")

    if has_att:
        msg = MIMEMultipart("mixed")
        msg.attach(body_part())
        part = MIMEBase("application", "octet-stream")
        part.set_payload(base64.b64decode(att_b64))
        encoders.encode_base64(part)
        part.add_header("Content-Disposition", "attachment", filename=str(att_name))
        msg.attach(part)
    else:
        msg = body_part()

    msg["to"] = str(inputs.get("to") or "")
    if inputs.get("cc"):
        msg["cc"] = str(inputs["cc"])
    if inputs.get("bcc"):
        msg["bcc"] = str(inputs["bcc"])
    msg["subject"] = str(inputs.get("subject") or "")
    msg["from"] = str(cfg.get("send_as") or cfg.get("email") or "")
    if inputs.get("reply_to"):
        msg["reply-to"] = str(inputs["reply_to"])
    if in_reply_to:
        msg["In-Reply-To"] = str(in_reply_to)
    if references:
        msg["References"] = str(references)
    return base64.urlsafe_b64encode(msg.as_bytes()).decode("ascii")


def main():
    cfg = _cfg()
    inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
    if not str(inputs.get("to") or ""):
        raise Exception("to is required")
    raw = build_raw(cfg, inputs)
    print(json.dumps(request("POST", "/messages/send", body={"raw": raw})))


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)
