"""Background poller for scheduled team campaign events."""
from __future__ import annotations

import asyncio
from typing import Any

from logos_adk.team import Team


class Chronos:
    """Persistent background runner that wakes up due team events over time."""

    def __init__(
        self,
        team: Team,
        *,
        poll_interval_seconds: float = 1.0,
    ) -> None:
        self._team = team
        self._poll_interval_seconds = max(0.01, float(poll_interval_seconds))
        self._task: asyncio.Task[Any] | None = None
        self._stop_event = asyncio.Event()

    @property
    def team(self) -> Team:
        return self._team

    @property
    def running(self) -> bool:
        return self._task is not None and not self._task.done()

    async def run_once(self) -> None:
        """Poll the team once and process any due scheduled work."""
        await self._team.run_rounds()

    async def run_forever(self) -> None:
        """Continuously poll the team until stopped."""
        self._stop_event.clear()
        while not self._stop_event.is_set():
            await self.run_once()
            try:
                await asyncio.wait_for(self._stop_event.wait(), timeout=self._poll_interval_seconds)
            except asyncio.TimeoutError:
                continue

    def start(self) -> asyncio.Task[Any]:
        """Start the background poller in the current event loop."""
        if self.running:
            assert self._task is not None
            return self._task
        self._stop_event.clear()
        self._task = asyncio.create_task(self.run_forever())
        return self._task

    async def stop(self) -> None:
        """Stop the background poller and wait for shutdown."""
        self._stop_event.set()
        if self._task is None:
            return
        task = self._task
        self._task = None
        await task


__all__ = ["Chronos"]
