"""Primitif Mail — email for AI agents.

Usage::

    from primitif import mail

    mb = mail.create_mailbox(name="agent")
    mb.send(to="user@example.com", subject="Hi", body_text="Hello")

    for msg in mb.inbox():
        detail = mb.read(msg.id)
        mb.reply(msg.id, body_text="Got it!")

    mb.delete()
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from primitif.mail.client import Mailbox, MailAdmin
from primitif.mail.exceptions import (
    MailAuthError,
    MailConflictError,
    MailNetworkError,
    MailError,
    MailNotFoundError,
    MailRateLimitError,
    MailServerError,
    MailValidationError,
)
from primitif.mail.models import (
    AccountInfo,
    AllowlistEntry,
    AttachmentInfo,
    CustomDomain,
    InboxMessage,
    MailboxInfo,
    MailboxListItem,
    MessageDetail,
    PlanLimits,
    ProtectedRecipient,
    SendResult,
    ThreadDetail,
    ThreadSummary,
    WebhookCreated,
    WebhookInfo,
)

if TYPE_CHECKING:
    from primitif._models import PaginatedList


# ---------------------------------------------------------------------------
# Lazy admin client — created on first use from PRIMITIF_API_KEY env var
# ---------------------------------------------------------------------------

_admin: MailAdmin | None = None


def _get_admin() -> MailAdmin:
    global _admin
    if _admin is None:
        from primitif.client import Primitif
        _admin = Primitif().mail
    return _admin


# ---------------------------------------------------------------------------
# Module-level functions — the simple import path
# ---------------------------------------------------------------------------


def create_mailbox(name: str | None = None, ttl: int | None = None, domain_id: str | None = None) -> Mailbox:
    """Create a mailbox. Returns a Mailbox ready to send and receive.

    Args:
        name: Mailbox name (used in address prefix). Omit for random.
        ttl: Optional TTL in seconds (max 30 days).
        domain_id: Optional custom domain ID.

    Example:
        >>> from primitif import mail
        >>> mb = mail.create_mailbox(name="agent")
        >>> print(mb.address)
    """
    return _get_admin().create_mailbox(name=name, ttl=ttl, domain_id=domain_id)


def list_mailboxes(*, limit: int = 20, cursor: str | None = None) -> PaginatedList[MailboxListItem]:
    """List all mailboxes in the namespace.

    Example:
        >>> for mb in mail.list_mailboxes():
        ...     print(mb.address, mb.received_count)
    """
    return _get_admin().list_mailboxes(limit=limit, cursor=cursor)


def delete_mailbox(mailbox_id: str) -> None:
    """Delete a mailbox by ID.

    Example:
        >>> mail.delete_mailbox("mb_...")
    """
    _get_admin().delete_mailbox(mailbox_id)


def account() -> AccountInfo:
    """Get account info (plan, usage, limits).

    Example:
        >>> info = mail.account()
        >>> print(info.plan, info.email_count)
    """
    return _get_admin().account()


def add_protected_recipient(pattern: str) -> ProtectedRecipient:
    """Add a protected recipient pattern (email or @domain).

    Example:
        >>> mail.add_protected_recipient("ceo@bigcorp.com")
    """
    return _get_admin().add_protected_recipient(pattern)


def list_protected_recipients() -> list[ProtectedRecipient]:
    """List all protected recipient patterns."""
    return _get_admin().list_protected_recipients()


def remove_protected_recipient(entry_id: str) -> None:
    """Remove a protected recipient pattern."""
    _get_admin().remove_protected_recipient(entry_id)


def add_custom_domain(domain: str) -> CustomDomain:
    """Register a custom email domain. Returns DNS records to add.

    Example:
        >>> domain = mail.add_custom_domain("yourcompany.com")
        >>> print(domain.dns_records)
    """
    return _get_admin().add_custom_domain(domain)


def verify_custom_domain(domain_id: str) -> CustomDomain:
    """Trigger DNS verification for a custom domain."""
    return _get_admin().verify_custom_domain(domain_id)


def list_custom_domains() -> list[CustomDomain]:
    """List all custom domains."""
    return _get_admin().list_custom_domains()


def set_default_domain(domain_id: str) -> CustomDomain:
    """Set a verified domain as the default for new mailboxes."""
    return _get_admin().set_default_domain(domain_id)


def clear_default_domain() -> None:
    """Clear the default domain."""
    _get_admin().clear_default_domain()


def delete_custom_domain(domain_id: str) -> None:
    """Delete a custom domain."""
    _get_admin().delete_custom_domain(domain_id)


__all__ = [
    # Module-level functions
    "create_mailbox",
    "list_mailboxes",
    "delete_mailbox",
    "account",
    "add_protected_recipient",
    "list_protected_recipients",
    "remove_protected_recipient",
    "add_custom_domain",
    "verify_custom_domain",
    "list_custom_domains",
    "set_default_domain",
    "clear_default_domain",
    "delete_custom_domain",
    # Classes
    "Mailbox",
    # Exceptions
    "MailError",
    "MailAuthError",
    "MailNetworkError",
    "MailNotFoundError",
    "MailConflictError",
    "MailValidationError",
    "MailRateLimitError",
    "MailServerError",
    # Models
    "AccountInfo",
    "AllowlistEntry",
    "AttachmentInfo",
    "CustomDomain",
    "InboxMessage",
    "MailboxInfo",
    "MailboxListItem",
    "MessageDetail",
    "PlanLimits",
    "ProtectedRecipient",
    "SendResult",
    "ThreadDetail",
    "ThreadSummary",
    "WebhookCreated",
    "WebhookInfo",
]
