"""scheduled-email — auto-rotating secret & email delivery service.

Quick start::

    from scheduled_email import start
    start()  # blocks current thread's timer; call stop() to cancel

Or as a context manager::

    from scheduled_email import ScheduledEmailService
    with ScheduledEmailService() as svc:
        ...

Environment variables (optional except SMTP user/pass and recipient):

    SCHEDMAIL_BASE_URL       — prefix for the login link (default: https://example.com/login?token=)
    SCHEDMAIL_ROTATE_HOURS   — rotation interval in hours (default: 24)
    SCHEDMAIL_SCT            — SCT constant (default: *****-daiju)
    SCHEDMAIL_SMTP_HOST      — SMTP server (default: smtp.163.com)
    SCHEDMAIL_SMTP_PORT      — SMTP port (default: 465)
    SCHEDMAIL_SMTP_USER      — sender email address  ← required
    SCHEDMAIL_SMTP_PASS      — sender SMTP password  ← required
    SCHEDMAIL_RECIPIENT      — recipient email address  ← required
    SCHEDMAIL_MASK_SECRET    — "true" to mask secret in emails (default: false)
"""

from __future__ import annotations

from ._config import ScheduledEmailConfig
from ._scheduler import ScheduledEmailService

__all__ = ["ScheduledEmailConfig", "ScheduledEmailService", "start", "stop"]

_default_service: ScheduledEmailService | None = None


def start(cfg: ScheduledEmailConfig | None = None) -> ScheduledEmailService:
    """Create and start the global ScheduledEmailService singleton.

    Returns the running service instance.
    """
    global _default_service
    if _default_service is not None and _default_service._running:
        return _default_service
    _default_service = ScheduledEmailService(cfg)
    _default_service.start()
    return _default_service


def stop() -> None:
    """Stop the global ScheduledEmailService if running."""
    global _default_service
    if _default_service is not None:
        _default_service.stop()
        _default_service = None
