import logging

from apscheduler.schedulers.asyncio import AsyncIOScheduler

from app.services.scheduler_log import log_task_result
from app.services import task_center_service


log = logging.getLogger("qycw.agent.lifecycle.scheduler")

SCHEDULER_TICK_SECONDS = 3600
BATCH_LIMIT = 200

_scheduler: AsyncIOScheduler | None = None


async def _job_evaluate_agents() -> None:
    result = await task_center_service.run_task("agent_lifecycle_evaluate", trigger_type="schedule")
    log_task_result(
        log,
        "agent lifecycle evaluation",
        result,
        activity_keys=("observe", "restore_active", "downgrade", "return_member", "risk_locked", "failed"),
    )


def start_agent_lifecycle_scheduler() -> None:
    global _scheduler
    if _scheduler and _scheduler.running:
        return
    _scheduler = AsyncIOScheduler(timezone="Asia/Shanghai")
    _scheduler.add_job(
        _job_evaluate_agents,
        "interval",
        seconds=SCHEDULER_TICK_SECONDS,
        id="agent_lifecycle_evaluate",
        replace_existing=True,
        max_instances=1,
        coalesce=True,
    )
    _scheduler.start()
    log.debug("agent lifecycle scheduler started: tick=%ss", SCHEDULER_TICK_SECONDS)


def shutdown_agent_lifecycle_scheduler() -> None:
    global _scheduler
    if _scheduler and _scheduler.running:
        _scheduler.shutdown(wait=False)
    _scheduler = None
