"""PikaMail receive-only API example. Python 3.10+, standard library only.

Set PIKAMAIL_API_KEY. Run `python pikamail.py list` to find inbox IDs.
Set PIKAMAIL_INBOX_ID and run `python pikamail.py read` to fetch messages.
For `create`, also set PIKAMAIL_NEW_PASSWORD. Keep recovery codes private.
"""
import json
import os
import sys
from urllib.error import HTTPError
from urllib.parse import quote
from urllib.request import Request, urlopen

BASE = "https://pikamail.life/api/v1"
KEY = os.environ["PIKAMAIL_API_KEY"]


def api(method, path, payload=None):
    data = None if payload is None else json.dumps(payload).encode("utf-8")
    request = Request(
        BASE + path,
        data=data,
        method=method,
        headers={
            "Authorization": f"Bearer {KEY}",
            "Content-Type": "application/json",
        },
    )
    try:
        with urlopen(request, timeout=15) as response:
            return json.load(response)
    except HTTPError as error:
        detail = error.read(4096).decode("utf-8", "replace")
        raise SystemExit(f"HTTP {error.code}: {detail}") from error


def main():
    command = sys.argv[1] if len(sys.argv) > 1 else "list"
    if command == "list":
        for inbox in api("GET", "/inboxes")["inboxes"]:
            print(inbox["id"], inbox["address"])
    elif command == "create":
        password = os.environ["PIKAMAIL_NEW_PASSWORD"]
        payload = {"password": password}
        if os.environ.get("PIKAMAIL_DOMAIN"):
            payload["domain"] = os.environ["PIKAMAIL_DOMAIN"]
        created = api("POST", "/inboxes", payload)
        print("Address:", created["address"])
        print("Recovery code (save privately; shown once):", created["recoveryCode"])
    elif command == "read":
        inbox_id = quote(os.environ["PIKAMAIL_INBOX_ID"], safe="")
        page = api("GET", f"/inboxes/{inbox_id}/messages?limit=25")
        for item in page["messages"]:
            message_id = quote(item["id"], safe="")
            message = api("GET", f"/inboxes/{inbox_id}/messages/{message_id}")
            print("From:", message["from"])
            print("Subject:", message["subject"])
            print(message.get("text") or "[No plain-text body]")
            print("---")
        if page["nextBefore"] is not None:
            print("More messages: request ?before=", page["nextBefore"], sep="")
    else:
        raise SystemExit("Usage: python pikamail.py [list|create|read]")


if __name__ == "__main__":
    main()
