"""Daily APScheduler cron for the auto-pin scan.

Single global job at 03:00 UTC. Runs scan_all_users_for_auto_pins so the
system promotes stable note versions before they get aged out of the
rolling cap. Off-hours by design — the scan is cheap but not time-
critical and doesn't need to interrupt regular activity.

One ScheduledJob (services/scheduler.py), like the other *_scheduler modules.
"""
from __future__ import annotations

import asyncio
import logging

from apscheduler.triggers.cron import CronTrigger

from scribe.services.scheduler import ScheduledJob
from scribe.services.version_pinning import scan_all_users_for_auto_pins

logger = logging.getLogger(__name__)


async def _run_scan() -> None:
    results = await scan_all_users_for_auto_pins()
    total = sum(results.values())
    if total > 0:
        logger.info(
            "auto-pin scan: pinned %d version(s) across %d user(s)",
            total, len(results),
        )
    else:
        logger.debug("auto-pin scan: no new pins")


_JOB = ScheduledJob("version_pinning_auto_scan", _run_scan, label="Version pinning")


def start_version_pinning_scheduler(loop: asyncio.AbstractEventLoop) -> None:
    _JOB.start(loop, CronTrigger(hour=3, minute=0, timezone="UTC"), describe="daily 03:00 UTC")


def stop_version_pinning_scheduler() -> None:
    _JOB.stop()
