from __future__ import annotations

import asyncio

from app.core.config import get_settings
from app.core.logging import get_logger
from app.modules.compute_gateway.sync import poll_compute_jobs_once


logger = get_logger(__name__)


async def run_compute_poller() -> None:
    settings = get_settings()
    if settings.compute_mode == "simulator" or settings.compute_status_sync_mode != "polling":
        logger.info("compute poller disabled", extra={"compute_mode": settings.compute_mode})
        return

    interval = max(3, settings.compute_poll_interval_seconds)
    logger.info("compute poller started", extra={"interval_seconds": interval})
    while True:
        try:
            result = await poll_compute_jobs_once()
            if result["synced"] or result["failed"]:
                logger.info("compute jobs polled", extra={"result": result})
        except asyncio.CancelledError:
            logger.info("compute poller stopped")
            raise
        except Exception as exc:  # noqa: BLE001 - keep background polling alive
            logger.exception("compute poller failed", extra={"error": str(exc)})
        await asyncio.sleep(interval)
