"""Python 3.10+, standard library only. Never print keys or mailbox tokens."""
import json
import os
import re
import sys
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen

key = os.environ.get("RAPIDAPI_KEY")
host = os.environ.get(
    "RAPIDAPI_HOST", "10minutesmail-temporary-email-api.p.rapidapi.com"
)
if not key or not re.fullmatch(r"[a-z0-9.-]+\.p\.rapidapi\.com", host):
    raise RuntimeError("Set RAPIDAPI_KEY and the marketplace RAPIDAPI_HOST.")


def call(path, method="GET", token=None):
    headers = {"X-RapidAPI-Key": key, "X-RapidAPI-Host": host}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    if method == "POST":
        headers["Content-Length"] = "0"
    # POST deliberately has no data: this API does not accept a JSON body.
    request = Request(f"https://{host}{path}", method=method, headers=headers)
    try:
        with urlopen(request, timeout=20) as response:
            return None if response.status == 204 else json.load(response)
    except HTTPError as error:
        body = error.read().decode("utf-8", errors="replace")
        raise RuntimeError(f"API {error.code}: {body}") from error


mailbox = None
try:
    print("Daily budget:", call("/usage"))
    mailbox = call("/mailboxes", "POST")
    print("Send your own synthetic email to:", mailbox["address"])
    print("Waiting up to two minutes; polling every 15 seconds.")
    for _ in range(8):
        time.sleep(15)
        inbox = call(f"/mailboxes/{mailbox['id']}/messages", token=mailbox["token"])
        if not inbox["messages"]:
            continue
        message_id = inbox["messages"][0]["id"]
        detail = call(
            f"/mailboxes/{mailbox['id']}/messages/{message_id}",
            token=mailbox["token"],
        )
        print("Received test message:", {"subject": detail["subject"], "text": detail["text"]})
        break
    else:
        print("No email arrived during this polling window.")
finally:
    if mailbox:
        had_error = sys.exc_info()[0] is not None
        try:
            call(f"/mailboxes/{mailbox['id']}", "DELETE", mailbox["token"])
            print("Access closed. Backend records are retained.")
        except Exception as cleanup_error:
            print(f"Could not close inbox: {cleanup_error}", file=sys.stderr)
            if not had_error:
                raise
