"""MailCraft quickstart in Python: standard library only (Python 3.8+).

Creates an inbox, emails you from it, waits for your reply on the event feed,
reads the thread and answers. It sends real mail.

    export MAILCRAFT_API_KEY=mc_live_...
    export MY_EMAIL=you@example.com
    python3 quickstart.py
"""

import json
import os
import time
import urllib.error
import urllib.request
import uuid

API = "https://api.mailcraft.ntconnect.com"
KEY = os.environ["MAILCRAFT_API_KEY"]


def call(method, path, body=None, idempotent=False):
    headers = {"Authorization": "Bearer " + KEY}
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode()
    if idempotent:
        headers["Idempotency-Key"] = str(uuid.uuid4())
    req = urllib.request.Request(API + path, data=data, method=method, headers=headers)
    try:
        with urllib.request.urlopen(req) as res:
            return json.load(res)
    except urllib.error.HTTPError as e:
        problem = json.load(e)  # every error is application/problem+json
        raise SystemExit(f"{e.code} {problem['title']}: {problem.get('detail', '')}")


# 2. Create an inbox.
inbox = call("POST", "/v0/inboxes", {"displayName": "Quickstart"})
print("inbox:", inbox["address"])

# Read the event feed from its newest event on.
newest = call("GET", "/v0/events?order=desc&limit=1")["data"]
since = newest[0]["id"] if newest else None

# 5. Send a message.
sent = call(
    "POST",
    "/v0/inboxes/" + inbox["id"] + "/messages",
    {
        "to": [os.environ["MY_EMAIL"]],
        "subject": "Hello from MailCraft",
        "text": "Reply to this email and the quickstart will answer.",
    },
    idempotent=True,
)
print("sent:", sent["id"])

# 3. Wait for your reply on the event feed (a webhook is the other way).
received = None
deadline = time.time() + 600
while received is None and time.time() < deadline:
    time.sleep(5)
    page = call("GET", "/v0/events" + ("?since=" + since if since else ""))
    for event in page["data"]:
        since = event["id"]
        if event["type"] == "message.received" and event["data"]["inbox_id"] == inbox["id"]:
            received = event["data"]
            break
if received is None:
    raise SystemExit("No reply within 10 minutes.")

# 4. Read the thread and the message.
thread = call("GET", "/v0/threads/" + received["thread_id"])
message = call("GET", "/v0/messages/" + received["message_id"])
print(len(thread["messages"]), "messages in the thread; you wrote:", message["text"])

# 6. Reply.
answer = call(
    "POST",
    "/v0/messages/" + received["message_id"] + "/reply",
    {"text": "Thanks, on it."},
    idempotent=True,
)
print("replied:", answer["id"])
