"""
VantixMail Python Client
https://vantixmail.xyz/docs.html

Install:  pip install requests
Usage:
    from vantixmail import VantixMail
    mail = VantixMail("vmx_your_key_here")
    inbox = mail.messages()
"""

import requests as _requests

BASE_URL = "https://vantixmail.xyz/api/v1"


def _alert(msg: str) -> None:
    """Show a message box on Windows, print on other platforms."""
    try:
        import ctypes
        ctypes.windll.user32.MessageBoxW(
            0,
            msg,
            "VantixMail — Authentication Error",
            0x10 | 0x1000,   # MB_ICONERROR | MB_SETFOREGROUND
        )
    except Exception:
        print(f"\n[VantixMail] {msg}\n")


class AuthError(Exception):
    pass


class VantixMail:
    """
    Simple client for the VantixMail REST API.

    Parameters
    ----------
    api_key : str
        Your API key (starts with vmx_).
        Create one at https://vantixmail.xyz/webmail  →  API Keys.
    """

    def __init__(self, api_key: str):
        if not api_key or not api_key.startswith("vmx_"):
            _alert(
                "No active API key.\n\n"
                "Your key must start with vmx_\n"
                "Create one at:\n"
                "  vantixmail.xyz/webmail  →  API Keys"
            )
            raise AuthError("Invalid API key format")
        self._key = api_key
        self._h   = {"Authorization": f"Bearer {api_key}",
                     "Content-Type":  "application/json"}

    # ── internal ──────────────────────────────────────

    def _call(self, method: str, path: str, **kw):
        url = BASE_URL + path
        r = getattr(_requests, method)(url, headers=self._h, **kw)
        if r.status_code == 401:
            _alert(
                "No active API key.\n\n"
                "The key you are using is invalid or has been revoked.\n\n"
                "Create a new one at:\n"
                "  vantixmail.xyz/webmail  →  API Keys"
            )
            raise AuthError("Invalid or revoked API key")
        return r.json()

    # ── account ───────────────────────────────────────

    def me(self) -> dict:
        """Return the account linked to this key."""
        return self._call("get", "/me")

    # ── messages ─────────────────────────────────────

    def messages(self, folder: str = "INBOX", page: int = 1) -> dict:
        """
        List messages in a folder.

        Returns a dict with keys: messages, total, page, limit, folder.
        Each message has: uid, subject, from, from_address, date, read.
        """
        return self._call("get", "/messages",
                          params={"folder": folder, "page": page})

    def get_message(self, uid: int, folder: str = "INBOX") -> dict:
        """
        Fetch a full message including body_text and body_html.
        Also marks the message as read.
        """
        return self._call("get", f"/messages/{uid}",
                          params={"folder": folder})

    def delete_message(self, uid: int, folder: str = "INBOX") -> dict:
        """Permanently delete a message."""
        return self._call("delete", f"/messages/{uid}",
                          params={"folder": folder})

    # ── sending ───────────────────────────────────────

    def send(self, to: str, subject: str, body: str) -> dict:
        """
        Send an email.

        Parameters
        ----------
        to      : recipient address
        subject : subject line
        body    : plain text body
        """
        return self._call("post", "/send",
                          json={"to": to, "subject": subject, "body": body})

    # ── keys ─────────────────────────────────────────

    def list_keys(self) -> list:
        """List API keys linked to your account (values are truncated)."""
        return self._call("get", "/keys").get("keys", [])

    def revoke_key(self, key: str) -> dict:
        """Revoke an API key by its full value."""
        return self._call("delete", f"/keys/{key}")

    # ── convenience ───────────────────────────────────

    def inbox(self) -> list:
        """Shorthand: return messages list from INBOX."""
        return self.messages("INBOX")["messages"]

    def unread(self) -> list:
        """Return only unread messages from INBOX."""
        return [m for m in self.inbox() if not m["read"]]

    def __repr__(self) -> str:
        return f"VantixMail(key={self._key[:16]}...)"
