"""Task scheduler: checks pending/watch tasks and triggers them."""

from __future__ import annotations

import asyncio
import logging
from datetime import UTC, datetime
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from agntspace.journal.service import JournalService
    from agntspace.tasks.service import TaskService

log = logging.getLogger(__name__)


class TaskScheduler:
    """Checks pending and watch tasks, triggers when conditions are met."""

    def __init__(
        self,
        task_service: TaskService,
        journal: JournalService,
        interval_seconds: int = 180,
    ) -> None:
        self._task_service = task_service
        self._journal = journal
        self._interval = interval_seconds
        self._task: asyncio.Task | None = None  # type: ignore[type-arg]
        self._running = False

    def start(self) -> None:
        if self._running:
            return
        self._running = True
        self._task = asyncio.create_task(self._loop())
        log.debug("Task scheduler started (interval: %ds)", self._interval)

    def stop(self) -> None:
        self._running = False
        if self._task:
            self._task.cancel()
            self._task = None

    async def check_tasks(self) -> list[str]:
        """Check for tasks that should be triggered. Returns list of actions taken."""
        actions: list[str] = []
        today = datetime.now(UTC).strftime("%Y-%m-%d")

        try:
            tasks = self._task_service.list_tasks()
        except Exception:
            return actions

        for t in tasks:
            status = t.get("status", "")
            due = t.get("due", "")

            # Auto-start delegated tasks that are due
            if status == "delegated" and due and due <= today:
                try:
                    self._task_service.update_status(t["slug"], "in_progress")
                    action = f"Auto-started task '{t.get('title', '?')}' (due: {due})"
                    actions.append(action)
                    self._journal.append_observation(action)
                except Exception:
                    pass

        return actions

    async def _loop(self) -> None:
        while self._running:
            try:
                await self.check_tasks()
            except asyncio.CancelledError:
                break
            except Exception:
                log.exception("Scheduler error")
            await asyncio.sleep(self._interval)
