"""Background asyncio poller for inbound mail automation."""

from __future__ import annotations

import asyncio
import logging

from app.config import settings
from app.database import SessionLocal
from app.inbound_mail import get_or_create_rules, run_inbound_poll

logger = logging.getLogger("inbound_poller")


async def inbound_mail_poll_loop(stop_event: asyncio.Event) -> None:
    """Poll on an interval while the API process is alive."""
    if not settings.inbound_mail_enabled:
        logger.info("INBOUND_MAIL_ENABLED is false — poller not started")
        return

    # First delay so startup/migrations settle
    await asyncio.sleep(5)

    while not stop_event.is_set():
        interval = settings.inbound_mail_poll_seconds or 120

        def _tick() -> int:
            """Run sync DB + Gmail work off the event loop; return next interval."""
            db = SessionLocal()
            try:
                rules = get_or_create_rules(db)
                next_interval = max(30, int(rules.poll_interval_seconds or interval))
                if rules.enabled:
                    result = run_inbound_poll(db, force=False)
                    logger.info("Inbound poll: %s", result.get("message"))
                return next_interval
            finally:
                db.close()

        try:
            interval = await asyncio.to_thread(_tick)
        except Exception:  # noqa: BLE001
            logger.exception("Inbound poller iteration failed")

        try:
            await asyncio.wait_for(stop_event.wait(), timeout=interval)
            break
        except asyncio.TimeoutError:
            continue
