"""AwoooP Ansible check-mode worker loop.

Runs only when explicitly enabled by settings. The worker consumes pending
``ansible_candidate_matched`` rows and records check-mode evidence; it never
executes Ansible apply.
"""

from __future__ import annotations

import asyncio

import structlog

from src.core.config import settings
from src.services.awooop_ansible_check_mode_service import run_pending_check_modes_once

logger = structlog.get_logger(__name__)


async def run_awooop_ansible_check_mode_loop() -> None:
    if not settings.ENABLE_AWOOOP_ANSIBLE_CHECK_MODE_WORKER:
        logger.info("awooop_ansible_check_mode_worker_disabled")
        return

    logger.info(
        "awooop_ansible_check_mode_worker_started",
        interval_seconds=settings.AWOOOP_ANSIBLE_CHECK_MODE_INTERVAL_SECONDS,
        batch_limit=settings.AWOOOP_ANSIBLE_CHECK_MODE_BATCH_LIMIT,
        timeout_seconds=settings.AWOOOP_ANSIBLE_CHECK_MODE_TIMEOUT_SECONDS,
    )
    await asyncio.sleep(settings.AWOOOP_ANSIBLE_CHECK_MODE_STARTUP_SLEEP_SECONDS)

    while True:
        try:
            result = await run_pending_check_modes_once(
                limit=settings.AWOOOP_ANSIBLE_CHECK_MODE_BATCH_LIMIT,
                timeout_seconds=settings.AWOOOP_ANSIBLE_CHECK_MODE_TIMEOUT_SECONDS,
            )
            if result.get("claimed") or result.get("blockers"):
                logger.info("awooop_ansible_check_mode_worker_tick", **result)
        except Exception as exc:
            logger.warning("awooop_ansible_check_mode_worker_failed", error=str(exc))

        await asyncio.sleep(settings.AWOOOP_ANSIBLE_CHECK_MODE_INTERVAL_SECONDS)
